Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(extension): add a manual Web Clipper store submission workflow

tianma-ifc58fe81a13ea
diff --git a/.github/workflows/extension-build.yml b/.github/workflows/extension-build.yml
index 2ad59c1a..3039b38d 100644
--- a/.github/workflows/extension-build.yml
+++ b/.github/workflows/extension-build.yml
@@ -6,7 +6,10 @@ on:
- "apps/extension/**"
- "package.json"
- "bun.lock"
+ - "scripts/publish-web-clipper.mjs"
+ - "scripts/publish-web-clipper.test.mjs"
- ".github/workflows/extension-build.yml"
+ - ".github/workflows/extension-store.yml"
push:
branches:
- main
@@ -14,7 +17,10 @@ on:
- "apps/extension/**"
- "package.json"
- "bun.lock"
+ - "scripts/publish-web-clipper.mjs"
+ - "scripts/publish-web-clipper.test.mjs"
- ".github/workflows/extension-build.yml"
+ - ".github/workflows/extension-store.yml"
workflow_dispatch:
permissions:
@@ -39,6 +45,9 @@ jobs:
- name: Test extension manifests
run: bun run test:extension
+ - name: Test store submission
+ run: bun test scripts/publish-web-clipper.test.mjs
+
- name: Build Chromium extension
run: bun run build:extension
diff --git a/.github/workflows/extension-store.yml b/.github/workflows/extension-store.yml
new file mode 100644
index 00000000..06b0c2c4
--- /dev/null
+++ b/.github/workflows/extension-store.yml
@@ -0,0 +1,83 @@
+name: Submit Web Clipper
+
+on:
+ workflow_dispatch:
+ inputs:
+ platform:
+ description: "Store to submit. Chrome also covers the Edge install link."
+ required: true
+ default: both
+ type: choice
+ options:
+ - both
+ - chrome
+ - firefox
+ release_notes:
+ description: "Firefox release notes. Leave empty for a one-line version note."
+ required: false
+ default: ""
+ type: string
+ dry_run:
+ description: "Build the packages without calling the stores"
+ required: true
+ default: false
+ type: boolean
+
+permissions:
+ contents: read
+
+concurrency:
+ group: edgeever-web-clipper-store
+ cancel-in-progress: false
+
+jobs:
+ submit:
+ if: github.repository == 'tianma-if/edgeever'
+ name: Submit Chrome and Firefox
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v5
+
+ - name: Set up Bun
+ uses: oven-sh/setup-bun@v2
+
+ - name: Install dependencies
+ run: bun install --frozen-lockfile
+
+ - name: Write release notes
+ env:
+ RELEASE_NOTES: ${{ inputs.release_notes }}
+ run: printf '%s' "$RELEASE_NOTES" > "$RUNNER_TEMP/web-clipper-release-notes.txt"
+
+ - name: Submit stores
+ id: submit
+ env:
+ PLATFORM: ${{ inputs.platform }}
+ DRY_RUN: ${{ inputs.dry_run }}
+ CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON: ${{ secrets.CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON }}
+ CHROME_WEB_STORE_CLIENT_ID: ${{ secrets.CHROME_WEB_STORE_CLIENT_ID }}
+ CHROME_WEB_STORE_CLIENT_SECRET: ${{ secrets.CHROME_WEB_STORE_CLIENT_SECRET }}
+ CHROME_WEB_STORE_REFRESH_TOKEN: ${{ secrets.CHROME_WEB_STORE_REFRESH_TOKEN }}
+ AMO_JWT_ISSUER: ${{ secrets.AMO_JWT_ISSUER }}
+ AMO_JWT_SECRET: ${{ secrets.AMO_JWT_SECRET }}
+ EDGE_EVER_REVIEW_INSTANCE_URL: ${{ secrets.EDGE_EVER_REVIEW_INSTANCE_URL }}
+ EDGE_EVER_REVIEW_API_TOKEN: ${{ secrets.EDGE_EVER_REVIEW_API_TOKEN }}
+ run: |
+ args=(--platform "$PLATFORM" --notes-file "$RUNNER_TEMP/web-clipper-release-notes.txt")
+ if [[ "$DRY_RUN" == "true" ]]; then
+ args+=(--dry-run)
+ fi
+ bun scripts/publish-web-clipper.mjs "${args[@]}"
+
+ - name: Upload submission packages
+ if: always() && steps.submit.outputs.version != ''
+ uses: actions/upload-artifact@v4
+ with:
+ name: web-clipper-${{ steps.submit.outputs.version }}
+ if-no-files-found: warn
+ path: |
+ ${{ steps.submit.outputs.chromium_zip }}
+ ${{ steps.submit.outputs.firefox_zip }}
+ ${{ steps.submit.outputs.source_zip }}
diff --git a/apps/extension/README.md b/apps/extension/README.md
index 3738905f..69a6fa3d 100644
--- a/apps/extension/README.md
+++ b/apps/extension/README.md
@@ -56,6 +56,10 @@ bun run package:extension:firefox
The archive is written to `apps/extension/web-ext-artifacts`. Firefox requires AMO signing for normal installation. The manifest supports Firefox Desktop 140 or later and Firefox for Android 142 or later so Mozilla's built-in data-transmission consent UI is available.
+## Store submission
+
+Chrome and Edge share one Chrome Web Store item. Firefox is submitted separately. From the repository root, the official workflow **Submit Web Clipper** builds and submits both. See [Web Clipper store submission](../../docs/extension-store.md). Increase the `version` in `package.json` before submitting; an uploaded version cannot be replaced.
+
## Firefox data disclosure
The Firefox package declares the data types required by its user-triggered clipping function:
diff --git a/apps/extension/SOURCE_BUILD.md b/apps/extension/SOURCE_BUILD.md
new file mode 100644
index 00000000..7015c41d
--- /dev/null
+++ b/apps/extension/SOURCE_BUILD.md
@@ -0,0 +1,26 @@
+# EdgeEver Web Clipper source
+
+This archive is the reviewable source for one Firefox Add-ons submission.
+The archive root is `edgeever-source`. It contains the extension source,
+the root package manifest, the Bun lockfile, workspace package manifests,
+and the patch files `bun install --frozen-lockfile` requires.
+
+Requirements:
+
+- Bun 1.3.14 or later
+- Node.js 20 or later, required by `web-ext`
+
+From the archive root:
+
+```sh
+bun install --frozen-lockfile
+bun run test:extension
+bun run build:extension:firefox
+bun run lint:extension:firefox
+bun run package:extension:firefox
+```
+
+The Firefox package is written to `apps/extension/web-ext-artifacts`.
+The extension reads a page only after the user chooses a clip action, then
+sends that content to the EdgeEver instance configured in the extension
+settings. Review steps are in `apps/extension/FIREFOX_STORE_LISTING.md`.
diff --git a/docs/extension-store.md b/docs/extension-store.md
new file mode 100644
index 00000000..8ef39f80
--- /dev/null
+++ b/docs/extension-store.md
@@ -0,0 +1,77 @@
+# Web Clipper store submission
+
+Chrome, Edge, and Firefox listings are submitted by the official repository
+workflow **Submit Web Clipper**. This is separate from `bun run release`.
+A product release does not upload the browser extension, and a store review
+does not change a GitHub Release.
+
+Edge users install the Chrome Web Store item
+`gjadpfmanienmlofajibkfkkpfdkclgo`. One Chrome submission covers that item.
+Firefox is a separate submission for `edgeever-web-clipper`. The workflow does
+not publish to Microsoft Edge Add-ons.
+
+The workflow builds the packages, uploads them, and submits them for review.
+It does not approve the listing. Users stay on the last approved version until
+Chrome and Mozilla each finish review. An uploaded version number cannot be
+reused. Increase `apps/extension/package.json` before submitting changes.
+
+## Run it
+
+On https://github.com/tianma-if/edgeever/actions/workflows/extension-store.yml,
+choose **Run workflow**. Leave the Firefox notes empty for a one-line version
+note, or paste the notes Mozilla should show. `dry_run` builds the packages
+and stops before calling either store.
+
+The same command runs locally after the credentials below are available in the
+environment:
+
+```sh
+bun run publish:extension -- --dry-run
+bun run publish:extension -- --notes "What changed."
+```
+
+`--platform chrome` or `--platform firefox` retries one store. A Chrome
+version that is already awaiting review is left in place. A Firefox version
+that is awaiting review and has no source archive receives the source archive
+on the next run.
+
+## Credentials
+
+Add these Actions secrets to `tianma-if/edgeever`. Forks do not run the job.
+
+Chrome accepts either a service account or a refresh token. The service
+account does not expire every few days:
+
+1. In Google Cloud, enable the Chrome Web Store API and create a service
+ account. Do not grant it extra project roles.
+2. In the Chrome Web Store developer dashboard, under Account, add that
+ service account email. The publisher can register one service account.
+3. Create a JSON key and store the whole file as
+ `CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON`.
+
+The refresh-token alternative uses `CHROME_WEB_STORE_CLIENT_ID`,
+`CHROME_WEB_STORE_CLIENT_SECRET`, and `CHROME_WEB_STORE_REFRESH_TOKEN` for
+scope `https://www.googleapis.com/auth/chromewebstore`. The Google account
+needs 2-Step Verification. An OAuth client left in testing expires its refresh
+token after seven days, so publish the consent screen or use the service
+account.
+
+Firefox uses an API key from
+https://addons.mozilla.org/developers/addon/api/key/:
+
+- `AMO_JWT_ISSUER`
+- `AMO_JWT_SECRET`
+
+These two optional secrets are added to the Firefox reviewer note:
+
+- `EDGE_EVER_REVIEW_INSTANCE_URL`
+- `EDGE_EVER_REVIEW_API_TOKEN`
+
+Chrome's upload API has no release-notes field. The Chrome listing text and
+privacy disclosure stay as they were last saved in the dashboard. Change those
+in the dashboard when the permissions or the public description change.
+Firefox receives the workflow notes as `en-US` release notes, plus the build
+steps from `apps/extension/SOURCE_BUILD.md`.
+
+The current Firefox listing uses license `AGPL-3.0-only`. The workflow sends
+that license with every version.
diff --git a/docs/extension-store.zh-CN.md b/docs/extension-store.zh-CN.md
new file mode 100644
index 00000000..351f4895
--- /dev/null
+++ b/docs/extension-store.zh-CN.md
@@ -0,0 +1,66 @@
+# 网页剪藏插件商店提交
+
+Chrome、Edge 和 Firefox 的上架由官方仓库工作流 **Submit Web Clipper** 提交。
+它和 `bun run release` 分开。产品正式发布不会上传浏览器插件,商店审核也不会
+改变 GitHub Release。
+
+Edge 用户安装的是 Chrome 网上应用店商品
+`gjadpfmanienmlofajibkfkkpfdkclgo`。一次 Chrome 提交覆盖这个商品。Firefox
+单独提交到 `edgeever-web-clipper`。这条工作流不向 Microsoft Edge 附加组件网站
+发布。
+
+工作流会构建安装包、上传并提交审核。它不能代替商店审核。用户会留在各自商店
+最后一个已通过的版本,直到 Chrome 和 Mozilla 分别审核完成。已经上传过的版本号
+不能重复使用。提交改动前要先提高 `apps/extension/package.json` 里的版本。
+
+## 运行
+
+打开 https://github.com/tianma-if/edgeever/actions/workflows/extension-store.yml,
+选择 **Run workflow**。Firefox 更新说明留空时,使用一行版本说明;也可以贴上
+希望 Mozilla 展示的说明。`dry_run` 只构建安装包,不会调用商店。
+
+本机环境里已经放好下面的凭据时,也可以直接运行:
+
+```sh
+bun run publish:extension -- --dry-run
+bun run publish:extension -- --notes "这次改了什么。"
+```
+
+`--platform chrome` 或 `--platform firefox` 可以只重试一个商店。Chrome
+上同一个版本已经在审核中时,会保持原提交。Firefox 上同一个版本正在审核但还没有
+源码包时,下一次运行会补上源码包。
+
+## 凭据
+
+把这些 Actions secrets 加到 `tianma-if/edgeever`。Fork 不会运行这个 Job。
+
+Chrome 可以使用服务账号,也可以使用 refresh token。服务账号不会过几天就失效:
+
+1. 在 Google Cloud 启用 Chrome Web Store API,并创建一个服务账号。不要给它
+ 额外的项目角色。
+2. 在 Chrome 网上应用店开发者后台的 Account 里添加这个服务账号邮箱。一个发布者
+ 只能登记一个服务账号。
+3. 创建 JSON 密钥,把整个文件存为
+ `CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON`。
+
+refresh token 这条替代路径使用 `CHROME_WEB_STORE_CLIENT_ID`、
+`CHROME_WEB_STORE_CLIENT_SECRET` 和 `CHROME_WEB_STORE_REFRESH_TOKEN`,范围是
+`https://www.googleapis.com/auth/chromewebstore`。Google 账号需要开启两步验证。
+OAuth 客户端如果停留在测试状态,refresh token 会在七天后失效,所以要把同意屏幕
+发布出去,或者改用服务账号。
+
+Firefox 使用 https://addons.mozilla.org/developers/addon/api/key/ 生成的 API 密钥:
+
+- `AMO_JWT_ISSUER`
+- `AMO_JWT_SECRET`
+
+下面两个可选 secret 会写进 Firefox 给审核员的说明:
+
+- `EDGE_EVER_REVIEW_INSTANCE_URL`
+- `EDGE_EVER_REVIEW_API_TOKEN`
+
+Chrome 的上传接口没有更新说明字段。Chrome 的商店简介和隐私披露保持后台里上次
+保存的内容。权限或公开介绍发生变化时,先在后台修改。Firefox 会把工作流里的说明
+作为 `en-US` 版本说明,并附上 `apps/extension/SOURCE_BUILD.md` 里的构建步骤。
+
+当前 Firefox 商品使用许可证 `AGPL-3.0-only`。工作流每次提交版本都会带上这个许可证。
diff --git a/docs/release.md b/docs/release.md
index 1aca8d46..cb9fa134 100644
--- a/docs/release.md
+++ b/docs/release.md
@@ -87,6 +87,10 @@ actually needed.
Issue closed; retry with
`bun run publish:stores -- --release vX.Y.Z --platform ios`. See
[Mobile Store Delivery](store-delivery.md).
+- Web Clipper store submission is a separate official-repository workflow.
+ Run **Submit Web Clipper** after increasing `apps/extension/package.json`.
+ It does not run as part of `bun run release`, and its review does not change
+ a GitHub Release. See [Web Clipper store submission](extension-store.md).
- Published desktop and Android audits read asset names and download
installers through the release API URL. `gh release view --json assets` and
`gh release download` can stay empty after a draft is published, and treating
diff --git a/docs/release.zh-CN.md b/docs/release.zh-CN.md
index a52d1bac..5baf96f0 100644
--- a/docs/release.zh-CN.md
+++ b/docs/release.zh-CN.md
@@ -74,6 +74,10 @@ bun run release -- \
GitHub Release 保持已发布,跟踪 Issue 保持已关闭;用
`bun run publish:stores -- --release vX.Y.Z --platform ios` 重试即可。详见
[移动端商店交付](store-delivery.zh-CN.md)。
+- 网页剪藏插件的商店提交是官方仓库里的独立工作流。提高
+ `apps/extension/package.json` 的版本后,运行 **Submit Web Clipper**。
+ 它不属于 `bun run release`,审核结果也不会改变 GitHub Release。详见
+ [网页剪藏插件商店提交](extension-store.zh-CN.md)。
- 公开发布后的桌面和 Android 审计通过 Release API URL 读取文件名并下载安装包。
Draft 刚公开时,`gh release view --json assets` 和 `gh release download`
可能持续看不到这些文件;如果把空列表当成资产缺失,发布会被退回 Draft。
diff --git a/package.json b/package.json
index d4bcf92b..f3516ebb 100644
--- a/package.json
+++ b/package.json
@@ -62,6 +62,7 @@
"test:release-planning": "bun test scripts/plan-native-release.test.mjs scripts/check-native-release-assets.test.mjs scripts/create-mac-update-metadata.test.mjs scripts/windows-update-metadata.test.mjs scripts/linux-update-release.test.mjs scripts/desktop-build-workflow.test.mjs scripts/pe-imports.test.mjs scripts/report-native-build-timings.test.mjs scripts/release.test.mjs scripts/validate-store-delivery.test.mjs scripts/store-delivery.test.mjs scripts/xcode-cloud-control.test.mjs scripts/download-play-universal-apk.test.mjs scripts/verify-android-apk-signature.test.mjs scripts/desktop-icns.test.mjs scripts/verify-desktop-cross-version-startup.test.mjs scripts/preview-macos-dock-icon.test.mjs apps/web/src/lib/version-check.test.mjs apps/mobile/src/lib/mobile-release.test.ts",
"release": "bun scripts/release.mjs",
"publish:stores": "bun scripts/store-delivery.mjs",
+ "publish:extension": "bun scripts/publish-web-clipper.mjs",
"test:desktop:sidecar": "bun scripts/test-desktop-sidecar.mjs",
"test:desktop": "bun test apps/desktop/src/main/account-scope.test.mjs apps/desktop/src/main/app-protocol.test.mjs apps/desktop/src/main/child-process-start.test.mjs apps/desktop/src/main/clipboard-write.test.mjs apps/desktop/src/main/desktop-diagnostics.test.mjs apps/desktop/src/main/desktop-menu.test.mjs apps/desktop/src/main/desktop-update-flow.test.mjs apps/desktop/src/main/diagnostic-log.test.mjs apps/desktop/src/main/file-association.test.mjs apps/desktop/src/main/wechat-chat-archive.test.mjs apps/desktop/src/main/wechat-share-import.test.mjs apps/desktop/src/main/share-extension-registration.test.mjs apps/desktop/src/main/windows-share-menu.test.mjs apps/desktop/src/main/file-permissions.test.mjs apps/desktop/src/main/installation-location.test.mjs apps/desktop/src/main/local-data-reset.test.mjs apps/desktop/src/main/ai-direct.test.mjs apps/desktop/src/main/plugin-public-network.test.mjs apps/desktop/src/main/renderer-recovery.test.mjs apps/desktop/src/main/renderer-hibernate.test.mjs apps/desktop/src/main/renderer-startup-guard.test.mjs apps/desktop/src/main/renderer-storage-migration.test.mjs apps/desktop/src/main/resource-request.test.mjs apps/desktop/src/main/resource-url.test.mjs apps/desktop/src/main/scheduled-task-scheduler.test.mjs apps/desktop/src/main/screenshot-capture.test.mjs apps/desktop/src/main/staged-resource.test.mjs apps/desktop/src/main/staged-resource-alias.test.mjs apps/desktop/src/main/tray-icon.test.mjs apps/desktop/src/main/user-data-directory.test.mjs apps/desktop/src/main/window-open-policy.test.mjs apps/desktop/src/main/window-visibility.test.mjs apps/desktop/src/main/windows-update-trust.test.mjs apps/web/src/lib/api.test.mjs apps/web/src/lib/app-page-path.test.mjs apps/web/src/lib/clipboard.test.mjs apps/web/src/lib/desktop-renderer-ready.test.mjs apps/web/src/lib/desktop-workspace-restore.test.mjs apps/web/src/lib/desktop-repository.test.mjs apps/web/src/lib/desktop-resources.test.mjs apps/web/src/lib/desktop-acp.test.mjs apps/web/src/lib/desktop-sync.test.mjs apps/web/src/lib/local-mirror.test.mjs apps/web/src/lib/repository.test.mjs apps/web/src/lib/runtime.test.mjs apps/web/src/lib/screenshot-import.test.mjs apps/web/src/lib/wechat-chat-import.test.mjs apps/web/src/lib/shared-file-import.test.mjs apps/web/src/lib/sync-queue.test.mjs && bun test --cwd apps/desktop src/main/acp-adapter-manager.test.mjs src/main/acp-host.test.mjs src/main/antigravity-proxy.test.mjs src/main/acp-mcp-bridge.test.mjs && bun run test:desktop:sidecar",
"verify:desktop-renderer": "bun scripts/verify-desktop-renderer.mjs",
diff --git a/scripts/publish-web-clipper.mjs b/scripts/publish-web-clipper.mjs
new file mode 100644
index 00000000..0e8f2e84
--- /dev/null
+++ b/scripts/publish-web-clipper.mjs
@@ -0,0 +1,863 @@
+import { spawnSync } from "node:child_process";
+import { createHmac, createSign, randomUUID } from "node:crypto";
+import {
+ appendFileSync,
+ cpSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, relative, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const REPO_ROOT = resolve(fileURLToPath(new URL("..", import.meta.url)));
+export const OFFICIAL_REPOSITORY = "tianma-if/edgeever";
+export const CHROME_PUBLISHER_ID = "8c414fb4-4243-4b51-9e6b-fe05e49307e3";
+export const CHROME_EXTENSION_ID = "gjadpfmanienmlofajibkfkkpfdkclgo";
+export const FIREFOX_ADDON_SLUG = "edgeever-web-clipper";
+export const FIREFOX_ADDON_ID = "[email protected]";
+export const FIREFOX_LICENSE_SLUG = "AGPL-3.0-only";
+const CHROME_SCOPE = "https://www.googleapis.com/auth/chromewebstore";
+const SOURCE_SKIP_DIRECTORIES = new Set([
+ "node_modules",
+ "dist",
+ "dist-firefox",
+ "web-ext-artifacts",
+ ".git",
+]);
+const ROOT_SOURCE_FILES = [
+ "LICENSE",
+ "package.json",
+ "bun.lock",
+ "bunfig.toml",
+ "tsconfig.json",
+];
+
+const usage = `Usage:
+ bun run publish:extension -- [options]
+
+Options:
+ --platform <target> chrome, firefox, or both (default: both)
+ --notes <text> Firefox release notes
+ --notes-file <path> Firefox release notes file
+ --dry-run Build the packages without calling the stores
+ --help Show this help
+
+Chrome and Edge share the Chrome Web Store item ${CHROME_EXTENSION_ID}.
+Firefox is submitted separately to ${FIREFOX_ADDON_SLUG}.
+`;
+
+export const parsePublishArgs = (argv) => {
+ const options = {
+ platform: "both",
+ notes: "",
+ notesFile: "",
+ dryRun: false,
+ help: false,
+ };
+ const valueOptions = new Map([
+ ["--platform", "platform"],
+ ["--notes", "notes"],
+ ["--notes-file", "notesFile"],
+ ]);
+
+ for (let index = 0; index < argv.length; index += 1) {
+ const argument = argv[index];
+ if (argument === "--dry-run") {
+ options.dryRun = true;
+ continue;
+ }
+ if (argument === "--help") {
+ options.help = true;
+ continue;
+ }
+ const key = valueOptions.get(argument);
+ if (!key) {
+ throw new Error(`Unknown option: ${argument}`);
+ }
+ const value = argv[index + 1];
+ if (!value || value.startsWith("--")) {
+ throw new Error(`${argument} requires a value.`);
+ }
+ options[key] = value;
+ index += 1;
+ }
+
+ if (!options.help && !["chrome", "firefox", "both"].includes(options.platform)) {
+ throw new Error("--platform must be chrome, firefox, or both.");
+ }
+ return options;
+};
+
+export const compareVersions = (left, right) => {
+ const parse = (value) => {
+ if (!/^\d+\.\d+\.\d+$/.test(value)) {
+ throw new Error(`Extension version must use X.Y.Z, received ${value}.`);
+ }
+ return value.split(".").map((part) => Number(part));
+ };
+ const leftParts = parse(left);
+ const rightParts = parse(right);
+ for (let index = 0; index < 3; index += 1) {
+ if (leftParts[index] !== rightParts[index]) {
+ return leftParts[index] - rightParts[index];
+ }
+ }
+ return 0;
+};
+
+export const highestCrxVersion = (revision) => {
+ const versions = (revision?.distributionChannels ?? [])
+ .map((channel) => channel.crxVersion)
+ .filter((version) => typeof version === "string" && version.length > 0);
+ return versions.sort(compareVersions).at(-1) ?? "";
+};
+
+export const chromeSubmissionPlan = ({ packageVersion, status }) => {
+ const published = highestCrxVersion(status?.publishedItemRevisionStatus);
+ const submitted = highestCrxVersion(status?.submittedItemRevisionStatus);
+ const submittedState = status?.submittedItemRevisionStatus?.state ?? "";
+ const pending = submittedState === "PENDING_REVIEW" || submittedState === "STAGED";
+
+ if (submitted && compareVersions(packageVersion, submitted) === 0 && pending) {
+ return { action: "already-submitted", published, submitted, submittedState };
+ }
+ if (submitted && pending) {
+ return {
+ action: "blocked",
+ reason: `Chrome ${submitted} is ${submittedState}. Wait for that review, or cancel it, before submitting ${packageVersion}.`,
+ };
+ }
+ if (published && compareVersions(packageVersion, published) <= 0) {
+ return {
+ action: "blocked",
+ reason: `Chrome already published ${published}. Increase apps/extension/package.json before submitting again.`,
+ };
+ }
+ return { action: "upload", published, submitted, submittedState };
+};
+
+export const firefoxSubmissionPlan = ({ packageVersion, versions }) => {
+ const listed = versions.filter((version) => version?.version);
+ const same = listed.find((version) => version.version === packageVersion);
+ if (same) {
+ const status = same.file?.status ?? "";
+ if (status === "unreviewed" && !same.source) {
+ return { action: "attach-source", version: same.version, status };
+ }
+ if (status === "unreviewed") {
+ return { action: "already-submitted", version: same.version, status };
+ }
+ return {
+ action: "blocked",
+ reason: `Firefox version ${packageVersion} is ${status || "already used"}. Increase apps/extension/package.json before submitting again.`,
+ };
+ }
+
+ const awaiting = listed.find((version) => version.file?.status === "unreviewed");
+ if (awaiting) {
+ return {
+ action: "blocked",
+ reason: `Firefox ${awaiting.version} is still awaiting review.`,
+ };
+ }
+ const newer = listed.find((version) => compareVersions(version.version, packageVersion) > 0);
+ if (newer) {
+ return {
+ action: "blocked",
+ reason: `Firefox already has ${newer.version}. Increase apps/extension/package.json before submitting ${packageVersion}.`,
+ };
+ }
+ return { action: "upload" };
+};
+
+export const chromeUploadFinished = (payload) => {
+ const state = payload?.uploadState || payload?.lastAsyncUploadState || "";
+ if (state.includes("FAIL") || state === "NOT_FOUND") {
+ return { done: true, ok: false, state };
+ }
+ if (state.includes("PROGRESS")) {
+ return { done: false, ok: false, state };
+ }
+ if (state.includes("SUCCEED") || state === "SUCCESS") {
+ return { done: true, ok: true, state };
+ }
+ if (payload?.itemId && !state) {
+ return { done: true, ok: true, state: "SUCCEEDED" };
+ }
+ return { done: false, ok: false, state };
+};
+
+export const amoUploadReady = (upload) => {
+ if (!upload?.processed) {
+ return { done: false, ok: false };
+ }
+ if (upload.valid === false) {
+ return { done: true, ok: false };
+ }
+ return { done: true, ok: true };
+};
+
+export const amoValidationErrors = (upload) => {
+ const messages = upload?.validation?.messages
+ ?? upload?.validation?.errors
+ ?? [];
+ return messages
+ .filter((message) => !message.type || message.type === "error")
+ .map((message) => message.message || JSON.stringify(message));
+};
+
+export const credentialPresence = (env) => ({
+ chromeServiceAccount: Boolean(env.CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON),
+ chromeRefreshToken: Boolean(
+ env.CHROME_WEB_STORE_CLIENT_ID
+ && env.CHROME_WEB_STORE_CLIENT_SECRET
+ && env.CHROME_WEB_STORE_REFRESH_TOKEN,
+ ),
+ amo: Boolean(env.AMO_JWT_ISSUER && env.AMO_JWT_SECRET),
+ reviewInstance: Boolean(
+ env.EDGE_EVER_REVIEW_INSTANCE_URL && env.EDGE_EVER_REVIEW_API_TOKEN,
+ ),
+});
+
+export const assertCredentials = (platform, env) => {
+ const present = credentialPresence(env);
+ const missing = [];
+ if ((platform === "chrome" || platform === "both") && !present.chromeServiceAccount && !present.chromeRefreshToken) {
+ missing.push("CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON or CHROME_WEB_STORE_CLIENT_ID, CHROME_WEB_STORE_CLIENT_SECRET, and CHROME_WEB_STORE_REFRESH_TOKEN");
+ }
+ if ((platform === "firefox" || platform === "both") && !present.amo) {
+ missing.push("AMO_JWT_ISSUER and AMO_JWT_SECRET");
+ }
+ if (missing.length > 0) {
+ throw new Error(`Missing Web Clipper store credentials: ${missing.join("; ")}.`);
+ }
+};
+
+export const assertOfficialRepository = (repository) => {
+ if (repository && repository !== OFFICIAL_REPOSITORY) {
+ throw new Error(`Web Clipper store submission runs only in ${OFFICIAL_REPOSITORY}.`);
+ }
+};
+
+export const resolveReleaseNotes = ({ notes, notesFile, version }) => {
+ const inline = notes?.trim() ?? "";
+ if (inline) {
+ return limitNotes(inline);
+ }
+ if (notesFile) {
+ const fromFile = readFileSync(notesFile, "utf8").trim();
+ if (fromFile) {
+ return limitNotes(fromFile);
+ }
+ }
+ return `EdgeEver Web Clipper ${version}.`;
+};
+
+const limitNotes = (notes) => {
+ if (notes.length > 4000) {
+ throw new Error("Release notes must be 4000 characters or fewer.");
+ }
+ return notes;
+};
+
+export const buildApprovalNotes = ({ version, reviewInstanceUrl, reviewApiToken }) => {
+ const lines = [
+ "Source archive root: edgeever-source.",
+ `Reproduce version ${version} with Bun 1.3.14 or later and Node.js 20 or later:`,
+ "bun install --frozen-lockfile",
+ "bun run test:extension",
+ "bun run build:extension:firefox",
+ "bun run lint:extension:firefox",
+ "bun run package:extension:firefox",
+ "See SOURCE_BUILD.md.",
+ "The extension reads a page only after a clip action and sends it to the EdgeEver instance configured in the extension settings.",
+ "Review steps are in apps/extension/FIREFOX_STORE_LISTING.md.",
+ ];
+ if (reviewInstanceUrl && reviewApiToken) {
+ lines.push(`Review instance: ${reviewInstanceUrl}`, `Review API token: ${reviewApiToken}`);
+ }
+ return lines.join("\n");
+};
+
+export const shouldCopyExtensionSource = (relativePath) => {
+ const parts = relativePath.split(/[\\/]/u).filter(Boolean);
+ if (parts.some((part) => SOURCE_SKIP_DIRECTORIES.has(part) || part === ".DS_Store")) {
+ return false;
+ }
+ return !(parts[0] === "store-assets" && relativePath.endsWith(".zip"));
+};
+
+export const workspacePackageManifests = (repoRoot) => {
+ const manifests = [];
+ for (const group of ["apps", "packages"]) {
+ const groupDirectory = join(repoRoot, group);
+ if (!existsSync(groupDirectory)) {
+ continue;
+ }
+ for (const entry of readdirSync(groupDirectory, { withFileTypes: true })) {
+ if (!entry.isDirectory() || (group === "apps" && entry.name === "extension")) {
+ continue;
+ }
+ const manifest = join(group, entry.name, "package.json");
+ if (existsSync(join(repoRoot, manifest))) {
+ manifests.push(manifest);
+ }
+ }
+ }
+ return manifests.sort();
+};
+
+export const encodeJwtPart = (value) =>
+ Buffer.from(JSON.stringify(value)).toString("base64url");
+
+export const createAmoJwt = ({ issuer, secret, now = Date.now(), jti = randomUUID() }) => {
+ const issuedAt = Math.floor(now / 1000);
+ const header = encodeJwtPart({ alg: "HS256", typ: "JWT" });
+ const payload = encodeJwtPart({
+ iss: issuer,
+ jti,
+ iat: issuedAt,
+ exp: issuedAt + 240,
+ });
+ const body = `${header}.${payload}`;
+ const signature = createHmac("sha256", secret).update(body).digest("base64url");
+ return `${body}.${signature}`;
+};
+
+export const createGoogleServiceAccountAssertion = ({
+ clientEmail,
+ privateKey,
+ now = Date.now(),
+}) => {
+ const issuedAt = Math.floor(now / 1000);
+ const header = encodeJwtPart({ alg: "RS256", typ: "JWT" });
+ const payload = encodeJwtPart({
+ iss: clientEmail,
+ scope: CHROME_SCOPE,
+ aud: "https://oauth2.googleapis.com/token",
+ iat: issuedAt,
+ exp: issuedAt + 3600,
+ });
+ const body = `${header}.${payload}`;
+ const signature = createSign("RSA-SHA256").update(body).sign(privateKey).toString("base64url");
+ return `${body}.${signature}`;
+};
+
+const runCommand = (command, args, options = {}) => {
+ const result = spawnSync(command, args, { stdio: "inherit", ...options });
+ if (result.error) {
+ throw new Error(`${command} failed to start: ${result.error.message}`);
+ }
+ if (result.status !== 0) {
+ throw new Error(`${command} ${args.join(" ")} failed with status ${result.status}.`);
+ }
+};
+
+const errorDetail = async (response) => {
+ const text = await response.text();
+ if (!text) {
+ return `HTTP ${response.status}`;
+ }
+ try {
+ const payload = JSON.parse(text);
+ const message = payload.error?.message || payload.detail || payload.message;
+ if (message) {
+ return `HTTP ${response.status}: ${message}`;
+ }
+ return `HTTP ${response.status}: ${JSON.stringify(payload).slice(0, 2000)}`;
+ } catch {
+ return `HTTP ${response.status}: ${text.slice(0, 2000)}`;
+ }
+};
+
+const requestJson = async (fetchImpl, url, options) => {
+ const response = await fetchImpl(url, options);
+ if (!response.ok) {
+ throw new Error(await errorDetail(response));
+ }
+ const text = await response.text();
+ return text ? JSON.parse(text) : {};
+};
+
+const sleep = (delayMs) => new Promise((resolveDelay) => {
+ setTimeout(resolveDelay, delayMs);
+});
+
+export const createChromeClient = ({
+ fetchImpl = fetch,
+ accessToken,
+ publisherId = CHROME_PUBLISHER_ID,
+ extensionId = CHROME_EXTENSION_ID,
+}) => {
+ const item = `publishers/${publisherId}/items/${extensionId}`;
+ const headers = { Authorization: `Bearer ${accessToken}` };
+ return {
+ fetchStatus: () => requestJson(
+ fetchImpl,
+ `https://chromewebstore.googleapis.com/v2/${item}:fetchStatus`,
+ { headers },
+ ),
+ upload: async (zipPath) => {
+ const response = await fetchImpl(
+ `https://chromewebstore.googleapis.com/upload/v2/${item}:upload`,
+ {
+ method: "POST",
+ headers: { ...headers, "Content-Type": "application/zip" },
+ body: readFileSync(zipPath),
+ },
+ );
+ if (!response.ok) {
+ throw new Error(await errorDetail(response));
+ }
+ const text = await response.text();
+ return text ? JSON.parse(text) : {};
+ },
+ publish: () => requestJson(
+ fetchImpl,
+ `https://chromewebstore.googleapis.com/v2/${item}:publish`,
+ {
+ method: "POST",
+ headers: { ...headers, "Content-Type": "application/json" },
+ body: JSON.stringify({ publishType: "DEFAULT_PUBLISH" }),
+ },
+ ),
+ };
+};
+
+const waitForChromeUpload = async (client) => {
+ for (let attempt = 0; attempt < 30; attempt += 1) {
+ const status = await client.fetchStatus();
+ const state = status.lastAsyncUploadState || "";
+ if (state.includes("FAIL") || state === "NOT_FOUND") {
+ throw new Error(`Chrome rejected the package upload (${state}).`);
+ }
+ if (!state.includes("PROGRESS")) {
+ return status;
+ }
+ await sleep(2000);
+ }
+ throw new Error("Timed out waiting for the Chrome Web Store upload.");
+};
+
+export const createFirefoxClient = ({
+ fetchImpl = fetch,
+ issuer,
+ secret,
+ addonSlug = FIREFOX_ADDON_SLUG,
+}) => {
+ const authorization = () => `JWT ${createAmoJwt({ issuer, secret })}`;
+ const addonUrl = `https://addons.mozilla.org/api/v5/addons/addon/${addonSlug}`;
+ return {
+ listVersions: async () => {
+ const versions = [];
+ let url = `${addonUrl}/versions/?page_size=50`;
+ for (let page = 0; page < 5 && url; page += 1) {
+ const payload = await requestJson(fetchImpl, url, {
+ headers: { Authorization: authorization() },
+ });
+ versions.push(...(payload.results ?? []));
+ url = payload.next ?? "";
+ }
+ return versions;
+ },
+ uploadPackage: async (zipPath) => {
+ const form = new FormData();
+ form.append("upload", new Blob([readFileSync(zipPath)]), "edgeever-web-clipper.zip");
+ form.append("channel", "listed");
+ const response = await fetchImpl("https://addons.mozilla.org/api/v5/addons/upload/", {
+ method: "POST",
+ headers: { Authorization: authorization() },
+ body: form,
+ });
+ if (!response.ok) {
+ throw new Error(await errorDetail(response));
+ }
+ return response.json();
+ },
+ fetchUpload: (uuid) => requestJson(
+ fetchImpl,
+ `https://addons.mozilla.org/api/v5/addons/upload/${uuid}/`,
+ { headers: { Authorization: authorization() } },
+ ),
+ createVersion: ({ uploadUuid, releaseNotes, approvalNotes }) => requestJson(
+ fetchImpl,
+ `${addonUrl}/versions/`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: authorization(),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ upload: uploadUuid,
+ compatibility: ["firefox", "android"],
+ license: FIREFOX_LICENSE_SLUG,
+ release_notes: { "en-US": releaseNotes },
+ approval_notes: approvalNotes,
+ }),
+ },
+ ),
+ attachSource: async ({ version, sourcePath, releaseNotes, approvalNotes }) => {
+ const form = new FormData();
+ form.append("source", new Blob([readFileSync(sourcePath)]), "edgeever-web-clipper-source.zip");
+ const sourceResponse = await fetchImpl(`${addonUrl}/versions/${version}/`, {
+ method: "PATCH",
+ headers: { Authorization: authorization() },
+ body: form,
+ });
+ if (!sourceResponse.ok) {
+ throw new Error(await errorDetail(sourceResponse));
+ }
+ return requestJson(fetchImpl, `${addonUrl}/versions/${version}/`, {
+ method: "PATCH",
+ headers: {
+ Authorization: authorization(),
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ compatibility: ["firefox", "android"],
+ release_notes: { "en-US": releaseNotes },
+ approval_notes: approvalNotes,
+ }),
+ });
+ },
+ };
+};
+
+const waitForAmoUpload = async (client, uuid) => {
+ for (let attempt = 0; attempt < 60; attempt += 1) {
+ const upload = await client.fetchUpload(uuid);
+ const ready = amoUploadReady(upload);
+ if (ready.done && !ready.ok) {
+ const errors = amoValidationErrors(upload);
+ throw new Error(`Firefox rejected the package. ${errors.join(" ") || "Validation failed."}`);
+ }
+ if (ready.done) {
+ return upload;
+ }
+ await sleep(5000);
+ }
+ throw new Error("Timed out waiting for Firefox Add-ons validation.");
+};
+
+const copySourceArchive = (repoRoot, destinationRoot) => {
+ mkdirSync(destinationRoot, { recursive: true });
+ for (const file of ROOT_SOURCE_FILES) {
+ cpSync(join(repoRoot, file), join(destinationRoot, file));
+ }
+ cpSync(join(repoRoot, "patches"), join(destinationRoot, "patches"), { recursive: true });
+ cpSync(
+ join(repoRoot, "apps/extension/SOURCE_BUILD.md"),
+ join(destinationRoot, "SOURCE_BUILD.md"),
+ );
+ const extensionRoot = join(repoRoot, "apps/extension");
+ cpSync(extensionRoot, join(destinationRoot, "apps/extension"), {
+ recursive: true,
+ filter: (source) => {
+ const extensionRelative = relative(extensionRoot, source);
+ return extensionRelative === "" || shouldCopyExtensionSource(extensionRelative);
+ },
+ });
+ for (const manifest of workspacePackageManifests(repoRoot)) {
+ const target = join(destinationRoot, manifest);
+ mkdirSync(dirname(target), { recursive: true });
+ cpSync(join(repoRoot, manifest), target);
+ }
+};
+
+const zipDirectoryContents = (directory, archivePath) => {
+ rmSync(archivePath, { force: true });
+ runCommand("zip", ["-r", "-X", archivePath, ".", "-x", "*.DS_Store", "-x", "*__MACOSX*"], {
+ cwd: directory,
+ });
+};
+
+const readExtensionVersion = () => {
+ const version = JSON.parse(readFileSync(join(REPO_ROOT, "apps/extension/package.json"), "utf8")).version;
+ compareVersions(version, version);
+ return version;
+};
+
+const assertBuiltManifests = (version) => {
+ const chromium = JSON.parse(readFileSync(join(REPO_ROOT, "apps/extension/dist/manifest.json"), "utf8"));
+ const firefox = JSON.parse(readFileSync(join(REPO_ROOT, "apps/extension/dist-firefox/manifest.json"), "utf8"));
+ if (chromium.version !== version || firefox.version !== version) {
+ throw new Error(`Built manifests are ${chromium.version} and ${firefox.version}; expected ${version}.`);
+ }
+ if (chromium.browser_specific_settings) {
+ throw new Error("The Chromium package must not include Firefox manifest settings.");
+ }
+ if (firefox.browser_specific_settings?.gecko?.id !== FIREFOX_ADDON_ID) {
+ throw new Error(`The Firefox package id must be ${FIREFOX_ADDON_ID}.`);
+ }
+};
+
+const findFirefoxPackage = (version) => {
+ const directory = join(REPO_ROOT, "apps/extension/web-ext-artifacts");
+ const names = readdirSync(directory).filter((name) =>
+ name.endsWith(`-${version}.zip`) && !name.includes("source"));
+ if (names.length !== 1) {
+ throw new Error(`Expected one Firefox package for ${version}, found ${names.join(", ") || "none"}.`);
+ }
+ return join(directory, names[0]);
+};
+
+const buildPackages = (version) => {
+ runCommand("zip", ["-v"], { stdio: "ignore" });
+ runCommand("bun", ["run", "test:extension"], { cwd: REPO_ROOT });
+ runCommand("bun", ["run", "build:extension"], { cwd: REPO_ROOT });
+ runCommand("bun", ["run", "package:extension:firefox"], { cwd: REPO_ROOT });
+ assertBuiltManifests(version);
+
+ const chromiumZip = join(
+ REPO_ROOT,
+ "apps/extension/store-assets",
+ `edgeever-web-clipper-v${version}.zip`,
+ );
+ mkdirSync(dirname(chromiumZip), { recursive: true });
+ zipDirectoryContents(join(REPO_ROOT, "apps/extension/dist"), chromiumZip);
+
+ const firefoxZip = findFirefoxPackage(version);
+ const sourceZip = join(
+ REPO_ROOT,
+ "apps/extension/web-ext-artifacts",
+ `edgeever_web_clipper-${version}-source.zip`,
+ );
+ const staging = mkdtempSync(join(tmpdir(), "edgeever-web-clipper-"));
+ try {
+ copySourceArchive(REPO_ROOT, join(staging, "edgeever-source"));
+ rmSync(sourceZip, { force: true });
+ runCommand("zip", ["-r", "-X", sourceZip, "edgeever-source", "-x", "*.DS_Store"], {
+ cwd: staging,
+ });
+ } finally {
+ rmSync(staging, { recursive: true, force: true });
+ }
+ return { version, chromiumZip, firefoxZip, sourceZip };
+};
+
+const writeGithubOutput = (packages) => {
+ if (!process.env.GITHUB_OUTPUT) {
+ return;
+ }
+ appendFileSync(
+ process.env.GITHUB_OUTPUT,
+ `version=${packages.version}\nchromium_zip=${packages.chromiumZip}\nfirefox_zip=${packages.firefoxZip}\nsource_zip=${packages.sourceZip}\n`,
+ );
+};
+
+const writeStepSummary = (markdown) => {
+ console.log(markdown);
+ if (process.env.GITHUB_STEP_SUMMARY) {
+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${markdown}\n`);
+ }
+};
+
+const chromeAccessToken = async (env, fetchImpl) => {
+ if (env.CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON) {
+ const account = JSON.parse(env.CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON);
+ if (!account.client_email || !account.private_key) {
+ throw new Error("CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON must include client_email and private_key.");
+ }
+ const assertion = createGoogleServiceAccountAssertion({
+ clientEmail: account.client_email,
+ privateKey: account.private_key,
+ });
+ const payload = await requestJson(fetchImpl, "https://oauth2.googleapis.com/token", {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
+ assertion,
+ }),
+ });
+ return payload.access_token;
+ }
+
+ const payload = await requestJson(fetchImpl, "https://oauth2.googleapis.com/token", {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ client_id: env.CHROME_WEB_STORE_CLIENT_ID,
+ client_secret: env.CHROME_WEB_STORE_CLIENT_SECRET,
+ refresh_token: env.CHROME_WEB_STORE_REFRESH_TOKEN,
+ grant_type: "refresh_token",
+ }),
+ });
+ return payload.access_token;
+};
+
+const submitChrome = async ({ version, chromiumZip, env, fetchImpl }) => {
+ const client = createChromeClient({
+ fetchImpl,
+ accessToken: await chromeAccessToken(env, fetchImpl),
+ });
+ const initial = chromeSubmissionPlan({
+ packageVersion: version,
+ status: await client.fetchStatus(),
+ });
+ if (initial.action !== "upload") {
+ return initial;
+ }
+
+ const uploaded = await client.upload(chromiumZip);
+ const immediate = chromeUploadFinished(uploaded);
+ if (immediate.done && !immediate.ok) {
+ throw new Error(`Chrome rejected the package upload (${immediate.state}).`);
+ }
+ if (!immediate.done) {
+ await waitForChromeUpload(client);
+ }
+ try {
+ const published = await client.publish();
+ return {
+ action: "submitted",
+ state: published.state ?? "PENDING_REVIEW",
+ };
+ } catch (error) {
+ const after = chromeSubmissionPlan({
+ packageVersion: version,
+ status: await client.fetchStatus(),
+ });
+ if (after.action === "already-submitted") {
+ return after;
+ }
+ throw error;
+ }
+};
+
+const submitFirefox = async ({ version, firefoxZip, sourceZip, releaseNotes, env, fetchImpl }) => {
+ const client = createFirefoxClient({
+ fetchImpl,
+ issuer: env.AMO_JWT_ISSUER,
+ secret: env.AMO_JWT_SECRET,
+ });
+ const approvalNotes = buildApprovalNotes({
+ version,
+ reviewInstanceUrl: env.EDGE_EVER_REVIEW_INSTANCE_URL,
+ reviewApiToken: env.EDGE_EVER_REVIEW_API_TOKEN,
+ });
+ const plan = firefoxSubmissionPlan({
+ packageVersion: version,
+ versions: await client.listVersions(),
+ });
+ if (plan.action === "blocked" || plan.action === "already-submitted") {
+ return plan;
+ }
+ if (plan.action === "attach-source") {
+ await client.attachSource({
+ version,
+ sourcePath: sourceZip,
+ releaseNotes,
+ approvalNotes,
+ });
+ return { action: "submitted", version, sourceAttached: true };
+ }
+
+ const upload = await client.uploadPackage(firefoxZip);
+ if (!upload.uuid) {
+ throw new Error("Firefox did not return an upload id.");
+ }
+ await waitForAmoUpload(client, upload.uuid);
+ const created = await client.createVersion({
+ uploadUuid: upload.uuid,
+ releaseNotes,
+ approvalNotes,
+ });
+ const createdVersion = created.version?.version ?? version;
+ await client.attachSource({
+ version: createdVersion,
+ sourcePath: sourceZip,
+ releaseNotes,
+ approvalNotes,
+ });
+ return { action: "submitted", version: createdVersion, sourceAttached: true };
+};
+
+const selectedPlatforms = (platform) =>
+ platform === "both" ? ["chrome", "firefox"] : [platform];
+
+const main = async () => {
+ const options = parsePublishArgs(process.argv.slice(2));
+ if (options.help) {
+ console.log(usage);
+ return;
+ }
+ if (!options.dryRun) {
+ assertOfficialRepository(process.env.GITHUB_REPOSITORY);
+ assertCredentials(options.platform, process.env);
+ }
+
+ const version = readExtensionVersion();
+ const releaseNotes = resolveReleaseNotes({
+ notes: options.notes,
+ notesFile: options.notesFile,
+ version,
+ });
+ const packages = buildPackages(version);
+ writeGithubOutput(packages);
+
+ if (options.dryRun) {
+ const present = credentialPresence(process.env);
+ writeStepSummary([
+ `Web Clipper ${version} packages are ready.`,
+ `Chromium: ${packages.chromiumZip}`,
+ `Firefox: ${packages.firefoxZip}`,
+ `Source: ${packages.sourceZip}`,
+ "Dry run: stores were not called.",
+ `Chrome credentials: ${present.chromeServiceAccount || present.chromeRefreshToken ? "present" : "missing"}`,
+ `Firefox credentials: ${present.amo ? "present" : "missing"}`,
+ ].join("\n"));
+ return;
+ }
+
+ if (!process.env.EDGE_EVER_REVIEW_INSTANCE_URL || !process.env.EDGE_EVER_REVIEW_API_TOKEN) {
+ console.warn("Review instance credentials are unset. Firefox approval notes omit the review login.");
+ }
+
+ const results = [];
+ const failures = [];
+ for (const platform of selectedPlatforms(options.platform)) {
+ const store = platform === "chrome" ? "Chrome" : "Firefox";
+ try {
+ const result = platform === "chrome"
+ ? await submitChrome({ ...packages, env: process.env, fetchImpl: fetch })
+ : await submitFirefox({
+ ...packages,
+ releaseNotes,
+ env: process.env,
+ fetchImpl: fetch,
+ });
+ results.push([store, result]);
+ if (result.action === "blocked") {
+ failures.push(result.reason);
+ }
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ results.push([store, { action: "failed", reason }]);
+ failures.push(reason);
+ }
+ }
+
+ writeStepSummary([
+ `Web Clipper ${version}`,
+ ...results.map(([store, result]) => `${store}: ${result.action}${result.reason ? ` — ${result.reason}` : ""}`),
+ "Chrome and Edge use the same Chrome Web Store submission. Review still has to approve it.",
+ "Firefox review still has to approve and sign the package.",
+ ].join("\n"));
+ if (failures.length > 0) {
+ throw new Error(failures.join(" "));
+ }
+};
+
+if (import.meta.main) {
+ main().catch((error) => {
+ console.error(error instanceof Error ? error.message : error);
+ process.exitCode = 1;
+ });
+}
diff --git a/scripts/publish-web-clipper.test.mjs b/scripts/publish-web-clipper.test.mjs
new file mode 100644
index 00000000..6b3b392b
--- /dev/null
+++ b/scripts/publish-web-clipper.test.mjs
@@ -0,0 +1,296 @@
+import { createHmac, createVerify, generateKeyPairSync } from "node:crypto";
+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, test } from "bun:test";
+import {
+ amoUploadReady,
+ amoValidationErrors,
+ assertCredentials,
+ assertOfficialRepository,
+ buildApprovalNotes,
+ chromeSubmissionPlan,
+ chromeUploadFinished,
+ compareVersions,
+ createAmoJwt,
+ createChromeClient,
+ createFirefoxClient,
+ createGoogleServiceAccountAssertion,
+ credentialPresence,
+ firefoxSubmissionPlan,
+ FIREFOX_LICENSE_SLUG,
+ highestCrxVersion,
+ OFFICIAL_REPOSITORY,
+ parsePublishArgs,
+ resolveReleaseNotes,
+ shouldCopyExtensionSource,
+ workspacePackageManifests,
+} from "./publish-web-clipper.mjs";
+
+const workflow = readFileSync(
+ new URL("../.github/workflows/extension-store.yml", import.meta.url),
+ "utf8",
+);
+
+describe("web clipper store command", () => {
+ test("defaults to both stores", () => {
+ expect(parsePublishArgs([])).toMatchObject({
+ platform: "both",
+ dryRun: false,
+ });
+ });
+
+ test("rejects an unknown store", () => {
+ expect(() => parsePublishArgs(["--platform", "edge"])).toThrow("--platform");
+ });
+
+ test("compares numeric versions", () => {
+ expect(compareVersions("0.1.9", "0.1.8")).toBeGreaterThan(0);
+ expect(compareVersions("0.1.8", "0.1.8")).toBe(0);
+ expect(compareVersions("0.2.0", "0.1.9")).toBeGreaterThan(0);
+ expect(() => compareVersions("1", "0.1.8")).toThrow("X.Y.Z");
+ });
+
+ test("blocks a Chrome package that is not newer than the public version", () => {
+ const plan = chromeSubmissionPlan({
+ packageVersion: "0.1.8",
+ status: {
+ publishedItemRevisionStatus: {
+ state: "PUBLISHED",
+ distributionChannels: [{ crxVersion: "0.1.8", deployPercentage: 100 }],
+ },
+ },
+ });
+
+ expect(plan.action).toBe("blocked");
+ expect(plan.reason).toContain("0.1.8");
+ });
+
+ test("uploads a newer Chrome package when nothing is pending", () => {
+ expect(chromeSubmissionPlan({
+ packageVersion: "0.1.9",
+ status: {
+ publishedItemRevisionStatus: {
+ distributionChannels: [{ crxVersion: "0.1.8" }],
+ },
+ },
+ }).action).toBe("upload");
+ });
+
+ test("treats the same Chrome version awaiting review as already submitted", () => {
+ expect(chromeSubmissionPlan({
+ packageVersion: "0.1.9",
+ status: {
+ publishedItemRevisionStatus: {
+ distributionChannels: [{ crxVersion: "0.1.8" }],
+ },
+ submittedItemRevisionStatus: {
+ state: "PENDING_REVIEW",
+ distributionChannels: [{ crxVersion: "0.1.9" }],
+ },
+ },
+ }).action).toBe("already-submitted");
+ });
+
+ test("blocks a different Chrome version that is already pending", () => {
+ expect(chromeSubmissionPlan({
+ packageVersion: "0.2.0",
+ status: {
+ submittedItemRevisionStatus: {
+ state: "STAGED",
+ distributionChannels: [{ crxVersion: "0.1.9" }],
+ },
+ },
+ }).action).toBe("blocked");
+ });
+
+ test("uses the highest Chrome channel version", () => {
+ expect(highestCrxVersion({
+ distributionChannels: [
+ { crxVersion: "0.1.8" },
+ { crxVersion: "0.1.10" },
+ ],
+ })).toBe("0.1.10");
+ });
+
+ test("asks Firefox to attach source when the pending version has none", () => {
+ expect(firefoxSubmissionPlan({
+ packageVersion: "0.1.9",
+ versions: [{ version: "0.1.9", file: { status: "unreviewed" }, source: null }],
+ }).action).toBe("attach-source");
+ });
+
+ test("does not reuse a public Firefox version", () => {
+ expect(firefoxSubmissionPlan({
+ packageVersion: "0.1.8",
+ versions: [{ version: "0.1.8", file: { status: "public" }, source: "https://example.test/source" }],
+ }).action).toBe("blocked");
+ });
+
+ test("blocks a second Firefox upload while another version awaits review", () => {
+ expect(firefoxSubmissionPlan({
+ packageVersion: "0.1.10",
+ versions: [{ version: "0.1.9", file: { status: "unreviewed" }, source: "https://example.test/source" }],
+ }).reason).toContain("0.1.9");
+ });
+
+ test("reads a finished Chrome upload without treating every status item as finished", () => {
+ expect(chromeUploadFinished({ itemId: "abc" })).toMatchObject({ done: true, ok: true });
+ expect(chromeUploadFinished({ uploadState: "IN_PROGRESS" }).done).toBe(false);
+ expect(chromeUploadFinished({ uploadState: "FAILED" })).toMatchObject({ done: true, ok: false });
+ });
+
+ test("waits until Firefox validation finishes and keeps warnings", () => {
+ expect(amoUploadReady({ processed: false })).toMatchObject({ done: false });
+ expect(amoUploadReady({ processed: true, valid: true })).toMatchObject({ done: true, ok: true });
+ expect(amoValidationErrors({
+ validation: {
+ messages: [
+ { type: "error", message: "Missing id" },
+ { type: "warning", message: "innerHTML" },
+ ],
+ },
+ })).toEqual(["Missing id"]);
+ });
+
+ test("names the missing credentials without including secret values", () => {
+ expect(() => assertCredentials("both", {
+ CHROME_WEB_STORE_CLIENT_SECRET: "super-secret",
+ })).toThrow("CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON");
+ expect(credentialPresence({
+ AMO_JWT_ISSUER: "user:1:1",
+ AMO_JWT_SECRET: "secret",
+ }).amo).toBe(true);
+ });
+
+ test("refuses to submit from a fork", () => {
+ expect(() => assertOfficialRepository("someone/edgeever")).toThrow(OFFICIAL_REPOSITORY);
+ expect(() => assertOfficialRepository("")).not.toThrow();
+ });
+
+ test("uses a one-line Firefox note when none was provided", () => {
+ expect(resolveReleaseNotes({ version: "0.1.9" })).toBe("EdgeEver Web Clipper 0.1.9.");
+ });
+
+ test("includes the review login only in the private approval note", () => {
+ const notes = buildApprovalNotes({
+ version: "0.1.9",
+ reviewInstanceUrl: "https://review.example.test",
+ reviewApiToken: "review-token",
+ });
+
+ expect(notes).toContain("https://review.example.test");
+ expect(notes).toContain("review-token");
+ expect(notes).toContain("bun run package:extension:firefox");
+ expect(buildApprovalNotes({ version: "0.1.9" })).not.toContain("Review API token");
+ });
+
+ test("keeps built store packages and dependency installs out of the source archive", () => {
+ expect(shouldCopyExtensionSource("src/background.ts")).toBe(true);
+ expect(shouldCopyExtensionSource("dist/manifest.json")).toBe(false);
+ expect(shouldCopyExtensionSource("node_modules/web-ext/package.json")).toBe(false);
+ expect(shouldCopyExtensionSource("store-assets/edgeever-web-clipper-v0.1.8.zip")).toBe(false);
+ expect(shouldCopyExtensionSource("store-assets/store-icon-128.png")).toBe(true);
+
+ const manifests = workspacePackageManifests(new URL("..", import.meta.url).pathname);
+ expect(manifests).toContain("apps/web/package.json");
+ expect(manifests).toContain("packages/shared/package.json");
+ expect(manifests).not.toContain("apps/extension/package.json");
+ });
+
+ test("signs Firefox and Chrome credentials", () => {
+ const amo = createAmoJwt({
+ issuer: "user:1:1",
+ secret: "amo-secret",
+ now: 1_700_000_000_000,
+ jti: "fixed-jti",
+ });
+ const [header, payload, signature] = amo.split(".");
+ const expected = createHmac("sha256", "amo-secret")
+ .update(`${header}.${payload}`)
+ .digest("base64url");
+ expect(signature).toBe(expected);
+ expect(JSON.parse(Buffer.from(payload, "base64url").toString())).toMatchObject({
+ iss: "user:1:1",
+ jti: "fixed-jti",
+ exp: 1_700_000_240,
+ });
+
+ const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
+ const assertion = createGoogleServiceAccountAssertion({
+ clientEmail: "[email protected]",
+ privateKey: privateKey.export({ type: "pkcs8", format: "pem" }),
+ now: 1_700_000_000_000,
+ });
+ const [googleHeader, googlePayload, googleSignature] = assertion.split(".");
+ const verifier = createVerify("RSA-SHA256");
+ verifier.update(`${googleHeader}.${googlePayload}`);
+ expect(verifier.verify(publicKey, googleSignature, "base64url")).toBe(true);
+ expect(JSON.parse(Buffer.from(googlePayload, "base64url").toString()).scope).toContain(
+ "chromewebstore",
+ );
+ });
+
+ test("asks Chrome to publish after review and Firefox for both apps", async () => {
+ const calls = [];
+ const fetchImpl = async (url, options = {}) => {
+ calls.push({ url, body: options.body, method: options.method });
+ if (String(url).endsWith(":publish")) {
+ return jsonResponse({ state: "PENDING_REVIEW" });
+ }
+ if (String(url).endsWith("/versions/")) {
+ return jsonResponse({ version: "0.1.9" });
+ }
+ return jsonResponse({});
+ };
+ const chrome = createChromeClient({ fetchImpl, accessToken: "token" });
+ await chrome.publish();
+
+ const directory = mkdtempSync(join(tmpdir(), "edgeever-clipper-api-"));
+ const packagePath = join(directory, "addon.zip");
+ writeFileSync(packagePath, "zip");
+ const firefox = createFirefoxClient({
+ fetchImpl,
+ issuer: "user:1:1",
+ secret: "amo-secret",
+ });
+ await firefox.uploadPackage(packagePath);
+ await firefox.createVersion({
+ uploadUuid: "upload-1",
+ releaseNotes: "Notes",
+ approvalNotes: "Build it",
+ });
+
+ const publish = calls.find((call) => String(call.url).endsWith(":publish"));
+ expect(JSON.parse(publish.body).publishType).toBe("DEFAULT_PUBLISH");
+ const created = calls.find((call) => String(call.url).endsWith("/versions/"));
+ expect(JSON.parse(created.body)).toMatchObject({
+ upload: "upload-1",
+ compatibility: ["firefox", "android"],
+ license: FIREFOX_LICENSE_SLUG,
+ release_notes: { "en-US": "Notes" },
+ });
+ const upload = calls.find((call) => String(call.url).endsWith("/upload/"));
+ expect(upload.method).toBe("POST");
+ expect(upload.body).toBeInstanceOf(FormData);
+ expect(upload.body.get("channel")).toBe("listed");
+ });
+
+ test("keeps store submission on the official repository workflow", () => {
+ expect(workflow).toContain("github.repository == 'tianma-if/edgeever'");
+ expect(workflow).toContain("workflow_dispatch:");
+ expect(workflow).toContain("CHROME_WEB_STORE_SERVICE_ACCOUNT_JSON");
+ expect(workflow).toContain("AMO_JWT_ISSUER");
+ expect(workflow).toContain("AMO_JWT_SECRET");
+ expect(workflow).toContain("edgeever-web-clipper-store");
+ expect(workflow).not.toContain("bun run release");
+ expect(workflow).not.toContain("publish:stores");
+ expect(workflow).not.toContain("echo ${{ secrets");
+ });
+});
+
+const jsonResponse = (payload) => ({
+ ok: true,
+ json: async () => payload,
+ text: async () => JSON.stringify(payload),
+});