Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(notifications): add queue-backed desktop and mobile system notifications (#777)
Gener1310e48b8d58
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 8f05bebb8..b6cf7d8c5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -345,7 +345,7 @@ jobs:case "$root" inscripts/ci) projects=(ci-scripts) ;;src/email-worker) projects=(email-worker-node email-worker-runtime) ;;- src/wake-worker) projects=(wake-worker-node wake-worker-runtime) ;;+ src/queue-worker) projects=(queue-worker-node queue-worker-runtime) ;;src/web) projects=(web-node web-dom web-runtime auth-node auth-runtime) ;;src/ws-do) projects=(ws-do-node ws-do-runtime) ;;*) projects=("$(node -e 'console.log(require("./" + process.argv[1] + "/package.json").name)' "$root")") ;;@@ -561,7 +561,10 @@ jobs:CI_PROJECTION_VALUE: ${{ needs.scope.outputs.integration_suites }}run: node scripts/ci/validate-execution-plan.mjs- name: Create local bindings- run: printf 'BETTER_AUTH_SECRET=ci-e2e-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\n' > src/web/.dev.vars+ run: |+ printf 'BETTER_AUTH_SECRET=ci-e2e-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\n' > src/web/.dev.vars+ cp src/queue-worker/.dev.vars.example src/queue-worker/.dev.vars+ sed -i 's|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!|' src/queue-worker/.dev.vars- run: pnpm run db:migrate- name: Start dev serversrun: |@@ -574,7 +577,7 @@ jobs:}pnpm --filter @alook/ws-do dev &wait_for http://localhost:8789/health- pnpm --filter @alook/wake-worker dev &+ pnpm --filter @alook/queue-worker dev &wait_for http://localhost:8790/healthpnpm --filter @alook/email-worker dev &wait_for http://localhost:8787/healthdiff --git a/.github/workflows/mobile-release.yml b/.github/workflows/mobile-release.ymlindex 0eec1e0c7..61563ae0a 100644--- a/.github/workflows/mobile-release.yml+++ b/.github/workflows/mobile-release.yml@@ -168,6 +168,7 @@ jobs:assert entitlements["com.apple.developer.associated-domains"] == ["applinks:auth.alook.ai"]+ assert entitlements["aps-environment"] == "production"PYgrep -F 'AUTH_WORKER_HOST = "auth.alook.ai"' src/web/auth/index.ts@@ -276,6 +277,15 @@ jobs:working-directory: src/desktoprun: pnpm tauri android init --ci --skip-targets-install+ - name: Prepare Android Firebase configuration+ env:+ ANDROID_GOOGLE_SERVICES_JSON: ${{ secrets.ANDROID_GOOGLE_SERVICES_JSON }}+ run: |+ node --input-type=module <<'NODE'+ import { prepareAndroidFirebase } from "./scripts/ci/prepare-android-firebase.mjs"+ prepareAndroidFirebase(process.env.ANDROID_GOOGLE_SERVICES_JSON, "src/desktop/src-tauri/gen/android/app/google-services.json")+ NODE+- name: Read and verify mobile release versionid: versionshell: bashdiff --git a/.github/workflows/publish-app.yml b/.github/workflows/publish-app.ymlindex d9f112762..ba0edf889 100644--- a/.github/workflows/publish-app.yml+++ b/.github/workflows/publish-app.yml@@ -62,7 +62,7 @@ jobs:- name: Build packagesif: steps.check.outputs.skip == 'false'- run: pnpm build --filter=@alook/shared --filter=@alook/web --filter=@alook/daemon --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/wake-worker+ run: pnpm build --filter=@alook/shared --filter=@alook/web --filter=@alook/daemon --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/queue-worker- name: Bundle app (pre-build workers)if: steps.check.outputs.skip == 'false'diff --git a/.gitignore b/.gitignoreindex 3dd6368a3..988682006 100644--- a/.gitignore+++ b/.gitignore@@ -19,6 +19,7 @@ docs/.alook/.dev.varsplans/+src/desktop/src-tauri/gen/android/app/google-services.jsonperf-artifacts/src/videos/**/build/src/videos/**/out/diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 3df702c88..3afb59b45 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -38,7 +38,7 @@ Alook is a monorepo with nine packages:| `@alook/app` | `src/app` | One-command local bootstrap (`npx @alook/app onboard`) || `@alook/daemon` | `src/daemon` | Host-side runtime backend, process manager, credential proxy || `@alook/desktop` | `src/desktop` | Desktop app (Tauri) |-| `@alook/wake-worker` | `src/wake-worker` | Wakes offline agents with unread messages |+| `@alook/queue-worker` | `src/queue-worker` | Handles versioned bot-wake and mobile-push tasks |## Making Changesdiff --git a/package.json b/package.jsonindex 7ac8ca344..25dad44aa 100644--- a/package.json+++ b/package.json@@ -5,8 +5,8 @@"scripts": {"build": "turbo run build","test": "pnpm --filter @alook/agent-driver build && turbo run test --filter=!@alook/agent-driver && pnpm --filter @alook/agent-driver test && vitest run --project ci-scripts",- "predev": "[ -f src/web/.dev.vars ] || (cp src/web/.dev.vars.example src/web/.dev.vars && sed -i '' \"s|^BETTER_AUTH_SECRET=$|BETTER_AUTH_SECRET=$(openssl rand -base64 32)|\" src/web/.dev.vars && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$(openssl rand -base64 32)|\" src/web/.dev.vars && echo '✓ Generated src/web/.dev.vars (fill in OAuth keys if needed)'); [ -f src/email-worker/.dev.vars ] || (cp src/email-worker/.dev.vars.example src/email-worker/.dev.vars && KEY=$(grep '^ENCRYPTION_KEY=' src/web/.dev.vars | cut -d= -f2-) && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$KEY|\" src/email-worker/.dev.vars && echo '✓ Generated src/email-worker/.dev.vars (synced ENCRYPTION_KEY from web)')",- "dev": "turbo run dev --filter=@alook/web --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/wake-worker --filter=@alook/shared",+ "predev": "[ -f src/web/.dev.vars ] || (cp src/web/.dev.vars.example src/web/.dev.vars && sed -i '' \"s|^BETTER_AUTH_SECRET=$|BETTER_AUTH_SECRET=$(openssl rand -base64 32)|\" src/web/.dev.vars && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$(openssl rand -base64 32)|\" src/web/.dev.vars && echo '✓ Generated src/web/.dev.vars (fill in OAuth keys if needed)'); [ -f src/email-worker/.dev.vars ] || cp src/email-worker/.dev.vars.example src/email-worker/.dev.vars; ALOOK_ENCRYPTION_KEY=$(grep '^ENCRYPTION_KEY=' src/web/.dev.vars | cut -d= -f2-); sed -i '' \"s|^ENCRYPTION_KEY=.*$|ENCRYPTION_KEY=$ALOOK_ENCRYPTION_KEY|\" src/email-worker/.dev.vars; [ -f src/queue-worker/.dev.vars ] || cp src/queue-worker/.dev.vars.example src/queue-worker/.dev.vars; sed -i '' \"s|^ENCRYPTION_KEY=.*$|ENCRYPTION_KEY=$ALOOK_ENCRYPTION_KEY|\" src/queue-worker/.dev.vars; echo '✓ Synced ENCRYPTION_KEY to email-worker and queue-worker'",+ "dev": "turbo run dev --filter=@alook/web --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/queue-worker --filter=@alook/shared","clean": "rm -rf node_modules src/*/node_modules src/*/dist src/*/.turbo src/daemon/agent-driver/node_modules src/daemon/agent-driver/dist src/daemon/agent-driver/.turbo .turbo src/web/.next src/web/.open-next src/web/blog/.next src/web/blog/.open-next src/*/.wrangler .alook","clean:builds": "rm -rf src/*/dist src/daemon/agent-driver/dist src/web/.next src/web/.open-next src/web/blog/.next src/web/blog/.open-next .turbo src/*/.turbo src/daemon/agent-driver/.turbo","reinstall": "pnpm run clean && pnpm install",@@ -20,7 +20,7 @@"build:desktop": "pnpm --filter @alook/desktop build","dev:email": "pnpm --filter @alook/email-worker dev","dev:ws": "pnpm --filter @alook/ws-do dev",- "dev:wake-worker": "pnpm --filter @alook/wake-worker dev",+ "dev:queue-worker": "pnpm --filter @alook/queue-worker dev","dev:app": "node scripts/dev-app.mjs","dev:meeting": "node scripts/dev-meeting.mjs","dev:send": "node -e \"const c=require('crypto');const a=process.argv.slice(1);const[f,t,s='Test',b='Hello from dev']=a;if(!f||!t){console.error('Usage: pnpm dev:send <from> <to> [subject] [body]');process.exit(1)}const raw=['From: '+f,'To: '+t,'Subject: '+s,'Message-ID: <'+c.randomUUID()+'@dev.local>','Date: '+new Date().toUTCString(),'MIME-Version: 1.0','Content-Type: text/plain; charset=utf-8','',b].join('\\r\\n');fetch('http://localhost:8787/cdn-cgi/handler/email?from='+encodeURIComponent(f)+'&to='+encodeURIComponent(t),{method:'POST',headers:{'Content-Type':'application/json'},body:raw}).then(r=>{if(r.ok)console.log('Email delivered to worker');else return r.text().then(t=>{throw new Error(t)})}).catch(e=>console.error('Email worker not running?',e.message))\"",@@ -36,7 +36,7 @@"deploy:web": "pnpm db:migrate:remote && cd src/web && npx opennextjs-cloudflare build && npx opennextjs-cloudflare deploy","deploy:ws-do": "cd src/ws-do && npx wrangler deploy","deploy:email": "cd src/email-worker && npx wrangler deploy",- "deploy:wake-worker": "cd src/wake-worker && npx wrangler deploy",+ "deploy:queue-worker": "cd src/queue-worker && npx wrangler deploy","db:migrate:remote": "pnpm --filter @alook/web exec wrangler d1 migrations apply alook-app --remote","bump": "node scripts/bump-version.mjs","typegrep:ws": "node scripts/lint-ws-events.mjs",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0942d01e6..05bec799e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -257,7 +257,7 @@ importers:specifier: 4.1.11version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- src/wake-worker:+ src/queue-worker:dependencies:'@alook/shared':specifier: workspace:*diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 150730a21..6afe4780c 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -6,7 +6,7 @@ packages:- "src/web"- "src/email-worker"- "src/ws-do"- - "src/wake-worker"+ - "src/queue-worker"- "src/app"- "src/desktop"- "tests/utils"diff --git a/scripts/bump-version.mjs b/scripts/bump-version.mjsindex b57716f80..0dcf2800d 100644--- a/scripts/bump-version.mjs+++ b/scripts/bump-version.mjs@@ -4,8 +4,8 @@ import { join } from "node:path";import { execSync } from "node:child_process";const ROOT = new URL("..", import.meta.url).pathname.replace(/\/$/, "");-const WORKSPACE_DIRS = ["src/shared", "src/cli", "src/app", "src/daemon", "src/daemon/agent-driver", "src/web", "src/email-worker", "src/ws-do", "src/wake-worker", "src/desktop"];-const DEPLOY_TRIGGER_DIRS = ["src/web", "src/email-worker", "src/ws-do", "src/wake-worker"];+const WORKSPACE_DIRS = ["src/shared", "src/cli", "src/app", "src/daemon", "src/daemon/agent-driver", "src/web", "src/email-worker", "src/ws-do", "src/queue-worker", "src/desktop"];+const DEPLOY_TRIGGER_DIRS = ["src/web", "src/email-worker", "src/ws-do", "src/queue-worker"];function readPkg(dir) {const p = join(ROOT, dir, "package.json");diff --git a/scripts/ci/change-scope-manifest.json b/scripts/ci/change-scope-manifest.jsonindex c4d39205a..0776992e0 100644--- a/scripts/ci/change-scope-manifest.json+++ b/scripts/ci/change-scope-manifest.json@@ -130,13 +130,13 @@"app_artifact": false},{- "name": "@alook/wake-worker",- "root": "src/wake-worker",+ "name": "@alook/queue-worker",+ "root": "src/queue-worker","static": true,"build": true,"knip": true,- "unit_root": "src/wake-worker",- "coverage_roots": ["src/wake-worker/**/*.{ts,tsx,js,jsx}"],+ "unit_root": "src/queue-worker",+ "coverage_roots": ["src/queue-worker/**/*.{ts,tsx,js,jsx}"],"windows_suites": [],"integration_suites": ["web"],"linux_suites": [],@@ -223,7 +223,7 @@"src/desktop/package.json","src/email-worker/package.json","src/shared/package.json",- "src/wake-worker/package.json",+ "src/queue-worker/package.json","src/web/package.json","src/ws-do/package.json","tests/utils/package.json"diff --git a/scripts/ci/changed-scopes.test.ts b/scripts/ci/changed-scopes.test.tsindex 4c43fd9c6..59de3cfd3 100644--- a/scripts/ci/changed-scopes.test.ts+++ b/scripts/ci/changed-scopes.test.ts@@ -205,9 +205,9 @@ describe("canonical execution plan", () => {"@alook/cli","@alook/daemon","@alook/email-worker",+ "@alook/queue-worker","@alook/shared","@alook/test-utils",- "@alook/wake-worker","@alook/web","@alook/ws-do",])diff --git a/scripts/ci/dev-registry-isolation.test.ts b/scripts/ci/dev-registry-isolation.test.tsindex c01747eb7..ac7d8bfd9 100644--- a/scripts/ci/dev-registry-isolation.test.ts+++ b/scripts/ci/dev-registry-isolation.test.ts@@ -7,7 +7,7 @@ const launcherPath = resolve(repositoryRoot, "scripts/dev-with-wrangler-registryconst packagePaths = ["src/web/package.json","src/ws-do/package.json",- "src/wake-worker/package.json",+ "src/queue-worker/package.json","src/email-worker/package.json",]const registryLauncher = /(?:^|\s)node\s+\.\.\/\.\.\/scripts\/dev-with-wrangler-registry\.mjs\s+([^\s]+)/gdiff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex 1fba41bcb..7a5b6e2f1 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -80,6 +80,7 @@ export const SPEC_SECONDS = {"56-inbox-friend-requests.spec.ts": 60,"56-remote-image-state-contract.spec.ts": 3.122,"57-server-delete-navigation-races.spec.ts": 55,+ "58-system-notifications.spec.ts": 46.600,}function walk(directory) {diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex 3f20cfdcc..74914293e 100644--- a/scripts/ci/e2e-shards.test.ts+++ b/scripts/ci/e2e-shards.test.ts@@ -80,12 +80,12 @@ describe("planE2eShards", () => {expect(new Set(assigned).size).toBe(specs.length)expect(SPEC_SECONDS["55-message-scroll-characterization.spec.ts"]).toBe(109.548)expect(specSeconds).toEqual([- 150.249, 150.644, 151.022, 150.534, 151.049,- 150.933, 150.119, 151.048, 150.765, 151.066,+ 155.554, 155.114, 155.36, 155.929, 155.489,+ 155.164, 155.229, 154.758, 155.247, 156.185,])expect(predictedSeconds).toEqual([- 225.249, 225.644, 226.022, 225.534, 226.049,- 225.933, 225.119, 226.048, 225.765, 226.066,+ 230.554, 230.114, 230.36, 230.929, 230.489,+ 230.164, 230.229, 229.758, 230.247, 231.185,])expect(first.every((shard) => (shard.fixed_setup_seconds === E2E_FIXED_SETUP_SECONDSdiff --git a/scripts/ci/mobile-system-notification.test.ts b/scripts/ci/mobile-system-notification.test.tsnew file mode 100644index 000000000..e1438d7c9--- /dev/null+++ b/scripts/ci/mobile-system-notification.test.ts@@ -0,0 +1,191 @@+import { execFileSync } from "node:child_process"+import { readFileSync, readdirSync } from "node:fs"+import { resolve } from "node:path"+import { describe, expect, it } from "vitest"++const root = resolve(import.meta.dirname, "../..")+const tauriRoot = resolve(root, "src/desktop/src-tauri")+const pluginRoot = resolve(tauriRoot, "plugins/mobile-push")+const readRoot = (path: string) => readFileSync(resolve(root, path), "utf8")+const readTauri = (path: string) => readFileSync(resolve(tauriRoot, path), "utf8")+const readPlugin = (path: string) => readFileSync(resolve(pluginRoot, path), "utf8")++type Capability = {+ identifier: string+ windows: string[]+ platforms: string[]+ local: boolean+ remote: { urls: string[] }+ permissions: string[]+}++const commands = [+ "mobile_system_notification_check_permission",+ "mobile_system_notification_request_permission",+ "mobile_system_notification_snapshot",+ "mobile_system_notification_acknowledge_registration",+ "mobile_system_notification_take_activation",+ "mobile_system_notification_listen",+ "mobile_system_notification_unlisten",+]+const production = JSON.parse(readTauri("tauri.conf.json")) as {+ app: { security: { capabilities: string[] } }+}+const development = JSON.parse(readTauri("tauri.dev.conf.json")) as {+ app: { security: { capabilities: Array<string | Capability> } }+}+const capability = JSON.parse(+ readTauri("capabilities/mobile-system-notification-mobile.json"),+) as Capability+const permission = readTauri("permissions/mobile-system-notification.toml")+const build = readTauri("build.rs")+const cargo = readTauri("Cargo.toml")+const rustEntry = readTauri("src/lib.rs")+const runtime = readTauri("src/mobile_system_notification_runtime.rs")+const androidManifest = readPlugin("android/src/main/AndroidManifest.xml")+const androidBuild = readPlugin("android/build.gradle.kts")+const androidAppBuild = readTauri("gen/android/app/build.gradle.kts")+const androidRootBuild = readTauri("gen/android/build.gradle.kts")+const androidStore = readPlugin(+ "android/src/main/java/ai/alook/plugin/mobilepush/MobilePushStore.kt",+)+const androidService = readPlugin(+ "android/src/main/java/ai/alook/plugin/mobilepush/AlookFirebaseMessagingService.kt",+)+const androidPlugin = readPlugin(+ "android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt",+)+const iosPlugin = readPlugin("ios/Sources/MobilePushPlugin.swift")+const iosProject = readTauri("gen/apple/project.yml")+const iosEntitlements = readTauri(+ "gen/apple/alook-desktop_iOS/alook-desktop_iOS.entitlements",+)+const mobileRelease = readRoot(".github/workflows/mobile-release.yml")++describe("mobile system notification contract", () => {+ it("grants only the guarded seven-command API to trusted mobile WebViews", () => {+ const expected = {+ windows: ["main"],+ platforms: ["android", "iOS"],+ remote: { urls: ["https://alook.ai"] },+ local: false,+ permissions: ["mobile-system-notification"],+ }+ expect(production.app.security.capabilities).toContain("mobile-system-notification-mobile")+ expect(capability).toMatchObject(expected)+ const dev = development.app.security.capabilities.find(+ value => typeof value !== "string"+ && value.identifier === "mobile-system-notification-dev",+ )+ expect(dev).toMatchObject({+ ...expected,+ identifier: "mobile-system-notification-dev",+ local: true,+ remote: { urls: ["http://localhost:3000"] },+ })+ for (const command of commands) {+ expect(build).toContain(`"${command}"`)+ expect(permission).toContain(command)+ expect(rustEntry).toContain(`mobile_system_notification_runtime::${command}`)+ const commandSource = runtime.slice(runtime.indexOf(`fn ${command}`))+ expect(commandSource.indexOf("guard(&window)")).toBeGreaterThan(0)+ expect(commandSource.indexOf("guard(&window)")).toBeLessThan(+ commandSource.indexOf(".mobile_push()"),+ )+ }+ for (const item of [capability, dev as Capability]) {+ expect(item.permissions).not.toEqual(expect.arrayContaining([+ expect.stringMatching(/^(?:core:default$|core:event:|deep-link:|store:)/),+ ]))+ }+ })++ it("registers the private plugin on mobile and keeps provider state native", () => {+ expect(cargo).toContain(+ 'tauri-plugin-mobile-push = { path = "plugins/mobile-push" }',+ )+ expect(rustEntry).toContain(".plugin(tauri_plugin_mobile_push::init())")+ expect(readPlugin("build.rs")).toContain('"snapshot"')+ expect(readPlugin("build.rs")).toContain('"acknowledgeRegistration"')+ expect(readPlugin("build.rs")).toContain('"takeActivation"')+ const webAdapter = readRoot(+ "src/web/src/lib/community/mobile-system-notification.ts",+ )+ expect(webAdapter).not.toMatch(/(?:localStorage|indexedDB|console\.)/)+ expect(webAdapter).toContain('credentials: "same-origin"')+ expect(webAdapter).toContain('"mobile_system_notification_acknowledge_registration"')+ })++ it("locks Android FCM delivery, durable state, and credential-free builds", () => {+ expect(androidManifest).toContain("android.permission.POST_NOTIFICATIONS")+ expect(androidManifest).toContain("com.google.firebase.MESSAGING_EVENT")+ expect(androidManifest).toContain('android:exported="false"')+ expect(androidManifest).toContain('android:value="alook_messages"')+ expect(androidBuild).toContain("com.google.firebase:firebase-bom:34.19.0")+ expect(androidBuild).toContain("com.google.firebase:firebase-messaging")+ expect(androidBuild).not.toContain("firebase-messaging-ktx")+ expect(androidRootBuild).toContain("com.google.gms:google-services:4.5.0")+ expect(androidAppBuild).toContain('file("google-services.json").exists()')+ expect(readRoot(".gitignore")).toContain(+ "src/desktop/src-tauri/gen/android/app/google-services.json",+ )+ expect(execFileSync("git", ["ls-files", "--", "src/desktop/src-tauri/gen/android/app/google-services.json"], {+ cwd: root,+ encoding: "utf8",+ }).trim()).toBe("")+ expect(androidStore).toContain("Context.MODE_PRIVATE")+ expect(androidStore).toContain("acknowledgedToken")+ expect(androidService).toContain("override fun onNewToken")+ expect(androidService).toContain("override fun onMessageReceived")+ expect(androidService).toContain("FLAG_ACTIVITY_SINGLE_TOP")+ expect(androidService).toContain("setContentIntent")+ expect(androidPlugin).toContain("override fun onNewIntent")+ })++ it("locks iOS APNs callbacks, foreground/tap handling, and production entitlement", () => {+ expect(iosPlugin).toContain("registerForRemoteNotifications()")+ expect(iosPlugin).toContain("didRegisterForRemoteNotificationsWithDeviceToken")+ expect(iosPlugin).toContain("didFailToRegisterForRemoteNotificationsWithError")+ expect(iosPlugin).toContain("willPresent notification")+ expect(iosPlugin).toContain("didReceive response")+ expect(iosPlugin).toContain("UIApplication.didBecomeActiveNotification")+ expect(iosPlugin).toContain("MobilePushStore")+ expect(iosProject).toContain("aps-environment: $(APS_ENVIRONMENT)")+ expect(iosProject).toContain("APS_ENVIRONMENT: development")+ expect(iosProject).toContain("APS_ENVIRONMENT: production")+ expect(iosEntitlements).toContain("<key>aps-environment</key>")+ expect(mobileRelease).toContain(+ 'assert entitlements["aps-environment"] == "production"',+ )+ })++ it("installs the iOS notification delegate synchronously before deferred app work", () => {+ const initializer = iosPlugin.slice(+ iosPlugin.indexOf("override init()"),+ iosPlugin.indexOf("\n deinit"),+ )+ const delegateAssignment = initializer.indexOf(+ "UNUserNotificationCenter.current().delegate = bridge.notificationHandler",+ )+ const deferredMainWork = initializer.indexOf("DispatchQueue.main.async {")+ expect(delegateAssignment).toBeGreaterThan(0)+ expect(deferredMainWork).toBeGreaterThan(delegateAssignment)+ const deferred = initializer.slice(deferredMainWork)+ expect(deferred).toContain("MobilePushDelegateHooks.install()")+ expect(deferred).toContain("UIApplication.shared.registerForRemoteNotifications()")+ })++ it("keeps flat route data and provider tokens out of native logs", () => {+ const nativeSources = [+ ...readdirSync(resolve(pluginRoot, "android/src/main/java/ai/alook/plugin/mobilepush"))+ .filter(name => name.endsWith(".kt"))+ .map(name => readPlugin(`android/src/main/java/ai/alook/plugin/mobilepush/${name}`)),+ iosPlugin,+ ].join("\n")+ for (const field of ["notificationId", "messageId", "targetId"]) {+ expect(nativeSources).toContain(field)+ }+ expect(nativeSources).not.toMatch(/\b(?:Log\.[a-z]|print(?:ln)?\s*\()/)+ expect(nativeSources).not.toMatch(/(?:deepLink|serverId|channelId|messageContent)/)+ })+})diff --git a/scripts/ci/prepare-android-firebase.mjs b/scripts/ci/prepare-android-firebase.mjsnew file mode 100644index 000000000..24322f266--- /dev/null+++ b/scripts/ci/prepare-android-firebase.mjs@@ -0,0 +1,24 @@+import { chmodSync, writeFileSync } from "node:fs"++export function prepareAndroidFirebase(raw, target) {+ let config+ try {+ config = JSON.parse(raw ?? "")+ } catch {+ throw new Error("ANDROID_GOOGLE_SERVICES_JSON must contain valid Firebase client JSON")+ }+ const project = config?.project_info+ const client = config?.client?.find?.(+ (entry) => entry?.client_info?.android_client_info?.package_name === "ai.alook.android",+ )+ if (+ project?.project_id !== "alook-prod" ||+ project?.project_number !== "190599692413" ||+ client?.client_info?.mobilesdk_app_id !== "1:190599692413:android:316a5d23e2888ac6ce7114" ||+ !client?.api_key?.some?.((entry) => typeof entry?.current_key === "string" && entry.current_key.trim())+ ) {+ throw new Error("Firebase client configuration must match the registered alook-prod Android app")+ }+ writeFileSync(target, raw, { mode: 0o600 })+ chmodSync(target, 0o600)+}diff --git a/scripts/ci/prepare-android-firebase.test.ts b/scripts/ci/prepare-android-firebase.test.tsnew file mode 100644index 000000000..2325d3cc6--- /dev/null+++ b/scripts/ci/prepare-android-firebase.test.ts@@ -0,0 +1,65 @@+import { mkdtempSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { dirname, join } from "node:path"+import { describe, expect, it } from "vitest"++import { prepareAndroidFirebase } from "./prepare-android-firebase.mjs"+const fixture = {+ project_info: { project_id: "alook-prod", project_number: "190599692413" },+ client: [{+ client_info: {+ mobilesdk_app_id: "1:190599692413:android:316a5d23e2888ac6ce7114",+ android_client_info: { package_name: "ai.alook.android" },+ },+ api_key: [{ current_key: "private-fixture-sentinel" }],+ }],+}+function run(raw: string | undefined) {+ const cwd = mkdtempSync(join(tmpdir(), "firebase-ci-"))+ const target = join(cwd, "src/desktop/src-tauri/gen/android/app/google-services.json")+ mkdirSync(dirname(target), { recursive: true })+ writeFileSync(target, "previous-config", { mode: 0o644 })+ try {+ let status = 0+ let output = ""+ try {+ prepareAndroidFirebase(raw, target)+ } catch (error) {+ status = 1+ output = String(error)+ }+ return { status, output, content: readFileSync(target, "utf8"), mode: statSync(target).mode & 0o777 }+ } finally {+ rmSync(cwd, { recursive: true, force: true })+ }+}+describe("Android Firebase release configuration", () => {+ it("restores the exact configuration and tightens an existing file without logging its API key", () => {+ const raw = JSON.stringify(fixture)+ const result = run(raw)+ expect(result.status).toBe(0)+ expect(result.content).toBe(raw)+ if (process.platform !== "win32") expect(result.mode).toBe(0o600)+ expect(result.output).not.toContain("private-fixture-sentinel")+ })+ it.each([undefined, "private-fixture-sentinel", "null", "{}"])("rejects missing or malformed configuration without overwriting a file: %s", (raw) => {+ const result = run(raw)+ expect(result.status).not.toBe(0)+ expect(result.content).toBe("previous-config")+ expect(result.output).not.toContain("private-fixture-sentinel")+ })+ it.each(["project", "number", "package", "app", "key", "blankKey", "nonStringKey"])("rejects mismatched or missing %s", (field) => {+ const config = structuredClone(fixture)+ if (field === "project") config.project_info.project_id = "wrong-project"+ if (field === "number") config.project_info.project_number = "0"+ if (field === "package") config.client[0].client_info.android_client_info.package_name = "wrong.package"+ if (field === "app") config.client[0].client_info.mobilesdk_app_id = "wrong-app"+ if (field === "key") config.client[0].api_key = []+ if (field === "blankKey") config.client[0].api_key[0].current_key = " "+ if (field === "nonStringKey") Object.assign(config.client[0].api_key[0], { current_key: null })+ const result = run(JSON.stringify(config))+ expect(result.status).not.toBe(0)+ expect(result.content).toBe("previous-config")+ expect(result.output).not.toContain("private-fixture-sentinel")+ })+})diff --git a/scripts/ci/queue-migration.test.ts b/scripts/ci/queue-migration.test.tsnew file mode 100644index 000000000..ca935d252--- /dev/null+++ b/scripts/ci/queue-migration.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest"+import {+ QUEUE_MIGRATION_RESOURCES,+ buildQueueMigrationPlan,+} from "../cloudflare/queue-migration.mjs"++describe("queue resource migration plan", () => {+ it("is data-only, ordered, and never dual-writes", () => {+ const plan = buildQueueMigrationPlan()+ expect(plan.mode).toBe("plan-only")+ expect(plan.executesCommands).toBe(false)+ expect(plan.dualWrite).toBe(false)+ expect(plan.phases.map((phase) => phase.id)).toEqual([+ "prepare",+ "deploy-compatible-consumer",+ "producer-cutover",+ "drain-and-observe",+ "cleanup",+ ])+ expect(plan.phases.find((phase) => phase.id === "producer-cutover")?.gate)+ .toContain("exactly one producer binding")+ })++ it("keeps legacy deletion behind a separate post-drain authorization", () => {+ const plan = buildQueueMigrationPlan()+ const cleanup = plan.phases.at(-1)!+ expect(cleanup.id).toBe("cleanup")+ expect(cleanup.separatelyAuthorized).toBe(true)+ expect(cleanup.gate).toContain("STOP")+ expect(cleanup.commands.join("\n")).toContain(QUEUE_MIGRATION_RESOURCES.oldQueue)+ expect(cleanup.commands.join("\n")).toContain(QUEUE_MIGRATION_RESOURCES.oldDlq)+ expect(cleanup.commands.join("\n")).toContain(QUEUE_MIGRATION_RESOURCES.oldWorker)+ })+})diff --git a/scripts/ci/system-notifications-desktop.test.ts b/scripts/ci/system-notifications-desktop.test.tsnew file mode 100644index 000000000..5014f8ae7--- /dev/null+++ b/scripts/ci/system-notifications-desktop.test.ts@@ -0,0 +1,81 @@+import { readFileSync } from "node:fs"+import { resolve } from "node:path"+import { describe, expect, it } from "vitest"++const root = resolve(import.meta.dirname, "../../src/desktop/src-tauri")+const read = (path: string) => readFileSync(resolve(root, path), "utf8")++const desktopCommands = [+ "daemon_runtime_capability",+ "daemon_pair",+ "set_window_theme",+ "close_splashscreen",+ "desktop_zoom_shortcut",+ "desktop_system_notification_show",+ "desktop_system_notification_listen",+ "desktop_system_notification_take_activation",+ "desktop_system_notification_unlisten",+]++function quotedValues(source: string) {+ return Array.from(source.matchAll(/"([a-z][a-z0-9_]*)"/g), (match) => match[1]!)+}++describe("desktop system notification contract", () => {+ it("keeps the build manifest and desktop ACL at the exact old-five plus new-four set", () => {+ const manifestCommands = quotedValues(read("build.rs"))+ .filter((command) => !command.startsWith("native_oauth_")+ && !command.startsWith("mobile_share_image_")+ && !command.startsWith("mobile_system_notification_"))+ const permissionCommands = quotedValues(+ read("permissions/desktop-commands.toml").match(/commands\.allow\s*=\s*\[[^\]]*\]/s)?.[0] ?? "",+ )+ expect(manifestCommands).toEqual(desktopCommands)+ expect(permissionCommands).toEqual(desktopCommands)+ })++ it("preserves the existing narrow production capability and desktop scheme", () => {+ const capability = JSON.parse(read("capabilities/desktop.json")) as {+ identifier: string+ local: boolean+ windows: string[]+ platforms: string[]+ remote: { urls: string[] }+ permissions: string[]+ }+ const config = JSON.parse(read("tauri.conf.json")) as {+ plugins: { "deep-link": { desktop: { schemes: string[] } } }+ }+ expect(capability).toMatchObject({+ identifier: "desktop-capability",+ local: true,+ windows: ["main"],+ remote: { urls: ["https://alook.ai"] },+ permissions: ["clipboard-manager:allow-write-image", "desktop-commands"],+ })+ expect(capability.platforms).toEqual(expect.arrayContaining(["linux", "macOS", "windows"]))+ expect(config.plugins["deep-link"].desktop.schemes).toEqual(["ai.alook.desktop"])+ })++ it("keeps platform behavior split between exact activation and Linux focus-only", () => {+ const source = read("src/system_notifications.rs")+ expect(source).toContain('#[cfg(target_os = "macos")]')+ expect(source).toContain('#[cfg(windows)]')+ expect(source).toContain('#[cfg(target_os = "linux")]')+ expect(source).toContain('<toast activationType=\\"protocol\\"')+ expect(source).toContain("didReceiveNotificationResponse")+ const linux = source.slice(source.lastIndexOf('#[cfg(target_os = "linux")]'))+ expect(linux).toContain("show_main_window")+ expect(linux).not.toContain("activate(&app")+ })++ it("does not gate delivery on main-window visibility and preserves real Quit", () => {+ const runtime = read("src/system_notifications.rs")+ const commands = read("src/commands.rs")+ const app = read("src/lib.rs")+ expect(runtime).not.toContain("is_visible")+ expect(app).toContain("api.prevent_close();")+ expect(app).toContain("let _ = window.hide();")+ expect(commands).toContain("app.exit(0);")+ })+})diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.tsindex 0d3c53867..bd94ad8ba 100644--- a/scripts/ci/workflow-contract.test.ts+++ b/scripts/ci/workflow-contract.test.ts@@ -27,7 +27,7 @@ type WorkerModuleContract = {wranglerConfig: string}-const directWorkerModules = ["ws-do", "email-worker", "wake-worker", "web"].map((name): WorkerModuleContract => {+const directWorkerModules = ["ws-do", "email-worker", "queue-worker", "web"].map((name): WorkerModuleContract => {const moduleRoot = resolve(import.meta.dirname, `../../src/${name}`)return {name,@@ -436,13 +436,15 @@ describe("CI workflow graph", () => {expect(e2e).toContain("if: needs.scope.outputs.run_e2e == 'true'")expect(e2e).toContain("- name: Create local bindings\n run:")+ expect(e2e).toContain("cp src/queue-worker/.dev.vars.example src/queue-worker/.dev.vars")+ expect(e2e.match(/ci-e2e-encryption-key-32chars!!/g)).toHaveLength(2)expect(e2e).toContain("- run: pnpm run db:migrate")expect(e2e).toContain("- name: Start dev servers\n run: |")expect(e2e).toContain("- name: Wait for services\n run: |")expect(e2e.indexOf("pnpm --filter @alook/ws-do dev &")).toBeLessThan(- e2e.indexOf("pnpm --filter @alook/wake-worker dev &"),+ e2e.indexOf("pnpm --filter @alook/queue-worker dev &"),)- expect(e2e.indexOf("pnpm --filter @alook/wake-worker dev &")).toBeLessThan(+ expect(e2e.indexOf("pnpm --filter @alook/queue-worker dev &")).toBeLessThan(e2e.indexOf("pnpm --filter @alook/email-worker dev &"),)expect(e2e.indexOf("pnpm --filter @alook/email-worker dev &")).toBeLessThan(@@ -627,7 +629,7 @@ describe("CI test budgets", () => {expect(windows).toContain('filters+=("--filter=@alook/$suite")')expect(windows).toContain('pnpm turbo run test "${filters[@]}"')expect(windows).not.toContain("--affected")- for (const packageName of ["web", "email-worker", "ws-do", "wake-worker"]) {+ for (const packageName of ["web", "email-worker", "ws-do", "queue-worker"]) {expect(windows).not.toContain(`--filter=@alook/${packageName}`)}expect(windows).not.toContain("--project ci-scripts")@@ -882,7 +884,7 @@ describe("Turbo CI execution", () => {"src/daemon/agent-driver","src/email-worker","src/ws-do",- "src/wake-worker",+ "src/queue-worker","src/app","tests/utils","scripts/ci",@@ -916,7 +918,7 @@ describe("Turbo CI execution", () => {for (const projects of ["projects=(ci-scripts)","projects=(email-worker-node email-worker-runtime)",- "projects=(wake-worker-node wake-worker-runtime)",+ "projects=(queue-worker-node queue-worker-runtime)","projects=(web-node web-dom web-runtime auth-node auth-runtime)","projects=(ws-do-node ws-do-runtime)",]) expect(linux).toContain(projects)@@ -1002,8 +1004,8 @@ describe("Turbo CI execution", () => {const webRuntime = readRepo("src/web/test-runtime/worker.runtime.test.ts")const emailNode = readRepo("src/email-worker/src/index.test.ts")const emailRuntime = readRepo("src/email-worker/test-runtime/worker.runtime.test.ts")- const wakeNode = readRepo("src/wake-worker/src/index.test.ts")- const wakeRuntime = readRepo("src/wake-worker/test-runtime/worker.runtime.test.ts")+ const queueNode = readRepo("src/queue-worker/src/index.test.ts")+ const queueRuntime = readRepo("src/queue-worker/test-runtime/worker.runtime.test.ts")expect(existsSync(resolve(import.meta.dirname, "../../src/ws-do/src/rate-limit-do.test.ts"))).toBe(false)expect(wsRuntime).toContain("persists the counter across stubs for the same Durable Object id")@@ -1018,11 +1020,11 @@ describe("Turbo CI execution", () => {expect(emailRuntime).toContain("forwards status and sync routes to the real IMAP Durable Object")expect(emailRuntime).toContain("rejects unsupported methods, paths, and missing IMAP account ids")- expect(wakeNode).not.toContain("returns 400 on invalid JSON body")- expect(wakeNode).not.toContain("returns 405 for non-POST methods")- expect(wakeNode).not.toContain("returns 200 { status: ok } for GET /health")- expect(wakeRuntime).toContain("rejects invalid JSON and non-POST dev requests at the real entrypoint")- expect(wakeRuntime).toContain("loads production migrations and serves the production entrypoint")+ expect(queueNode).not.toContain("returns 400 on invalid JSON body")+ expect(queueNode).not.toContain("returns 405 for non-POST methods")+ expect(queueNode).not.toContain("returns 200 { status: ok } for GET /health")+ expect(queueRuntime).toContain("rejects invalid JSON and non-POST dev requests at the real entrypoint")+ expect(queueRuntime).toContain("loads production migrations and serves the production entrypoint")})})@@ -1135,6 +1137,13 @@ describe("Desktop image clipboard", () => {remote: { urls: ["http://localhost:3000"] },permissions: ["allow-mobile-share-image-copy", "allow-mobile-share-image-save"],}),+ expect.objectContaining({+ identifier: "mobile-system-notification-dev",+ local: true,+ platforms: ["android", "iOS"],+ remote: { urls: ["http://localhost:3000"] },+ permissions: ["mobile-system-notification"],+ }),])})})@@ -1186,6 +1195,9 @@ describe("Mobile release availability", () => {'entitlements["com.apple.developer.associated-domains"]',)expect(mobileReleaseWorkflow).toContain("applinks:auth.alook.ai")+ expect(mobileReleaseWorkflow).toContain(+ 'entitlements["aps-environment"] == "production"',+ )expect(mobileReleaseWorkflow).toContain("xcrun altool --upload-app")expect(mobileReleaseWorkflow).toContain("actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a")expect(bumpScript).toContain('args.includes("--mobile")')@@ -1194,6 +1206,15 @@ describe("Mobile release availability", () => {expect(bumpScript).toContain("iOS CFBundleShortVersionString")})+ it("restores Firebase client configuration after Android init and before compiling", () => {+ const init = mobileReleaseWorkflow.indexOf("pnpm tauri android init")+ const restore = mobileReleaseWorkflow.indexOf("./scripts/ci/prepare-android-firebase.mjs")+ const build = mobileReleaseWorkflow.indexOf("pnpm tauri android build")+ expect(mobileReleaseWorkflow).toContain("ANDROID_GOOGLE_SERVICES_JSON: ${{ secrets.ANDROID_GOOGLE_SERVICES_JSON }}")+ expect(restore).toBeGreaterThan(init)+ expect(build).toBeGreaterThan(restore)+ })+it("attaches a signed Android APK to --mobile GitHub releases without Google Play", () => {expect(desktopAndroidConfig.identifier).toBe("ai.alook.android")expect(androidGradle).toContain('namespace = "ai.alook.android"')diff --git a/scripts/cloudflare/queue-migration.mjs b/scripts/cloudflare/queue-migration.mjsnew file mode 100644index 000000000..26e803419--- /dev/null+++ b/scripts/cloudflare/queue-migration.mjs@@ -0,0 +1,91 @@+#!/usr/bin/env node++import { pathToFileURL } from "node:url"++export const QUEUE_MIGRATION_RESOURCES = Object.freeze({+ oldWorker: "alook-wake-worker",+ oldQueue: "alook-wake",+ oldDlq: "alook-wake-dlq",+ newWorker: "alook-queue-worker",+ newQueue: "alook-queue",+ newDlq: "alook-queue-dlq",+})++export function buildQueueMigrationPlan() {+ const names = QUEUE_MIGRATION_RESOURCES+ return {+ mode: "plan-only",+ executesCommands: false,+ dualWrite: false,+ phases: [+ {+ id: "prepare",+ mutating: true,+ commands: [+ `pnpm exec wrangler queues create ${names.newQueue}`,+ `pnpm exec wrangler queues create ${names.newDlq}`,+ ],+ gate: "Confirm the new Queue and DLQ exist with zero producers.",+ },+ {+ id: "deploy-compatible-consumer",+ mutating: true,+ commands: ["pnpm --filter @alook/queue-worker deploy"],+ gate: "Verify the new consumer accepts legacy wake and v1 queue tasks.",+ },+ {+ id: "producer-cutover",+ mutating: true,+ commands: ["pnpm --filter @alook/web deploy"],+ gate: `Verify Web has exactly one producer binding, targeting ${names.newQueue}; never dual-write.`,+ },+ {+ id: "drain-and-observe",+ mutating: false,+ commands: [+ `pnpm exec wrangler queues info ${names.oldQueue}`,+ `pnpm exec wrangler queues info ${names.newQueue}`,+ `pnpm exec wrangler queues info ${names.newDlq}`,+ ],+ gate: "Old depth and oldest age are zero, no old producer remains, and new wake traffic is healthy.",+ },+ {+ id: "cleanup",+ mutating: true,+ separatelyAuthorized: true,+ commands: [+ `pnpm exec wrangler queues delete ${names.oldQueue}`,+ `pnpm exec wrangler queues delete ${names.oldDlq}`,+ `pnpm exec wrangler delete --name ${names.oldWorker}`,+ ],+ gate: "STOP unless exact production cleanup authorization is recorded after the drain gate passes.",+ },+ ],+ }+}++function renderText(plan) {+ const lines = [+ "Queue migration plan (display only; no commands were executed)",+ "No dual-write: cut over the single Web producer only after the compatible consumer is ready.",+ ]+ for (const phase of plan.phases) {+ lines.push("", `${phase.id}${phase.separatelyAuthorized ? " [SEPARATE AUTHORIZATION REQUIRED]" : ""}`)+ lines.push(...phase.commands.map((command) => ` ${command}`), ` Gate: ${phase.gate}`)+ }+ return lines.join("\n")+}++function main(argv) {+ if (argv.includes("--execute")) {+ console.error("Refusing --execute: this script is intentionally plan/read-only.")+ process.exitCode = 2+ return+ }+ const plan = buildQueueMigrationPlan()+ console.log(argv.includes("--json") ? JSON.stringify(plan, null, 2) : renderText(plan))+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main(process.argv.slice(2))+}diff --git a/src/app/README.md b/src/app/README.mdindex 9c5b330c9..b3e716076 100644--- a/src/app/README.md+++ b/src/app/README.md@@ -73,7 +73,7 @@ All services share a single SQLite database (Cloudflare D1 local mode) with stat│ └── migrations/ # SQL migration files├── email-worker/ # Email worker (wrangler.toml, .dev.vars)├── ws-do/ # WebSocket Durable Object worker-├── wake-worker/ # Agent wake dispatcher+├── queue-worker/ # Queue task consumer (agent wake + mobile push)├── daemon/ # Private machine credentials, daemon state, and logs├── logs/ # Service logs (web, email, WS, and wake workers)└── .pids.json # PID tracking for running servicesdiff --git a/src/app/scripts/bundle.ts b/src/app/scripts/bundle.tsindex 32ec5fe26..94a7a547f 100644--- a/src/app/scripts/bundle.ts+++ b/src/app/scripts/bundle.ts@@ -1,7 +1,7 @@#!/usr/bin/env bun/*** Bundle script — run in CI before `npm publish` of @alook/app.- * Builds web (opennextjs-cloudflare), email-worker, ws-do, and wake-worker into+ * Builds web (opennextjs-cloudflare), email-worker, ws-do, and queue-worker into* pre-compiled bundles that can run with `wrangler dev --local` without* needing source code or node_modules.*/@@ -98,19 +98,19 @@ writeFileSync(wsToml.replace('main = "src/index.ts"', 'main = "index.js"'),);-// --- Build Wake Worker ----console.log("\n=== Building Wake Worker ===\n");-const wakeSrc = join(monoRoot, "src", "wake-worker");-const wakeDest = join(bundledDir, "wake-worker");-mkdirSync(wakeDest, { recursive: true });+// --- Build Queue Worker ---+console.log("\n=== Building Queue Worker ===\n");+const queueSrc = join(monoRoot, "src", "queue-worker");+const queueDest = join(bundledDir, "queue-worker");+mkdirSync(queueDest, { recursive: true });-run("npx wrangler deploy --dry-run --outdir dist", wakeSrc);-cpSync(join(wakeSrc, "dist", "index.js"), join(wakeDest, "index.js"));+run("npx wrangler deploy --dry-run --outdir dist", queueSrc);+cpSync(join(queueSrc, "dist", "index.js"), join(queueDest, "index.js"));-const wakeToml = readFileSync(join(wakeSrc, "wrangler.toml"), "utf-8");+const queueToml = readFileSync(join(queueSrc, "wrangler.toml"), "utf-8");writeFileSync(- join(wakeDest, "wrangler.toml"),- wakeToml.replace('main = "src/index.ts"', 'main = "index.js"'),+ join(queueDest, "wrangler.toml"),+ queueToml.replace('main = "src/index.ts"', 'main = "index.js"'),);console.log("\n✓ Bundle complete at:", bundledDir);diff --git a/src/app/src/commands/onboard.ts b/src/app/src/commands/onboard.tsindex d4ac6924a..5de37673f 100644--- a/src/app/src/commands/onboard.ts+++ b/src/app/src/commands/onboard.ts@@ -27,14 +27,14 @@ export function onboardCommand(): Command {.option("--port-web <port>", "Web server port", String(DEFAULT_PORTS.web)).option("--port-email <port>", "Email worker port", String(DEFAULT_PORTS.emailWorker)).option("--port-ws <port>", "WebSocket worker port", String(DEFAULT_PORTS.wsDo))- .option("--port-wake <port>", "Wake worker port", String(DEFAULT_PORTS.wakeWorker))+ .option("--port-wake <port>", "Wake worker port", String(DEFAULT_PORTS.queueWorker)).option("--skip-register", "Skip account creation (just start services)").action(async (opts) => {const ports = {web: parseInt(opts.portWeb, 10),emailWorker: parseInt(opts.portEmail, 10),wsDo: parseInt(opts.portWs, 10),- wakeWorker: parseInt(opts.portWake, 10),+ queueWorker: parseInt(opts.portWake, 10),};console.log("\n🚀 Alook Local Setup\n");diff --git a/src/app/src/commands/start.ts b/src/app/src/commands/start.tsindex 3b995a674..9608070f8 100644--- a/src/app/src/commands/start.ts+++ b/src/app/src/commands/start.ts@@ -12,7 +12,7 @@ export function startCommand(): Command {.option("--port-web <port>", "Web server port", String(DEFAULT_PORTS.web)).option("--port-email <port>", "Email worker port", String(DEFAULT_PORTS.emailWorker)).option("--port-ws <port>", "WebSocket worker port", String(DEFAULT_PORTS.wsDo))- .option("--port-wake <port>", "Wake worker port", String(DEFAULT_PORTS.wakeWorker))+ .option("--port-wake <port>", "Wake worker port", String(DEFAULT_PORTS.queueWorker)).action(async (opts) => {if (!isInstalled()) {console.error("Error: Alook not installed. Run 'npx @alook/app onboard' first.");@@ -23,7 +23,7 @@ export function startCommand(): Command {web: parseInt(opts.portWeb, 10),emailWorker: parseInt(opts.portEmail, 10),wsDo: parseInt(opts.portWs, 10),- wakeWorker: parseInt(opts.portWake, 10),+ queueWorker: parseInt(opts.portWake, 10),};const alreadyRunning = isRunning();diff --git a/src/app/src/lib/checks.ts b/src/app/src/lib/checks.tsindex 87afdc7f8..ca17efeb3 100644--- a/src/app/src/lib/checks.ts+++ b/src/app/src/lib/checks.ts@@ -16,12 +16,12 @@ export async function checkPort(port: number): Promise<boolean> {});}-export async function checkPorts(ports: { web: number; emailWorker: number; wsDo: number; wakeWorker: number }): Promise<void> {+export async function checkPorts(ports: { web: number; emailWorker: number; wsDo: number; queueWorker: number }): Promise<void> {const checks = [{ name: "web", port: ports.web },{ name: "email-worker", port: ports.emailWorker },{ name: "ws-do", port: ports.wsDo },- { name: "wake-worker", port: ports.wakeWorker },+ { name: "queue-worker", port: ports.queueWorker },];for (const { name, port } of checks) {diff --git a/src/app/src/lib/constants.ts b/src/app/src/lib/constants.tsindex ac1089b7d..b6a9356be 100644--- a/src/app/src/lib/constants.ts+++ b/src/app/src/lib/constants.ts@@ -23,7 +23,7 @@ export const DEFAULT_PORTS: DevPortProfile = {web: 15210,emailWorker: 15211,wsDo: 15212,- wakeWorker: 15213,+ queueWorker: 15213,};export const WEB_URL = (port: number) => `http://localhost:${port}`;diff --git a/src/app/src/lib/pid.ts b/src/app/src/lib/pid.tsindex 63334d2c0..97761b226 100644--- a/src/app/src/lib/pid.ts+++ b/src/app/src/lib/pid.ts@@ -6,12 +6,12 @@ interface PidRecord {web?: number;emailWorker?: number;wsDo?: number;- wakeWorker?: number;+ queueWorker?: number;ports?: {web?: number;emailWorker?: number;wsDo?: number;- wakeWorker?: number;+ queueWorker?: number;};}diff --git a/src/app/src/lib/secrets.ts b/src/app/src/lib/secrets.tsindex 5b2abc1d4..3e36c94b8 100644--- a/src/app/src/lib/secrets.ts+++ b/src/app/src/lib/secrets.ts@@ -17,9 +17,28 @@ function extractKey(filePath: string, key: string): string | null {}}+function setKey(content: string, key: string, value: string): string {+ const line = `${key}=${value}`;+ const pattern = new RegExp(`^${key}=.*$`, "m");+ const next = pattern.test(content) ? content.replace(pattern, line) : `${content.trimEnd()}\n${line}`;+ return `${next.trimEnd()}\n`;+}++function syncWorkerVars(filePath: string, encryptionKey: string, emptyKeys: string[] = []): void {+ let content = existsSync(filePath) ? readFileSync(filePath, "utf-8") : "";+ content = setKey(content, "ENCRYPTION_KEY", encryptionKey);+ for (const key of emptyKeys) {+ if (extractKey(filePath, key) === null && !new RegExp(`^${key}=`, "m").test(content)) {+ content = setKey(content, key, "");+ }+ }+ writeFileSync(filePath, content, { mode: 0o600 });+}+export function ensureSecrets(webPort: number): void {const webVars = join(SELF_HOSTED_DIR, "web", ".dev.vars");const emailVars = join(SELF_HOSTED_DIR, "email-worker", ".dev.vars");+ const queueVars = join(SELF_HOSTED_DIR, "queue-worker", ".dev.vars");if (!existsSync(webVars)) {const authSecret = generateSecret();@@ -33,16 +52,31 @@ export function ensureSecrets(webPort: number): void {`GOOGLE_CLIENT_ID=`,`GOOGLE_CLIENT_SECRET=`,].join("\n");- writeFileSync(webVars, content, { mode: 0o600 });+ writeFileSync(webVars, `${content}\n`, { mode: 0o600 });console.log("Generated web secrets");-- writeFileSync(emailVars, `ENCRYPTION_KEY=${encryptionKey}\n`, { mode: 0o600 });- console.log("Generated email-worker secrets");- } else if (!existsSync(emailVars)) {- const encryptionKey = extractKey(webVars, "ENCRYPTION_KEY") || generateSecret();- writeFileSync(emailVars, `ENCRYPTION_KEY=${encryptionKey}\n`, { mode: 0o600 });- console.log("Synced email-worker secrets from web");} else {- console.log("Secrets already exist, skipping");+ const existingKey = extractKey(webVars, "ENCRYPTION_KEY");+ if (!existingKey) {+ writeFileSync(+ webVars,+ setKey(readFileSync(webVars, "utf-8"), "ENCRYPTION_KEY", generateSecret()),+ { mode: 0o600 },+ );+ }}++ const encryptionKey = extractKey(webVars, "ENCRYPTION_KEY");+ if (!encryptionKey) throw new Error("Failed to establish the shared ENCRYPTION_KEY");++ syncWorkerVars(emailVars, encryptionKey);+ syncWorkerVars(queueVars, encryptionKey, [+ "APNS_TEAM_ID",+ "APNS_KEY_ID",+ "APNS_PRIVATE_KEY",+ "APNS_TOPIC",+ "FCM_PROJECT_ID",+ "FCM_CLIENT_EMAIL",+ "FCM_PRIVATE_KEY",+ ]);+ console.log("Synced worker secrets from web");}diff --git a/src/app/src/lib/services.ts b/src/app/src/lib/services.tsindex 6a5a4c28b..94cb8df89 100644--- a/src/app/src/lib/services.ts+++ b/src/app/src/lib/services.ts@@ -10,7 +10,7 @@ interface ServicePorts {web: number;emailWorker: number;wsDo: number;- wakeWorker: number;+ queueWorker: number;}interface StartOptions {@@ -76,7 +76,7 @@ function killProcess(pid: number): boolean {export function startServices(ports: ServicePorts, opts: StartOptions = {}): void {const existing = readPids();- const anyAlive = [existing.web, existing.emailWorker, existing.wsDo, existing.wakeWorker].some(+ const anyAlive = [existing.web, existing.emailWorker, existing.wsDo, existing.queueWorker].some((pid) => pid && isAlive(pid),);if (anyAlive) {@@ -90,35 +90,35 @@ export function startServices(ports: ServicePorts, opts: StartOptions = {}): voilet webChild: ChildProcess;let emailChild: ChildProcess;let wsChild: ChildProcess;- let wakeChild: ChildProcess;+ let queueChild: ChildProcess;if (isDevMode) {const root = process.env.ALOOK_PROJECT_ROOT!;const webDir = join(root, "src", "web");const emailDir = join(root, "src", "email-worker");const wsDir = join(root, "src", "ws-do");- const wakeDir = join(root, "src", "wake-worker");+ const queueDir = join(root, "src", "queue-worker");const persistTo = ["--persist-to", join(SELF_HOSTED_DIR, "web", ".wrangler", "state")];webChild = spawnService("web", "npx", ["next", "dev", "--port", String(ports.web)], webDir, foreground);emailChild = spawnService("email-worker", "npx", ["wrangler", "dev", "--local", "--port", String(ports.emailWorker), ...persistTo], emailDir, foreground);wsChild = spawnService("ws-do", "npx", ["wrangler", "dev", "--local", "--port", String(ports.wsDo), ...persistTo], wsDir, foreground);- wakeChild = spawnService("wake-worker", "npx", ["wrangler", "dev", "--local", "--port", String(ports.wakeWorker), ...persistTo], wakeDir, foreground);+ queueChild = spawnService("queue-worker", "npx", ["wrangler", "dev", "--local", "--port", String(ports.queueWorker), ...persistTo], queueDir, foreground);} else {const persistTo = ["--persist-to", join(SELF_HOSTED_DIR, "web", ".wrangler", "state")];const web = wranglerProcess(["dev", "--local", "--port", String(ports.web), ...persistTo]);const email = wranglerProcess(["dev", "--local", "--port", String(ports.emailWorker), ...persistTo]);const ws = wranglerProcess(["dev", "--local", "--port", String(ports.wsDo), ...persistTo]);- const wake = wranglerProcess(["dev", "--local", "--port", String(ports.wakeWorker), ...persistTo]);+ const queue = wranglerProcess(["dev", "--local", "--port", String(ports.queueWorker), ...persistTo]);webChild = spawnService("web", web.command, web.args, join(SELF_HOSTED_DIR, "web"), foreground);emailChild = spawnService("email-worker", email.command, email.args, join(SELF_HOSTED_DIR, "email-worker"), foreground);wsChild = spawnService("ws-do", ws.command, ws.args, join(SELF_HOSTED_DIR, "ws-do"), foreground);- wakeChild = spawnService("wake-worker", wake.command, wake.args, join(SELF_HOSTED_DIR, "wake-worker"), foreground);+ queueChild = spawnService("queue-worker", queue.command, queue.args, join(SELF_HOSTED_DIR, "queue-worker"), foreground);}- if (!webChild.pid || !emailChild.pid || !wsChild.pid || !wakeChild.pid) {+ if (!webChild.pid || !emailChild.pid || !wsChild.pid || !queueChild.pid) {console.error("Error: failed to start one or more services.");- for (const child of [webChild, emailChild, wsChild, wakeChild]) {+ for (const child of [webChild, emailChild, wsChild, queueChild]) {if (child.pid) killProcess(child.pid);}process.exit(1);@@ -128,19 +128,19 @@ export function startServices(ports: ServicePorts, opts: StartOptions = {}): voiweb: webChild.pid,emailWorker: emailChild.pid,wsDo: wsChild.pid,- wakeWorker: wakeChild.pid,+ queueWorker: queueChild.pid,ports: {web: ports.web,emailWorker: ports.emailWorker,wsDo: ports.wsDo,- wakeWorker: ports.wakeWorker,+ queueWorker: ports.queueWorker,},});console.log(` Web: http://localhost:${ports.web} (pid=${webChild.pid})`);console.log(` Email Worker: port ${ports.emailWorker} (pid=${emailChild.pid})`);console.log(` WS-DO: port ${ports.wsDo} (pid=${wsChild.pid})`);- console.log(` Wake Worker: port ${ports.wakeWorker} (pid=${wakeChild.pid})`);+ console.log(` Queue Worker: port ${ports.queueWorker} (pid=${queueChild.pid})`);if (foreground) {let exiting = false;@@ -148,7 +148,7 @@ export function startServices(ports: ServicePorts, opts: StartOptions = {}): voiif (exiting) return;exiting = true;console.log("\nStopping services...");- for (const child of [webChild, emailChild, wsChild, wakeChild]) {+ for (const child of [webChild, emailChild, wsChild, queueChild]) {if (child.pid) killProcess(child.pid);}clearPids();@@ -183,7 +183,7 @@ export function stopServices(): void {export function isRunning(): boolean {const pids = readPids();- return [pids.web, pids.emailWorker, pids.wsDo, pids.wakeWorker].some(+ return [pids.web, pids.emailWorker, pids.wsDo, pids.queueWorker].some((pid) => pid && isAlive(pid),);}diff --git a/src/app/src/lib/wrangler-config.ts b/src/app/src/lib/wrangler-config.tsindex 6f851c4e2..b15f2b2a1 100644--- a/src/app/src/lib/wrangler-config.ts+++ b/src/app/src/lib/wrangler-config.ts@@ -75,7 +75,7 @@ export function removeServiceBinding(content: string, binding: string): string {.join("");}-export function patchWranglerConfigs(ports: { web: number; emailWorker: number; wsDo: number; wakeWorker: number }): void {+export function patchWranglerConfigs(ports: { web: number; emailWorker: number; wsDo: number; queueWorker: number }): void {const webToml = join(SELF_HOSTED_DIR, "web", "wrangler.toml");let webContent = deduplicateDevSection(readFileSync(webToml, "utf-8"));@@ -92,7 +92,7 @@ export function patchWranglerConfigs(ports: { web: number; emailWorker: number;webContent = setVar(webContent, "DEV_WS_DO_URL", `http://localhost:${ports.wsDo}`);webContent = setVar(webContent, "DEV_EMAIL_WORKER_URL", `http://localhost:${ports.emailWorker}`);- webContent = setVar(webContent, "DEV_WAKE_WORKER_URL", `http://localhost:${ports.wakeWorker}`);+ webContent = setVar(webContent, "DEV_QUEUE_WORKER_URL", `http://localhost:${ports.queueWorker}`);webContent = setVar(webContent, "NODE_ENV", "development");webContent = setVar(webContent, "BLOG_DISCOVERY_REQUIRED", "false");webContent = removeServiceBinding(webContent, "BLOG_WORKER");@@ -100,10 +100,10 @@ export function patchWranglerConfigs(ports: { web: number; emailWorker: number;setDevPort(join(SELF_HOSTED_DIR, "email-worker", "wrangler.toml"), ports.emailWorker);setDevPort(join(SELF_HOSTED_DIR, "ws-do", "wrangler.toml"), ports.wsDo);- setDevPort(join(SELF_HOSTED_DIR, "wake-worker", "wrangler.toml"), ports.wakeWorker);+ setDevPort(join(SELF_HOSTED_DIR, "queue-worker", "wrangler.toml"), ports.queueWorker);setInspectorPort(join(SELF_HOSTED_DIR, "web", "wrangler.toml"), 19229);setInspectorPort(join(SELF_HOSTED_DIR, "ws-do", "wrangler.toml"), 19230);setInspectorPort(join(SELF_HOSTED_DIR, "email-worker", "wrangler.toml"), 19231);- setInspectorPort(join(SELF_HOSTED_DIR, "wake-worker", "wrangler.toml"), 19232);+ setInspectorPort(join(SELF_HOSTED_DIR, "queue-worker", "wrangler.toml"), 19232);}diff --git a/src/app/test/checks.test.ts b/src/app/test/checks.test.tsindex aea1da201..c5b0b7228 100644--- a/src/app/test/checks.test.ts+++ b/src/app/test/checks.test.ts@@ -1,6 +1,28 @@import { describe, it, expect, vi, beforeEach } from "vitest";+const mocks = vi.hoisted(() => ({+ createConnection: vi.fn(),+}));++vi.mock("net", () => ({+ createConnection: mocks.createConnection,+}));++function connectionThatEmits(eventToEmit: "connect" | "error") {+ const connection = {+ destroy: vi.fn(),+ on: vi.fn(),+ };+ connection.on.mockImplementation((event: string, handler: () => void) => {+ if (event === eventToEmit) handler();+ return connection;+ });+ return connection;+}+describe("checks", () => {+ beforeEach(() => vi.clearAllMocks());+describe("checkNodeVersion", () => {it("does not exit for Node >= 20", async () => {const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {@@ -18,10 +40,36 @@ describe("checks", () => {describe("checkPort", () => {it("returns true for an unused port", async () => {+ mocks.createConnection.mockReturnValue(connectionThatEmits("error"));const { checkPort } = await import("../src/lib/checks.js");- // Port 0 or a random high port should be unusedconst result = await checkPort(49999);expect(result).toBe(true);});});++ describe("checkPorts", () => {+ it("accepts four deterministically available service ports", async () => {+ mocks.createConnection.mockImplementation(() => connectionThatEmits("error"));+ const exit = vi.spyOn(process, "exit").mockImplementation((() => {+ throw new Error("unexpected exit");+ }) as never);+ const { checkPorts } = await import("../src/lib/checks.js");++ await expect(checkPorts({+ web: 3000,+ emailWorker: 8787,+ wsDo: 8789,+ queueWorker: 8790,+ })).resolves.toBeUndefined();++ expect(mocks.createConnection.mock.calls.map(([options]) => options)).toEqual([+ { port: 3000, host: "127.0.0.1" },+ { port: 8787, host: "127.0.0.1" },+ { port: 8789, host: "127.0.0.1" },+ { port: 8790, host: "127.0.0.1" },+ ]);+ expect(exit).not.toHaveBeenCalled();+ exit.mockRestore();+ });+ });});diff --git a/src/app/test/commands.test.ts b/src/app/test/commands.test.tsindex dc4c11be5..fe3e99acf 100644--- a/src/app/test/commands.test.ts+++ b/src/app/test/commands.test.ts@@ -82,7 +82,7 @@ describe("start command", () => {"--port-wake", "15213",], { from: "user" });- const ports = { web: 15210, emailWorker: 15211, wsDo: 15212, wakeWorker: 15213 };+ const ports = { web: 15210, emailWorker: 15211, wsDo: 15212, queueWorker: 15213 };expect(mocks.checkPorts).toHaveBeenCalledWith(ports);expect(mocks.startServices).toHaveBeenCalledWith(ports, { foreground: false });expect(mocks.waitForServer).toHaveBeenCalledWith("http://localhost:15210");diff --git a/src/app/test/install.test.ts b/src/app/test/install.test.tsindex 3fd0131ea..02c7636fc 100644--- a/src/app/test/install.test.ts+++ b/src/app/test/install.test.ts@@ -10,8 +10,8 @@ const bundledFixtureFiles = ["web/wrangler.toml","email-worker/index.js","ws-do/index.js",- "wake-worker/wrangler.toml",- "wake-worker/index.js",+ "queue-worker/wrangler.toml",+ "queue-worker/index.js",];function createFiles(rootDir: string, files: string[]): void {@@ -39,8 +39,8 @@ describe("install", () => {describe("normalizeInstallFilePath", () => {it("uses forward slashes for logical install paths", async () => {const { normalizeInstallFilePath } = await import("../src/lib/install.js");- expect(normalizeInstallFilePath("wake-worker\\wrangler.toml")).toBe(- "wake-worker/wrangler.toml",+ expect(normalizeInstallFilePath("queue-worker\\wrangler.toml")).toBe(+ "queue-worker/wrangler.toml",);});});@@ -57,8 +57,8 @@ describe("install", () => {expect(isInstalled(bundleDir, testDir)).toBe(true);});- it("returns false for a legacy installation without wake-worker", async () => {- createFiles(testDir, bundledFixtureFiles.filter((file) => !file.startsWith("wake-worker/")));+ it("returns false for an installation without queue-worker", async () => {+ createFiles(testDir, bundledFixtureFiles.filter((file) => !file.startsWith("queue-worker/")));const { isInstalled } = await import("../src/lib/install.js");expect(isInstalled(bundleDir, testDir)).toBe(false);});@@ -83,21 +83,21 @@ describe("install", () => {});it("treats a directory at a bundled file path as missing", async () => {- createFiles(testDir, bundledFixtureFiles.filter((file) => file !== "wake-worker/index.js"));- mkdirSync(join(testDir, "wake-worker/index.js"), { recursive: true });+ createFiles(testDir, bundledFixtureFiles.filter((file) => file !== "queue-worker/index.js"));+ mkdirSync(join(testDir, "queue-worker/index.js"), { recursive: true });const { getMissingInstallFiles } = await import("../src/lib/install.js");expect(getMissingInstallFiles(bundleDir, testDir)).toEqual([- "wake-worker/index.js",+ "queue-worker/index.js",]);});});describe("assertInstallationComplete", () => {it("names missing files in the error", async () => {- createFiles(testDir, bundledFixtureFiles.filter((file) => file !== "wake-worker/wrangler.toml"));+ createFiles(testDir, bundledFixtureFiles.filter((file) => file !== "queue-worker/wrangler.toml"));const { assertInstallationComplete } = await import("../src/lib/install.js");expect(() => assertInstallationComplete(bundleDir, testDir)).toThrow(- "Alook installation is incomplete after installing bundled assets. Missing required files: wake-worker/wrangler.toml. Reinstall @alook/app and try again.",+ "Alook installation is incomplete after installing bundled assets. Missing required files: queue-worker/wrangler.toml. Reinstall @alook/app and try again.",);});diff --git a/src/app/test/onboard.test.ts b/src/app/test/onboard.test.tsindex c86acae5c..0de4073bd 100644--- a/src/app/test/onboard.test.ts+++ b/src/app/test/onboard.test.ts@@ -6,7 +6,7 @@ const mocks = vi.hoisted(() => ({checkPorts: vi.fn(),createInterface: vi.fn(),ensureSecrets: vi.fn(),- getMissingInstallFiles: vi.fn(() => ["wake-worker/wrangler.toml"]),+ getMissingInstallFiles: vi.fn(() => ["queue-worker/wrangler.toml"]),installBundled: vi.fn(),isInstalled: vi.fn(() => false),isRunning: vi.fn(() => false),@@ -44,7 +44,7 @@ import { onboardCommand } from "../src/commands/onboard.js";beforeEach(() => {vi.clearAllMocks();delete process.env.ALOOK_PROJECT_ROOT;- mocks.getMissingInstallFiles.mockReturnValue(["wake-worker/wrangler.toml"]);+ mocks.getMissingInstallFiles.mockReturnValue(["queue-worker/wrangler.toml"]);mocks.isInstalled.mockReturnValue(false);mocks.isRunning.mockReturnValue(false);mocks.createInterface.mockReturnValue({diff --git a/src/app/test/secrets.test.ts b/src/app/test/secrets.test.tsindex 5eb5637a0..ae6d263cf 100644--- a/src/app/test/secrets.test.ts+++ b/src/app/test/secrets.test.ts@@ -8,7 +8,7 @@ const testDir = join(tmpdir(), `alook-test-secrets-${process.pid}`);vi.mock("../src/lib/constants.js", () => ({SELF_HOSTED_DIR: testDir,PID_FILE: join(testDir, ".pids.json"),- DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789, wakeWorker: 8790 },+ DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789, queueWorker: 8790 },WEB_URL: (port: number) => `http://localhost:${port}`,}));@@ -16,6 +16,7 @@ describe("secrets", () => {beforeEach(() => {mkdirSync(join(testDir, "web"), { recursive: true });mkdirSync(join(testDir, "email-worker"), { recursive: true });+ mkdirSync(join(testDir, "queue-worker"), { recursive: true });});afterEach(() => {@@ -31,18 +32,27 @@ describe("secrets", () => {const webVars = join(testDir, "web", ".dev.vars");const emailVars = join(testDir, "email-worker", ".dev.vars");+ const queueVars = join(testDir, "queue-worker", ".dev.vars");expect(existsSync(webVars)).toBe(true);expect(existsSync(emailVars)).toBe(true);+ expect(existsSync(queueVars)).toBe(true);const { readFileSync } = require("fs");const webContent = readFileSync(webVars, "utf-8");expect(webContent).toContain("BETTER_AUTH_SECRET=");expect(webContent).toContain("ENCRYPTION_KEY=");expect(webContent).toContain("BETTER_AUTH_URL=http://localhost:3000");+ const encryptionKey = webContent.match(/^ENCRYPTION_KEY=(.+)$/m)?.[1];+ expect(encryptionKey).toBeTruthy();+ expect(readFileSync(emailVars, "utf-8")).toContain(`ENCRYPTION_KEY=${encryptionKey}`);+ const queueContent = readFileSync(queueVars, "utf-8");+ expect(queueContent).toContain(`ENCRYPTION_KEY=${encryptionKey}`);+ expect(queueContent).toContain("APNS_TEAM_ID=");+ expect(queueContent).toContain("FCM_PRIVATE_KEY=");});- it("syncs encryption key from web to email-worker when email vars missing", async () => {+ it("syncs the web encryption key to both workers", async () => {// Pre-create web vars with a known keywriteFileSync(join(testDir, "web", ".dev.vars"),@@ -55,18 +65,48 @@ describe("secrets", () => {const { readFileSync } = require("fs");const emailContent = readFileSync(join(testDir, "email-worker", ".dev.vars"), "utf-8");+ const queueContent = readFileSync(join(testDir, "queue-worker", ".dev.vars"), "utf-8");expect(emailContent).toContain("ENCRYPTION_KEY=test-key-123");+ expect(queueContent).toContain("ENCRYPTION_KEY=test-key-123");});- it("skips when both secret files already exist", async () => {- writeFileSync(join(testDir, "web", ".dev.vars"), "existing", { mode: 0o600 });- writeFileSync(join(testDir, "email-worker", ".dev.vars"), "existing", { mode: 0o600 });+ it("adds a generated encryption key when existing web vars omit it", async () => {+ writeFileSync(+ join(testDir, "web", ".dev.vars"),+ "BETTER_AUTH_SECRET=abc\nBETTER_AUTH_URL=http://localhost:3000\n",+ { mode: 0o600 },+ );++ const { ensureSecrets } = await import("../src/lib/secrets.js");+ ensureSecrets(3000);- const consoleSpy = vi.spyOn(console, "log");+ const { readFileSync } = require("fs");+ const webContent = readFileSync(join(testDir, "web", ".dev.vars"), "utf-8");+ const encryptionKey = webContent.match(/^ENCRYPTION_KEY=(.+)$/m)?.[1];+ expect(encryptionKey).toBeTruthy();+ expect(readFileSync(join(testDir, "email-worker", ".dev.vars"), "utf-8"))+ .toContain(`ENCRYPTION_KEY=${encryptionKey}`);+ expect(readFileSync(join(testDir, "queue-worker", ".dev.vars"), "utf-8"))+ .toContain(`ENCRYPTION_KEY=${encryptionKey}`);+ });++ it("repairs drift while preserving provider credentials", async () => {+ writeFileSync(join(testDir, "web", ".dev.vars"), "ENCRYPTION_KEY=canonical\n", { mode: 0o600 });+ writeFileSync(join(testDir, "email-worker", ".dev.vars"), "ENCRYPTION_KEY=stale\n", { mode: 0o600 });+ writeFileSync(+ join(testDir, "queue-worker", ".dev.vars"),+ "ENCRYPTION_KEY=stale\nAPNS_TEAM_ID=team\n",+ { mode: 0o600 },+ );const { ensureSecrets } = await import("../src/lib/secrets.js");ensureSecrets(3000);- expect(consoleSpy).toHaveBeenCalledWith("Secrets already exist, skipping");- consoleSpy.mockRestore();+ const { readFileSync } = require("fs");+ expect(readFileSync(join(testDir, "email-worker", ".dev.vars"), "utf-8"))+ .toContain("ENCRYPTION_KEY=canonical");+ const queueContent = readFileSync(join(testDir, "queue-worker", ".dev.vars"), "utf-8");+ expect(queueContent).toContain("ENCRYPTION_KEY=canonical");+ expect(queueContent).toContain("APNS_TEAM_ID=team");+ expect(queueContent).toContain("FCM_PRIVATE_KEY=");});});diff --git a/src/app/test/services.test.ts b/src/app/test/services.test.tsindex 19958e0fd..2b1f18071 100644--- a/src/app/test/services.test.ts+++ b/src/app/test/services.test.ts@@ -4,15 +4,68 @@ import { join } from "path";import { tmpdir } from "os";const testDir = join(tmpdir(), `alook-test-services-${process.pid}`);+const childMocks = vi.hoisted(() => ({+ execSync: vi.fn(),+ spawn: vi.fn(),+ wranglerProcess: vi.fn((args: string[]) => ({ command: "wrangler", args })),+}));++vi.mock("child_process", () => ({+ execSync: childMocks.execSync,+ spawn: childMocks.spawn,+}));++vi.mock("../src/lib/wrangler.js", () => ({+ wranglerProcess: childMocks.wranglerProcess,+}));vi.mock("../src/lib/constants.js", () => ({SELF_HOSTED_DIR: testDir,PID_FILE: join(testDir, ".pids.json"),- DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789, wakeWorker: 8790 },+ DEFAULT_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789, queueWorker: 8790 },WEB_URL: (port: number) => `http://localhost:${port}`,}));describe("services", () => {+ const originalNodeEnv = process.env.NODE_ENV;+ const originalProjectRoot = process.env.ALOOK_PROJECT_ROOT;++ function fakeChild(pid?: number) {+ return {+ pid,+ stderr: { on: vi.fn() },+ stdout: { on: vi.fn() },+ unref: vi.fn(),+ };+ }++ function mockChildren(pids: Array<number | undefined> = [101, 102, 103, 104]) {+ const children = pids.map(fakeChild);+ childMocks.spawn.mockImplementation(() => children.shift()!);+ return children;+ }++ function expectTerminatedPids(pids: number[], platform: "linux" | "win32") {+ if (platform === "win32") {+ expect(process.kill).not.toHaveBeenCalled();+ expect(childMocks.execSync).toHaveBeenCalledTimes(pids.length);+ for (const [index, pid] of pids.entries()) {+ expect(childMocks.execSync).toHaveBeenNthCalledWith(+ index + 1,+ `taskkill /F /T /PID ${pid}`,+ { stdio: "ignore" },+ );+ }+ return;+ }++ expect(childMocks.execSync).not.toHaveBeenCalled();+ expect(process.kill).toHaveBeenCalledTimes(pids.length);+ for (const [index, pid] of pids.entries()) {+ expect(process.kill).toHaveBeenNthCalledWith(index + 1, -pid, "SIGTERM");+ }+ }+// Windows CI can spend >15s on the cold Vitest transform of services.ts// (pulls @alook/shared). Warm the graph once so per-test dynamic imports// hit the transform cache instead of timing out.@@ -24,12 +77,18 @@ describe("services", () => {beforeEach(() => {mkdirSync(testDir, { recursive: true });+ vi.clearAllMocks();});afterEach(() => {if (existsSync(testDir)) {rmSync(testDir, { recursive: true, force: true });}+ if (originalNodeEnv === undefined) delete process.env.NODE_ENV;+ else process.env.NODE_ENV = originalNodeEnv;+ if (originalProjectRoot === undefined) delete process.env.ALOOK_PROJECT_ROOT;+ else process.env.ALOOK_PROJECT_ROOT = originalProjectRoot;+ vi.restoreAllMocks();vi.resetModules();});@@ -86,9 +145,125 @@ describe("services", () => {const logs: string[] = [];const spy = vi.spyOn(console, "log").mockImplementation((m?: unknown) => { logs.push(String(m)); });- startServices({ web: 3000, emailWorker: 8787, wsDo: 8789 });+ startServices({ web: 3000, emailWorker: 8787, wsDo: 8789, queueWorker: 8790 });expect(logs.join("\n")).toContain("already running");spy.mockRestore();});++ it("spawns all four development services from the project tree", async () => {+ process.env.NODE_ENV = "development";+ process.env.ALOOK_PROJECT_ROOT = "/test/project";+ vi.resetModules();+ mockChildren();+ vi.spyOn(console, "log").mockImplementation(() => {});+ const { startServices } = await import("../src/lib/services.js");++ startServices({ web: 3000, emailWorker: 8787, wsDo: 8789, queueWorker: 8790 });++ expect(childMocks.spawn).toHaveBeenCalledTimes(4);+ expect(childMocks.spawn).toHaveBeenNthCalledWith(+ 4,+ "npx",+ expect.arrayContaining(["wrangler", "dev", "--port", "8790"]),+ expect.objectContaining({+ cwd: join("/test/project", "src", "queue-worker"),+ detached: true,+ env: expect.objectContaining({ NODE_ENV: "development" }),+ stdio: ["ignore", expect.any(Number), expect.any(Number)],+ }),+ );+ });++ it("spawns all four packaged services from generated Wrangler commands", async () => {+ process.env.NODE_ENV = "production";+ delete process.env.ALOOK_PROJECT_ROOT;+ vi.resetModules();+ mockChildren();+ vi.spyOn(console, "log").mockImplementation(() => {});+ const { startServices } = await import("../src/lib/services.js");++ startServices({ web: 3000, emailWorker: 8787, wsDo: 8789, queueWorker: 8790 });++ expect(childMocks.wranglerProcess).toHaveBeenCalledTimes(4);+ expect(childMocks.wranglerProcess).toHaveBeenLastCalledWith(+ expect.arrayContaining(["dev", "--port", "8790"]),+ );+ expect(childMocks.spawn).toHaveBeenNthCalledWith(+ 4,+ "wrangler",+ expect.arrayContaining(["dev", "--port", "8790"]),+ expect.objectContaining({+ cwd: join(testDir, "queue-worker"),+ detached: true,+ env: expect.objectContaining({ NODE_ENV: "development" }),+ stdio: ["ignore", expect.any(Number), expect.any(Number)],+ }),+ );+ });++ it.each(["linux", "win32"] as const)(+ "terminates already-started children when one service has no pid on %s",+ async (platform) => {+ vi.spyOn(process, "platform", "get").mockReturnValue(platform);+ process.env.NODE_ENV = "production";+ vi.resetModules();+ mockChildren([101, undefined, 103, 104]);+ vi.spyOn(process, "kill").mockImplementation(() => true);+ const exit = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {+ throw new Error(`exit:${code}`);+ }) as never);+ vi.spyOn(console, "log").mockImplementation(() => {});+ vi.spyOn(console, "error").mockImplementation(() => {});+ const { startServices } = await import("../src/lib/services.js");++ expect(() => startServices({+ web: 3000,+ emailWorker: 8787,+ wsDo: 8789,+ queueWorker: 8790,+ })).toThrow("exit:1");+ expect(childMocks.spawn).toHaveBeenCalledTimes(4);+ expectTerminatedPids([101, 103, 104], platform);+ expect(exit).toHaveBeenCalledOnce();+ expect(exit).toHaveBeenCalledWith(1);+ },+ );++ it.each(["linux", "win32"] as const)(+ "cleans up every foreground child on SIGINT exactly once on %s",+ async (platform) => {+ vi.spyOn(process, "platform", "get").mockReturnValue(platform);+ process.env.NODE_ENV = "development";+ process.env.ALOOK_PROJECT_ROOT = "/test/project";+ vi.resetModules();+ mockChildren();+ vi.spyOn(process, "kill").mockImplementation(() => true);+ const exit = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {+ throw new Error(`exit:${code}`);+ }) as never);+ const handlers = new Map<string, () => void>();+ vi.spyOn(process, "on").mockImplementation(((event: string, handler: () => void) => {+ handlers.set(event, handler);+ return process;+ }) as never);+ vi.spyOn(console, "log").mockImplementation(() => {});+ const { startServices } = await import("../src/lib/services.js");++ startServices(+ { web: 3000, emailWorker: 8787, wsDo: 8789, queueWorker: 8790 },+ { foreground: true },+ );+ const { PID_FILE } = await import("../src/lib/constants.js");+ expect(existsSync(PID_FILE)).toBe(true);+ expect(() => handlers.get("SIGINT")!()).toThrow("exit:0");+ expect(handlers.get("SIGINT")!()).toBeUndefined();++ expect(childMocks.spawn).toHaveBeenCalledTimes(4);+ expectTerminatedPids([101, 102, 103, 104], platform);+ expect(existsSync(PID_FILE)).toBe(false);+ expect(exit).toHaveBeenCalledTimes(1);+ expect(exit).toHaveBeenCalledWith(0);+ },+ );});});diff --git a/src/app/test/wrangler-config.test.ts b/src/app/test/wrangler-config.test.tsindex 0587b319a..156650699 100644--- a/src/app/test/wrangler-config.test.ts+++ b/src/app/test/wrangler-config.test.ts@@ -30,7 +30,7 @@ function setDevPort(content: string, port: number): string {describe("wrangler-config", () => {it("patches the self-hosted Web config to disable Blog discovery", async () => {const root = mkdtempSync(join(tmpdir(), "alook-app-wrangler-"));- for (const service of ["web", "email-worker", "ws-do", "wake-worker"]) {+ for (const service of ["web", "email-worker", "ws-do", "queue-worker"]) {mkdirSync(join(root, service), { recursive: true });writeFileSync(join(root, service, "wrangler.toml"), service === "web"? `name = "web"@@ -47,11 +47,12 @@ BLOG_DISCOVERY_REQUIRED = "true"vi.resetModules();vi.doMock("../src/lib/constants.js", () => ({ SELF_HOSTED_DIR: root }));const { patchWranglerConfigs } = await import("../src/lib/wrangler-config.js");- patchWranglerConfigs({ web: 3000, emailWorker: 8788, wsDo: 8789, wakeWorker: 8790 });+ patchWranglerConfigs({ web: 3000, emailWorker: 8788, wsDo: 8789, queueWorker: 8790 });const web = readFileSync(join(root, "web/wrangler.toml"), "utf8");expect(web).toContain('BLOG_DISCOVERY_REQUIRED = "false"');expect(web).not.toContain('binding = "BLOG_WORKER"');+ expect(web).toContain('DEV_QUEUE_WORKER_URL = "http://localhost:8790"');});describe("removeServiceBinding", () => {diff --git a/src/daemon/README.md b/src/daemon/README.mdindex e34bf4c01..2314645a0 100644--- a/src/daemon/README.md+++ b/src/daemon/README.md@@ -276,7 +276,7 @@ This project uses **pnpm** (see the `packageManager` field).pnpm installpnpm run typecheck # tsc --noEmit (passes clean)pnpm test # vitest — unit tests only (drivers/manager/inbox/credentials/server)-pnpm run test:integration # real infra: requires wrangler dev + ws-do dev + wake-worker dev (see below)+pnpm run test:integration # real infra: requires wrangler dev + ws-do dev + queue-worker dev (see below)```Unit behavior is covered by `src/**/*.test.ts`. Full control-plane and@@ -329,7 +329,7 @@ pnpm run daemon -- start --foreground --machine-key cmk_… \A bot bound to this machine (via the community UI/API) can now be woken byposting a message in a channel it's a member of — the real wake-producer path-(`src/web` → `src/wake-worker` → `src/ws-do`) delivers `agent:wake` over the+(`src/web` → `src/queue-worker` → `src/ws-do`) delivers `agent:wake` over thedaemon's real `WsControlChannel`.`pnpm --filter @alook/daemon build` emits a self-contained daemon bundle. Thediff --git a/src/daemon/src/runtimeConfig.ts b/src/daemon/src/runtimeConfig.tsindex 8c4c8b6ab..cef606c1a 100644--- a/src/daemon/src/runtimeConfig.ts+++ b/src/daemon/src/runtimeConfig.ts@@ -3,7 +3,7 @@** The canonical `RuntimeConfig`/`makeRuntimeConfig` now live in* `@alook/shared/runtime-config` (lifted there so the `src/web` wake producer- * and `src/wake-worker` consumer, neither of which can depend on this+ * and `src/queue-worker` consumer, neither of which can depend on this* CLI/daemon package, can construct the `config` field of an `agent:wake`* `HostCommand` — see `plans/community-agent-cli-bridge.md` §1 and* `plans/minimal-wake-queue-unread-notice.md`). Re-exported here so existingdiff --git a/src/daemon/src/server/wsControlServer.ts b/src/daemon/src/server/wsControlServer.tsindex 4197dbe26..65b255e15 100644--- a/src/daemon/src/server/wsControlServer.ts+++ b/src/daemon/src/server/wsControlServer.ts@@ -8,7 +8,7 @@* "running agents" set, and does NOT retry/redeliver anything — that* server-side control-plane state was retired (minimal-wake-queue-unread-notice* plan §6): the real production path is `src/web`'s wake producer →- * `src/wake-worker`'s queue consumer → `sendWakeToMachine`, and the DAEMON+ * `src/queue-worker`'s queue consumer → `sendWakeToMachine`, and the DAEMON* (not this fixture) decides spawn-vs-notify-vs-coalesce for `agent:wake`.* This class exists purely so daemon-side control-plane/e2e tests can drive* `agent:wake`/`agent:stop` over a REAL WebSocket instead of an in-process@@ -84,7 +84,7 @@ export interface WsControlServerOpts {* Ws-transport shim for exactly one connected host at a time (the dev/test* case); a later host replaces the active socket. Commands are pushed* explicitly via `pushCommand` — there is no automatic dispatch, because- * deciding WHEN to wake an agent is now `src/web`/`src/wake-worker`'s job in+ * deciding WHEN to wake an agent is now `src/web`/`src/queue-worker`'s job in* production, not this fixture's.*/export class WsControlServer {diff --git a/src/desktop/src-tauri/Cargo.lock b/src/desktop/src-tauri/Cargo.lockindex f6e2aed6e..dc498d64c 100644--- a/src/desktop/src-tauri/Cargo.lock+++ b/src/desktop/src-tauri/Cargo.lock@@ -37,11 +37,14 @@ name = "alook-desktop"version = "0.1.36"dependencies = ["base64 0.22.1",+ "block2","command-group","getrandom 0.3.4",+ "notify-rust","objc2","objc2-app-kit","objc2-foundation",+ "objc2-user-notifications","objc2-web-kit","png 0.18.1","serde",@@ -53,6 +56,7 @@ dependencies = ["tauri-plugin-clipboard-manager","tauri-plugin-deep-link","tauri-plugin-dialog",+ "tauri-plugin-mobile-push","tauri-plugin-mobile-share-image","tauri-plugin-notification","tauri-plugin-opener",@@ -2625,6 +2629,8 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"dependencies = [+ "bitflags 2.12.1",+ "block2","objc2","objc2-foundation",]@@ -4169,6 +4175,16 @@ dependencies = ["url",]+[[package]]+name = "tauri-plugin-mobile-push"+version = "0.1.0"+dependencies = [+ "serde",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.18",+]+[[package]]name = "tauri-plugin-mobile-share-image"version = "0.1.0"diff --git a/src/desktop/src-tauri/Cargo.toml b/src/desktop/src-tauri/Cargo.tomlindex 3dff632dd..0ebe9a20f 100644--- a/src/desktop/src-tauri/Cargo.toml+++ b/src/desktop/src-tauri/Cargo.toml@@ -28,6 +28,7 @@ url = "2"[target."cfg(any(target_os = \"android\", target_os = \"ios\"))".dependencies]tauri-plugin-mobile-share-image = { path = "plugins/mobile-share-image" }+tauri-plugin-mobile-push = { path = "plugins/mobile-push" }[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dependencies]tauri-plugin-notification = "2"@@ -43,14 +44,17 @@ objc2 = "=0.6.4"objc2-foundation = { version = "=0.3.2", features = ["NSDictionary", "NSError", "NSGeometry", "NSObject", "NSString", "NSURL", "NSURLError", "NSURLRequest"] }[target."cfg(target_os = \"macos\")".dependencies]+block2 = "=0.6.2"objc2-app-kit = { version = "=0.3.2", features = ["NSView", "NSWindow", "NSColor"] }+objc2-user-notifications = { version = "=0.3.2", default-features = false, features = ["std", "UNNotification", "UNNotificationContent", "UNNotificationRequest", "UNNotificationResponse", "UNNotificationSound", "UNNotificationTrigger", "UNUserNotificationCenter", "block2"] }objc2-web-kit = { version = "=0.3.2", features = ["WKWebView"], default-features = false }[target."cfg(windows)".dependencies]webview2-com = "=0.38.2"-windows = "=0.61.3"+windows = { version = "=0.61.3", features = ["Data_Xml_Dom", "UI_Notifications"] }[target."cfg(target_os = \"linux\")".dependencies]+notify-rust = "=4.17.0"webkit2gtk = { version = "=2.0.2", features = ["v2_6"] }[features]diff --git a/src/desktop/src-tauri/build.rs b/src/desktop/src-tauri/build.rsindex 7fa4393ea..926e13af0 100644--- a/src/desktop/src-tauri/build.rs+++ b/src/desktop/src-tauri/build.rs@@ -6,8 +6,19 @@ fn main() {"set_window_theme","close_splashscreen","desktop_zoom_shortcut",+ "desktop_system_notification_show",+ "desktop_system_notification_listen",+ "desktop_system_notification_take_activation",+ "desktop_system_notification_unlisten","mobile_share_image_copy","mobile_share_image_save",+ "mobile_system_notification_check_permission",+ "mobile_system_notification_request_permission",+ "mobile_system_notification_snapshot",+ "mobile_system_notification_acknowledge_registration",+ "mobile_system_notification_take_activation",+ "mobile_system_notification_listen",+ "mobile_system_notification_unlisten","native_oauth_snapshot","native_oauth_listen","native_oauth_unlisten",diff --git a/src/desktop/src-tauri/capabilities/mobile-system-notification-mobile.json b/src/desktop/src-tauri/capabilities/mobile-system-notification-mobile.jsonnew file mode 100644index 000000000..a7703a59f--- /dev/null+++ b/src/desktop/src-tauri/capabilities/mobile-system-notification-mobile.json@@ -0,0 +1,21 @@+{+ "$schema": "../gen/schemas/mobile-schema.json",+ "identifier": "mobile-system-notification-mobile",+ "description": "Native mobile system notification registration and activation for the trusted main WebView",+ "windows": [+ "main"+ ],+ "platforms": [+ "android",+ "iOS"+ ],+ "local": false,+ "remote": {+ "urls": [+ "https://alook.ai"+ ]+ },+ "permissions": [+ "mobile-system-notification"+ ]+}diff --git a/src/desktop/src-tauri/gen/android/app/build.gradle.kts b/src/desktop/src-tauri/gen/android/app/build.gradle.ktsindex 537459791..54a513250 100644--- a/src/desktop/src-tauri/gen/android/app/build.gradle.kts+++ b/src/desktop/src-tauri/gen/android/app/build.gradle.kts@@ -90,3 +90,7 @@ dependencies {}apply(from = "tauri.build.gradle.kts")++if (file("google-services.json").exists()) {+ apply(plugin = "com.google.gms.google-services")+}diff --git a/src/desktop/src-tauri/gen/android/build.gradle.kts b/src/desktop/src-tauri/gen/android/build.gradle.ktsindex 607240bc8..353f711f3 100644--- a/src/desktop/src-tauri/gen/android/build.gradle.kts+++ b/src/desktop/src-tauri/gen/android/build.gradle.kts@@ -6,6 +6,7 @@ buildscript {dependencies {classpath("com.android.tools.build:gradle:8.11.0")classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.25")+ classpath("com.google.gms:google-services:4.5.0")}}@@ -19,4 +20,3 @@ allprojects {tasks.register("clean").configure {delete("build")}-diff --git a/src/desktop/src-tauri/gen/apple/alook-desktop_iOS/alook-desktop_iOS.entitlements b/src/desktop/src-tauri/gen/apple/alook-desktop_iOS/alook-desktop_iOS.entitlementsindex e8f0e028c..c2880bab1 100644--- a/src/desktop/src-tauri/gen/apple/alook-desktop_iOS/alook-desktop_iOS.entitlements+++ b/src/desktop/src-tauri/gen/apple/alook-desktop_iOS/alook-desktop_iOS.entitlements@@ -6,5 +6,7 @@<array><string>applinks:auth.alook.ai</string></array>+ <key>aps-environment</key>+ <string>$(APS_ENVIRONMENT)</string></dict></plist>diff --git a/src/desktop/src-tauri/gen/apple/project.yml b/src/desktop/src-tauri/gen/apple/project.ymlindex 72972fe43..61152c870 100644--- a/src/desktop/src-tauri/gen/apple/project.yml+++ b/src/desktop/src-tauri/gen/apple/project.yml@@ -62,6 +62,7 @@ targets:properties:com.apple.developer.associated-domains:- applinks:auth.alook.ai+ aps-environment: $(APS_ENVIRONMENT)scheme:environmentVariables:RUST_BACKTRACE: full@@ -76,7 +77,10 @@ targets:ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES: trueEXCLUDED_ARCHS[sdk=iphoneos*]: x86_64configs:+ debug:+ APS_ENVIRONMENT: developmentrelease:+ APS_ENVIRONMENT: productionCODE_SIGN_STYLE: ManualCODE_SIGN_IDENTITY: Apple DistributionDEVELOPMENT_TEAM: 5RF24VHDQBdiff --git a/src/desktop/src-tauri/permissions/desktop-commands.toml b/src/desktop/src-tauri/permissions/desktop-commands.tomlindex 70ba98e88..a76bb5270 100644--- a/src/desktop/src-tauri/permissions/desktop-commands.toml+++ b/src/desktop/src-tauri/permissions/desktop-commands.toml@@ -1,4 +1,4 @@[[permission]]identifier = "desktop-commands"description = "Existing main-window desktop commands"-commands.allow = ["daemon_runtime_capability", "daemon_pair", "set_window_theme", "close_splashscreen", "desktop_zoom_shortcut"]+commands.allow = ["daemon_runtime_capability", "daemon_pair", "set_window_theme", "close_splashscreen", "desktop_zoom_shortcut", "desktop_system_notification_show", "desktop_system_notification_listen", "desktop_system_notification_take_activation", "desktop_system_notification_unlisten"]diff --git a/src/desktop/src-tauri/permissions/mobile-system-notification.toml b/src/desktop/src-tauri/permissions/mobile-system-notification.tomlnew file mode 100644index 000000000..4d014b411--- /dev/null+++ b/src/desktop/src-tauri/permissions/mobile-system-notification.toml@@ -0,0 +1,4 @@+[[permission]]+identifier = "mobile-system-notification"+description = "Native mobile push registration and activation orchestration for the trusted main WebView"+commands.allow = ["mobile_system_notification_check_permission", "mobile_system_notification_request_permission", "mobile_system_notification_snapshot", "mobile_system_notification_acknowledge_registration", "mobile_system_notification_take_activation", "mobile_system_notification_listen", "mobile_system_notification_unlisten"]diff --git a/src/desktop/src-tauri/plugins/mobile-push/.gitignore b/src/desktop/src-tauri/plugins/mobile-push/.gitignorenew file mode 100644index 000000000..3a4319185--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/.gitignore@@ -0,0 +1,6 @@+/\.tauri+/android/.tauri+/android/build+/ios/.build+/ios/.swiftpm+/ios/Package.resolveddiff --git a/src/desktop/src-tauri/plugins/mobile-push/Cargo.toml b/src/desktop/src-tauri/plugins/mobile-push/Cargo.tomlnew file mode 100644index 000000000..6a48d9c5b--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "tauri-plugin-mobile-push"+version = "0.1.0"+edition = "2021"+links = "tauri-plugin-mobile-push"++[build-dependencies]+tauri-plugin = { version = "2", features = ["build"] }++[dependencies]+serde = { version = "1", features = ["derive"] }+tauri = { version = "=2.11.2", default-features = false }+thiserror = "2"++[target.'cfg(target_os = "ios")'.dependencies]+tauri = { version = "=2.11.2", features = ["wry"], default-features = false }diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/build.gradle.kts b/src/desktop/src-tauri/plugins/mobile-push/android/build.gradle.ktsnew file mode 100644index 000000000..8259466c6--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/build.gradle.kts@@ -0,0 +1,31 @@+plugins {+ id("com.android.library")+ id("org.jetbrains.kotlin.android")+}++android {+ namespace = "ai.alook.plugin.mobilepush"+ compileSdk = 36++ defaultConfig {+ minSdk = 24+ consumerProguardFiles("proguard-rules.pro")+ }++ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_1_8+ targetCompatibility = JavaVersion.VERSION_1_8+ }+ kotlinOptions {+ jvmTarget = "1.8"+ }+}++dependencies {+ implementation("androidx.core:core-ktx:1.17.0")+ implementation(platform("com.google.firebase:firebase-bom:34.19.0"))+ implementation("com.google.firebase:firebase-messaging")+ implementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")+ implementation(project(":tauri-android"))+ testImplementation("junit:junit:4.13.2")+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/proguard-rules.pro b/src/desktop/src-tauri/plugins/mobile-push/android/proguard-rules.pronew file mode 100644index 000000000..c47679a5d--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/proguard-rules.pro@@ -0,0 +1 @@+-keep class ai.alook.plugin.mobilepush.AlookFirebaseMessagingService { *; }diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/settings.gradle b/src/desktop/src-tauri/plugins/mobile-push/android/settings.gradlenew file mode 100644index 000000000..210e65bab--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/settings.gradle@@ -0,0 +1 @@+rootProject.name = 'mobile-push'diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/AndroidManifest.xml b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/AndroidManifest.xmlnew file mode 100644index 000000000..4a8306dfa--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/AndroidManifest.xml@@ -0,0 +1,21 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />++ <application>+ <service+ android:name="ai.alook.plugin.mobilepush.AlookFirebaseMessagingService"+ android:exported="false">+ <intent-filter>+ <action android:name="com.google.firebase.MESSAGING_EVENT" />+ </intent-filter>+ </service>++ <meta-data+ android:name="com.google.firebase.messaging.default_notification_channel_id"+ android:value="alook_messages" />+ <meta-data+ android:name="com.google.firebase.messaging.default_notification_icon"+ android:resource="@drawable/ic_alook_notification" />+ </application>+</manifest>diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/AlookFirebaseMessagingService.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/AlookFirebaseMessagingService.ktnew file mode 100644index 000000000..5960a678e--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/AlookFirebaseMessagingService.kt@@ -0,0 +1,55 @@+package ai.alook.plugin.mobilepush++import android.app.PendingIntent+import android.content.Intent+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import com.google.firebase.messaging.FirebaseMessagingService+import com.google.firebase.messaging.RemoteMessage++class AlookFirebaseMessagingService : FirebaseMessagingService() {+ override fun onNewToken(token: String) {+ super.onNewToken(token)+ if (runCatching { MobilePushStore(applicationContext).updateCurrentToken(token) }.getOrDefault(false)) {+ MobilePushPlugin.signalCurrent()+ }+ }++ override fun onMessageReceived(message: RemoteMessage) {+ super.onMessageReceived(message)+ val route = MobilePushRoute.fromMap(message.data) ?: return+ val content = message.notification ?: return+ if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) return++ MobilePushPlugin.createNotificationChannel(applicationContext)+ val launchIntent = packageManager.getLaunchIntentForPackage(packageName) ?: return+ launchIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP+ launchIntent.putExtra("notificationId", route.notificationId)+ launchIntent.putExtra("messageId", route.messageId)+ launchIntent.putExtra("targetId", route.targetId)+ val requestCode = route.notificationId.hashCode() and Int.MAX_VALUE+ val pendingIntent = PendingIntent.getActivity(+ this,+ requestCode,+ launchIntent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ val notification = NotificationCompat.Builder(this, CHANNEL_ID)+ .setSmallIcon(ai.alook.plugin.mobilepush.R.drawable.ic_alook_notification)+ .setContentTitle(content.title ?: "Alook")+ .setContentText(content.body ?: "New message")+ .setAutoCancel(true)+ .setContentIntent(pendingIntent)+ .setGroup(route.targetId)+ .build()+ NotificationManagerCompat.from(this).notify(+ route.notificationId,+ requestCode,+ notification,+ )+ }++ companion object {+ const val CHANNEL_ID = "alook_messages"+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.ktnew file mode 100644index 000000000..be9cdebba--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushPlugin.kt@@ -0,0 +1,253 @@+package ai.alook.plugin.mobilepush++import android.Manifest+import android.app.Activity+import android.app.NotificationChannel+import android.app.NotificationManager+import android.content.Intent+import android.os.Build+import android.webkit.WebView+import androidx.core.app.NotificationManagerCompat+import app.tauri.PermissionState+import app.tauri.annotation.Command+import app.tauri.annotation.InvokeArg+import app.tauri.annotation.Permission+import app.tauri.annotation.PermissionCallback+import app.tauri.annotation.TauriPlugin+import app.tauri.plugin.Channel+import app.tauri.plugin.Invoke+import app.tauri.plugin.JSObject+import app.tauri.plugin.Plugin+import com.google.firebase.messaging.FirebaseMessaging+import java.lang.ref.WeakReference++@InvokeArg+class AcknowledgeRegistrationArgs {+ lateinit var providerToken: String+}++@InvokeArg+class MobilePushListenArgs {+ lateinit var channel: Channel+}++@InvokeArg+class MobilePushUnlistenArgs {+ var registrationId: Long = 0+}++internal fun mobilePushPermissionState(+ notificationsEnabled: Boolean,+ declaredState: String?,+): String = when {+ notificationsEnabled -> "granted"+ declaredState == PermissionState.PROMPT.toString() -> "prompt"+ else -> "denied"+}++@TauriPlugin(+ permissions = [+ Permission(strings = [Manifest.permission.POST_NOTIFICATIONS], alias = "permissionState"),+ ],+)+class MobilePushPlugin(private val activity: Activity) : Plugin(activity) {+ private val store = MobilePushStore(activity.applicationContext)+ private var listener: Channel? = null++ override fun load(webView: WebView) {+ super.load(webView)+ instance = WeakReference(this)+ createNotificationChannel(activity)+ intake(activity.intent)+ refreshToken()+ }++ override fun onResume() {+ super.onResume()+ intake(activity.intent)+ refreshToken()+ signal()+ }++ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ activity.intent = intent+ intake(intent)+ }++ @Command+ override fun checkPermissions(invoke: Invoke) {+ resolvePermission(invoke)+ }++ @Command+ override fun requestPermissions(invoke: Invoke) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU+ || permissionState() != PermissionState.PROMPT.toString()+ ) {+ resolvePermission(invoke)+ } else {+ requestPermissionForAlias("permissionState", invoke, "permissionCallback")+ }+ }++ @PermissionCallback+ private fun permissionCallback(invoke: Invoke) {+ resolvePermission(invoke)+ }++ @Command+ fun snapshot(invoke: Invoke) {+ refreshToken()+ try {+ val registration = store.registration()+ val response = JSObject()+ response.put("installationId", store.installationId())+ response.put("platform", "android")+ response.put("providerEnvironment", "production")+ response.put("providerToken", registration.currentToken)+ response.put("previousProviderToken", registration.previousToken())+ response.put("appVersion", appVersion())+ invoke.resolve(response)+ } catch (_: Exception) {+ invoke.reject("Native push storage is unavailable", "store_unavailable")+ }+ }++ @Command+ fun acknowledgeRegistration(invoke: Invoke) {+ val args = try {+ invoke.parseArgs(AcknowledgeRegistrationArgs::class.java)+ } catch (_: Exception) {+ invoke.reject("Registration acknowledgement is invalid", "invalid_request")+ return+ }+ try {+ if (!store.acknowledge(args.providerToken)) {+ invoke.reject("Registration token changed", "stale_token")+ return+ }+ invoke.resolve()+ } catch (_: Exception) {+ invoke.reject("Native push storage is unavailable", "store_unavailable")+ }+ }++ @Command+ fun takeActivation(invoke: Invoke) {+ try {+ val route = store.takeActivation()+ if (route == null) {+ invoke.resolve()+ return+ }+ val response = JSObject()+ response.put("notificationId", route.notificationId)+ response.put("messageId", route.messageId)+ response.put("targetId", route.targetId)+ invoke.resolve(response)+ } catch (_: Exception) {+ invoke.reject("Native push storage is unavailable", "store_unavailable")+ }+ }++ @Command+ fun listen(invoke: Invoke) {+ val args = try {+ invoke.parseArgs(MobilePushListenArgs::class.java)+ } catch (_: Exception) {+ invoke.reject("Notification listener is invalid", "invalid_request")+ return+ }+ listener = args.channel+ invoke.resolveObject(args.channel.id)+ }++ @Command+ fun unlisten(invoke: Invoke) {+ val args = try {+ invoke.parseArgs(MobilePushUnlistenArgs::class.java)+ } catch (_: Exception) {+ invoke.reject("Notification listener is invalid", "invalid_request")+ return+ }+ if (listener?.id == args.registrationId) listener = null+ invoke.resolve()+ }++ private fun resolvePermission(invoke: Invoke) {+ val response = JSObject()+ response.put("permissionState", permissionState())+ invoke.resolve(response)+ }++ private fun permissionState(): String = mobilePushPermissionState(+ NotificationManagerCompat.from(activity).areNotificationsEnabled(),+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ getPermissionState("permissionState")?.toString()+ } else {+ null+ },+ )++ private fun refreshToken() {+ try {+ FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->+ if (runCatching { store.updateCurrentToken(token) }.getOrDefault(false)) signal()+ }+ } catch (_: Exception) {+ return+ }+ }++ private fun intake(intent: Intent?) {+ val route = intent?.let {+ MobilePushRoute.create(+ it.getStringExtra("notificationId"),+ it.getStringExtra("messageId"),+ it.getStringExtra("targetId"),+ )+ } ?: return+ try {+ store.saveActivation(route)+ intent.removeExtra("notificationId")+ intent.removeExtra("messageId")+ intent.removeExtra("targetId")+ signal()+ } catch (_: Exception) {+ return+ }+ }++ private fun signal() {+ runCatching { listener?.send(JSObject()) }+ }++ private fun appVersion(): String? = runCatching {+ activity.packageManager.getPackageInfo(activity.packageName, 0).versionName+ }.getOrNull()++ companion object {+ private var instance: WeakReference<MobilePushPlugin>? = null++ fun signalCurrent() {+ instance?.get()?.signal()+ }++ fun createNotificationChannel(activity: Activity) {+ createNotificationChannel(activity.applicationContext)+ }++ fun createNotificationChannel(context: android.content.Context) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return+ val manager = context.getSystemService(NotificationManager::class.java) ?: return+ manager.createNotificationChannel(+ NotificationChannel(+ AlookFirebaseMessagingService.CHANNEL_ID,+ "Messages",+ NotificationManager.IMPORTANCE_DEFAULT,+ ),+ )+ }+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushRoute.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushRoute.ktnew file mode 100644index 000000000..2efa26136--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushRoute.kt@@ -0,0 +1,31 @@+package ai.alook.plugin.mobilepush++import java.util.UUID++data class MobilePushRoute(+ val notificationId: String,+ val messageId: String,+ val targetId: String,+) {+ companion object {+ private val safeId = Regex("^[A-Za-z0-9_-]{1,128}$")++ fun create(notificationId: String?, messageId: String?, targetId: String?): MobilePushRoute? {+ if (notificationId == null || messageId == null || targetId == null) return null+ val canonicalNotificationId = try {+ UUID.fromString(notificationId).toString()+ } catch (_: IllegalArgumentException) {+ return null+ }+ if (canonicalNotificationId != notificationId.lowercase()) return null+ if (!safeId.matches(messageId) || !safeId.matches(targetId)) return null+ return MobilePushRoute(canonicalNotificationId, messageId, targetId)+ }++ fun fromMap(values: Map<String, String>): MobilePushRoute? = create(+ values["notificationId"],+ values["messageId"],+ values["targetId"],+ )+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushStore.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushStore.ktnew file mode 100644index 000000000..1c76bd26b--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/java/ai/alook/plugin/mobilepush/MobilePushStore.kt@@ -0,0 +1,98 @@+package ai.alook.plugin.mobilepush++import android.content.Context+import android.content.SharedPreferences+import java.util.UUID++data class MobilePushRegistrationState(+ val currentToken: String? = null,+ val acknowledgedToken: String? = null,+) {+ fun withCurrentToken(token: String): MobilePushRegistrationState =+ if (token == currentToken) this else copy(currentToken = token)++ fun acknowledge(token: String): MobilePushRegistrationState =+ copy(acknowledgedToken = token)++ fun previousToken(): String? = acknowledgedToken?.takeIf { it != currentToken }+}++class MobilePushStore(context: Context) {+ private val preferences: SharedPreferences = context.getSharedPreferences(+ "alook.mobilePush",+ Context.MODE_PRIVATE,+ )+ private val lock = Any()++ fun installationId(): String = synchronized(lock) {+ preferences.getString(INSTALLATION_ID, null)?.let { return@synchronized it }+ val created = UUID.randomUUID().toString()+ check(preferences.edit().putString(INSTALLATION_ID, created).commit())+ created+ }++ fun registration(): MobilePushRegistrationState = synchronized(lock) {+ MobilePushRegistrationState(+ currentToken = preferences.getString(CURRENT_TOKEN, null),+ acknowledgedToken = preferences.getString(ACKNOWLEDGED_TOKEN, null),+ )+ }++ fun updateCurrentToken(token: String): Boolean = synchronized(lock) {+ require(token.length in 16..4096 && token.none { it.isISOControl() })+ val current = registration()+ val next = current.withCurrentToken(token)+ if (next == current) return@synchronized false+ check(preferences.edit().putString(CURRENT_TOKEN, next.currentToken).commit())+ true+ }++ fun acknowledge(token: String): Boolean = synchronized(lock) {+ require(token.length in 16..4096 && token.none { it.isISOControl() })+ val current = registration()+ val next = current.acknowledge(token)+ if (next == current) return@synchronized true+ check(preferences.edit().putString(ACKNOWLEDGED_TOKEN, next.acknowledgedToken).commit())+ true+ }++ fun saveActivation(route: MobilePushRoute) = synchronized(lock) {+ check(+ preferences.edit()+ .putString(PENDING_NOTIFICATION_ID, route.notificationId)+ .putString(PENDING_MESSAGE_ID, route.messageId)+ .putString(PENDING_TARGET_ID, route.targetId)+ .commit(),+ )+ }++ fun takeActivation(): MobilePushRoute? = synchronized(lock) {+ val route = MobilePushRoute.create(+ preferences.getString(PENDING_NOTIFICATION_ID, null),+ preferences.getString(PENDING_MESSAGE_ID, null),+ preferences.getString(PENDING_TARGET_ID, null),+ )+ if (preferences.contains(PENDING_NOTIFICATION_ID)+ || preferences.contains(PENDING_MESSAGE_ID)+ || preferences.contains(PENDING_TARGET_ID)+ ) {+ check(+ preferences.edit()+ .remove(PENDING_NOTIFICATION_ID)+ .remove(PENDING_MESSAGE_ID)+ .remove(PENDING_TARGET_ID)+ .commit(),+ )+ }+ route+ }++ companion object {+ private const val INSTALLATION_ID = "installationId"+ private const val CURRENT_TOKEN = "currentToken"+ private const val ACKNOWLEDGED_TOKEN = "acknowledgedToken"+ private const val PENDING_NOTIFICATION_ID = "pendingNotificationId"+ private const val PENDING_MESSAGE_ID = "pendingMessageId"+ private const val PENDING_TARGET_ID = "pendingTargetId"+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/main/res/drawable/ic_alook_notification.xml b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/res/drawable/ic_alook_notification.xmlnew file mode 100644index 000000000..8860239ab--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/main/res/drawable/ic_alook_notification.xml@@ -0,0 +1,9 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M12,2C8.69,2 6,4.69 6,8v3.59L4.29,13.3A1,1 0,0 0,5 15h14a1,1 0,0 0,0.71 -1.7L18,11.59V8c0,-3.31 -2.69,-6 -6,-6zM9.5,17a2.5,2.5 0,0 0,5 0h-5z" />+</vector>diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushRouteTest.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushRouteTest.ktnew file mode 100644index 000000000..0b0f18d3c--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushRouteTest.kt@@ -0,0 +1,41 @@+package ai.alook.plugin.mobilepush++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Test++class MobilePushRouteTest {+ @Test+ fun acceptsOnlyCanonicalAllowlistedRouteValues() {+ val route = MobilePushRoute.create(+ "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "message_1",+ "channel-2",+ )+ assertEquals("message_1", route?.messageId)+ assertNull(MobilePushRoute.create("bad", "message_1", "channel-2"))+ assertNull(MobilePushRoute.create(+ "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "../message",+ "channel-2",+ ))+ }++ @Test+ fun ignoresTransportExtrasButStoresOnlyTheThreeRouteFields() {+ val route = MobilePushRoute.fromMap(mapOf(+ "notificationId" to "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId" to "message_1",+ "targetId" to "channel_2",+ "from" to "transport",+ ))+ assertEquals(+ MobilePushRoute(+ "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "message_1",+ "channel_2",+ ),+ route,+ )+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushStoreCoreTest.kt b/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushStoreCoreTest.ktnew file mode 100644index 000000000..bfbebdd69--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/android/src/test/java/ai/alook/plugin/mobilepush/MobilePushStoreCoreTest.kt@@ -0,0 +1,38 @@+package ai.alook.plugin.mobilepush++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Test++class MobilePushStoreCoreTest {+ @Test+ fun permissionStateHasOnlyTheThreeWebContractValues() {+ assertEquals("granted", mobilePushPermissionState(true, "prompt"))+ assertEquals("prompt", mobilePushPermissionState(false, "prompt"))+ assertEquals("denied", mobilePushPermissionState(false, "prompt-with-rationale"))+ assertEquals("denied", mobilePushPermissionState(false, "denied"))+ assertEquals("denied", mobilePushPermissionState(false, null))+ }++ @Test+ fun successfulPostedTokenBecomesProofAcrossAConcurrentRotation() {+ val t0 = "token-00000000000"+ val t1 = "token-11111111111"+ val t2 = "token-22222222222"++ val initial = MobilePushRegistrationState(currentToken = t0).acknowledge(t0)+ assertNull(initial.previousToken())++ val failedT1 = initial.withCurrentToken(t1)+ assertEquals(t0, failedT1.previousToken())++ val failedT2 = failedT1.withCurrentToken(t2)+ assertEquals(t0, failedT2.previousToken())+ val acknowledgedT1 = failedT2.acknowledge(t1)+ assertEquals(t1, acknowledgedT1.previousToken())++ val acknowledgedT2 = acknowledgedT1.acknowledge(t2)+ assertNull(acknowledgedT2.previousToken())+ assertEquals(t2, acknowledgedT2.acknowledgedToken)+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/build.rs b/src/desktop/src-tauri/plugins/mobile-push/build.rsnew file mode 100644index 000000000..dd3724d8a--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/build.rs@@ -0,0 +1,13 @@+fn main() {+ tauri_plugin::Builder::new(&[+ "snapshot",+ "acknowledgeRegistration",+ "takeActivation",+ "listen",+ "unlisten",+ ])+ .android_path("android")+ .ios_path("ios")+ .try_build()+ .expect("failed to build mobile push plugin");+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/ios/Package.swift b/src/desktop/src-tauri/plugins/mobile-push/ios/Package.swiftnew file mode 100644index 000000000..c9be77b5f--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/ios/Package.swift@@ -0,0 +1,31 @@+// swift-tools-version:5.3++import PackageDescription++let package = Package(+ name: "tauri-plugin-mobile-push",+ platforms: [.iOS(.v14)],+ products: [+ .library(+ name: "tauri-plugin-mobile-push",+ type: .static,+ targets: ["tauri-plugin-mobile-push"])+ ],+ dependencies: [+ .package(name: "Tauri", path: "../.tauri/tauri-api")+ ],+ targets: [+ .target(+ name: "tauri-plugin-mobile-push",+ dependencies: [.byName(name: "Tauri")],+ path: "Sources",+ linkerSettings: [+ .linkedFramework("UIKit"),+ .linkedFramework("UserNotifications"),+ ]),+ .testTarget(+ name: "MobilePushPluginTests",+ dependencies: [.byName(name: "tauri-plugin-mobile-push")],+ path: "Tests/MobilePushPluginTests")+ ]+)diff --git a/src/desktop/src-tauri/plugins/mobile-push/ios/Sources/MobilePushPlugin.swift b/src/desktop/src-tauri/plugins/mobile-push/ios/Sources/MobilePushPlugin.swiftnew file mode 100644index 000000000..d03ca6436--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/ios/Sources/MobilePushPlugin.swift@@ -0,0 +1,445 @@+import Foundation+import ObjectiveC+import Tauri+import UIKit+import UserNotifications+import WebKit++struct MobilePushRoute: Codable, Equatable {+ let notificationId: String+ let messageId: String+ let targetId: String++ private static let safeId = try! NSRegularExpression(+ pattern: "^[A-Za-z0-9_-]{1,128}$"+ )++ static func create(+ notificationId: String?,+ messageId: String?,+ targetId: String?+ ) -> MobilePushRoute? {+ guard let notificationId = notificationId,+ let messageId = messageId,+ let targetId = targetId,+ let uuid = UUID(uuidString: notificationId),+ uuid.uuidString.lowercased() == notificationId.lowercased(),+ matchesSafeId(messageId),+ matchesSafeId(targetId)+ else { return nil }+ return MobilePushRoute(+ notificationId: uuid.uuidString.lowercased(),+ messageId: messageId,+ targetId: targetId+ )+ }++ static func from(_ values: [AnyHashable: Any]) -> MobilePushRoute? {+ create(+ notificationId: values["notificationId"] as? String,+ messageId: values["messageId"] as? String,+ targetId: values["targetId"] as? String+ )+ }++ private static func matchesSafeId(_ value: String) -> Bool {+ let range = NSRange(value.startIndex..<value.endIndex, in: value)+ return safeId.firstMatch(in: value, range: range)?.range == range+ }+}++struct MobilePushRegistrationState: Equatable {+ let currentToken: String?+ let acknowledgedToken: String?++ init(currentToken: String? = nil, acknowledgedToken: String? = nil) {+ self.currentToken = currentToken+ self.acknowledgedToken = acknowledgedToken+ }++ func withCurrentToken(_ token: String) -> MobilePushRegistrationState {+ token == currentToken ? self : .init(+ currentToken: token,+ acknowledgedToken: acknowledgedToken+ )+ }++ func acknowledging(_ token: String) -> MobilePushRegistrationState {+ .init(+ currentToken: currentToken,+ acknowledgedToken: token+ )+ }++ var previousToken: String? {+ acknowledgedToken == currentToken ? nil : acknowledgedToken+ }+}++final class MobilePushStore {+ private let defaults: UserDefaults+ private let lock = NSLock()++ init(defaults: UserDefaults = .standard) {+ self.defaults = defaults+ }++ func installationId() -> String {+ lock.lock()+ defer { lock.unlock() }+ if let existing = defaults.string(forKey: Keys.installationId) { return existing }+ let created = UUID().uuidString.lowercased()+ defaults.set(created, forKey: Keys.installationId)+ return created+ }++ func registration() -> MobilePushRegistrationState {+ lock.lock()+ defer { lock.unlock() }+ return unlockedRegistration()+ }++ @discardableResult+ func updateCurrentToken(_ token: String) -> Bool {+ lock.lock()+ defer { lock.unlock() }+ guard token.utf8.count >= 16, token.utf8.count <= 4096 else { return false }+ let current = unlockedRegistration()+ let next = current.withCurrentToken(token)+ guard next != current else { return false }+ defaults.set(next.currentToken, forKey: Keys.currentToken)+ return true+ }++ func acknowledge(_ token: String) -> Bool {+ lock.lock()+ defer { lock.unlock() }+ guard token.utf8.count >= 16, token.utf8.count <= 4096 else { return false }+ let current = unlockedRegistration()+ let next = current.acknowledging(token)+ defaults.set(next.acknowledgedToken, forKey: Keys.acknowledgedToken)+ return true+ }++ func saveActivation(_ route: MobilePushRoute) {+ lock.lock()+ defer { lock.unlock() }+ defaults.set(route.notificationId, forKey: Keys.pendingNotificationId)+ defaults.set(route.messageId, forKey: Keys.pendingMessageId)+ defaults.set(route.targetId, forKey: Keys.pendingTargetId)+ }++ func takeActivation() -> MobilePushRoute? {+ lock.lock()+ defer { lock.unlock() }+ let route = MobilePushRoute.create(+ notificationId: defaults.string(forKey: Keys.pendingNotificationId),+ messageId: defaults.string(forKey: Keys.pendingMessageId),+ targetId: defaults.string(forKey: Keys.pendingTargetId)+ )+ defaults.removeObject(forKey: Keys.pendingNotificationId)+ defaults.removeObject(forKey: Keys.pendingMessageId)+ defaults.removeObject(forKey: Keys.pendingTargetId)+ return route+ }++ private func unlockedRegistration() -> MobilePushRegistrationState {+ MobilePushRegistrationState(+ currentToken: defaults.string(forKey: Keys.currentToken),+ acknowledgedToken: defaults.string(forKey: Keys.acknowledgedToken)+ )+ }++ private enum Keys {+ static let installationId = "alook.mobilePush.installationId"+ static let currentToken = "alook.mobilePush.currentToken"+ static let acknowledgedToken = "alook.mobilePush.acknowledgedToken"+ static let pendingNotificationId = "alook.mobilePush.pendingNotificationId"+ static let pendingMessageId = "alook.mobilePush.pendingMessageId"+ static let pendingTargetId = "alook.mobilePush.pendingTargetId"+ }+}++private final class MobilePushNotificationHandler: NSObject, UNUserNotificationCenterDelegate {+ func userNotificationCenter(+ _ center: UNUserNotificationCenter,+ willPresent notification: UNNotification,+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void+ ) {+ completionHandler([.banner, .list, .sound])+ }++ func userNotificationCenter(+ _ center: UNUserNotificationCenter,+ didReceive response: UNNotificationResponse,+ withCompletionHandler completionHandler: @escaping () -> Void+ ) {+ defer { completionHandler() }+ guard let route = MobilePushRoute.from(response.notification.request.content.userInfo) else {+ return+ }+ MobilePushBridge.shared.acceptActivation(route)+ }+}++private final class MobilePushBridge {+ static let shared = MobilePushBridge()++ let store = MobilePushStore()+ let notificationHandler = MobilePushNotificationHandler()+ weak var plugin: MobilePushPlugin?++ func acceptDeviceToken(_ data: Data) {+ let token = data.map { String(format: "%02x", $0) }.joined()+ if store.updateCurrentToken(token) { plugin?.signal() }+ }++ func acceptRegistrationFailure() {+ plugin?.signal()+ }++ func acceptActivation(_ route: MobilePushRoute) {+ store.saveActivation(route)+ plugin?.signal()+ }+}++private enum MobilePushDelegateHooks {+ private static let lock = NSLock()+ private static var installedClasses = Set<String>()++ static func install() {+ dispatchPrecondition(condition: .onQueue(.main))+ guard let delegate = UIApplication.shared.delegate,+ let delegateClass = object_getClass(delegate)+ else { return }+ let className = NSStringFromClass(delegateClass)+ lock.lock()+ defer { lock.unlock() }+ guard installedClasses.insert(className).inserted else { return }+ installDeviceToken(on: delegateClass)+ installFailure(on: delegateClass)+ }++ private static func installDeviceToken(on delegateClass: AnyClass) {+ let selector = #selector(+ UIApplicationDelegate.application(_:didRegisterForRemoteNotificationsWithDeviceToken:)+ )+ typealias Callback = @convention(c) (AnyObject, Selector, UIApplication, Data) -> Void+ let original = class_getInstanceMethod(delegateClass, selector)+ .map { unsafeBitCast(method_getImplementation($0), to: Callback.self) }+ let block: @convention(block) (AnyObject, UIApplication, Data) -> Void = {+ receiver, application, token in+ original?(receiver, selector, application, token)+ MobilePushBridge.shared.acceptDeviceToken(token)+ }+ let implementation = imp_implementationWithBlock(block)+ let encoding = class_getInstanceMethod(delegateClass, selector)+ .flatMap { method_getTypeEncoding($0) }+ addOrReplace(+ selector,+ on: delegateClass,+ implementation: implementation,+ encoding: encoding+ )+ }++ private static func installFailure(on delegateClass: AnyClass) {+ let selector = #selector(+ UIApplicationDelegate.application(_:didFailToRegisterForRemoteNotificationsWithError:)+ )+ typealias Callback = @convention(c) (AnyObject, Selector, UIApplication, Error) -> Void+ let original = class_getInstanceMethod(delegateClass, selector)+ .map { unsafeBitCast(method_getImplementation($0), to: Callback.self) }+ let block: @convention(block) (AnyObject, UIApplication, Error) -> Void = {+ receiver, application, error in+ original?(receiver, selector, application, error)+ MobilePushBridge.shared.acceptRegistrationFailure()+ }+ let implementation = imp_implementationWithBlock(block)+ let encoding = class_getInstanceMethod(delegateClass, selector)+ .flatMap { method_getTypeEncoding($0) }+ addOrReplace(+ selector,+ on: delegateClass,+ implementation: implementation,+ encoding: encoding+ )+ }++ private static func addOrReplace(+ _ selector: Selector,+ on delegateClass: AnyClass,+ implementation: IMP,+ encoding: UnsafePointer<CChar>?+ ) {+ let added: Bool+ if let encoding = encoding {+ added = class_addMethod(delegateClass, selector, implementation, encoding)+ } else {+ added = "v@:@@".withCString {+ class_addMethod(delegateClass, selector, implementation, $0)+ }+ }+ if !added, let method = class_getInstanceMethod(delegateClass, selector) {+ method_setImplementation(method, implementation)+ }+ }+}++private struct PermissionResponse: Encodable {+ let permissionState: String+}++private struct RegistrationSnapshot: Encodable {+ let installationId: String+ let platform: String+ let providerEnvironment: String+ let providerToken: String?+ let previousProviderToken: String?+ let appVersion: String?+}++private struct AcknowledgeRegistrationArgs: Decodable {+ let providerToken: String+}++private struct ListenArgs: Decodable {+ let channel: Channel+}++private struct UnlistenArgs: Decodable {+ let registrationId: UInt64+}++final class MobilePushPlugin: Plugin {+ private let bridge = MobilePushBridge.shared+ private var listener: Channel?+ private var lifecycleObserver: NSObjectProtocol?++ override init() {+ super.init()+ bridge.plugin = self+ UNUserNotificationCenter.current().delegate = bridge.notificationHandler+ DispatchQueue.main.async {+ MobilePushDelegateHooks.install()+ UIApplication.shared.registerForRemoteNotifications()+ }+ lifecycleObserver = NotificationCenter.default.addObserver(+ forName: UIApplication.didBecomeActiveNotification,+ object: nil,+ queue: .main+ ) { [weak self] _ in+ UIApplication.shared.registerForRemoteNotifications()+ self?.signal()+ }+ }++ deinit {+ if let lifecycleObserver = lifecycleObserver {+ NotificationCenter.default.removeObserver(lifecycleObserver)+ }+ }++ @objc override public func checkPermissions(_ invoke: Invoke) {+ UNUserNotificationCenter.current().getNotificationSettings { settings in+ invoke.resolve(PermissionResponse(permissionState: self.permissionState(settings)))+ }+ }++ @objc override public func requestPermissions(_ invoke: Invoke) {+ UNUserNotificationCenter.current().requestAuthorization(+ options: [.alert, .sound, .badge]+ ) { _, error in+ guard error == nil else {+ invoke.reject("Notification permission is unavailable", code: "permission_unavailable")+ return+ }+ DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() }+ self.checkPermissions(invoke)+ }+ }++ @objc public func snapshot(_ invoke: Invoke) {+ let registration = bridge.store.registration()+ invoke.resolve(RegistrationSnapshot(+ installationId: bridge.store.installationId(),+ platform: "ios",+ providerEnvironment: providerEnvironment(),+ providerToken: registration.currentToken,+ previousProviderToken: registration.previousToken,+ appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String+ ))+ }++ @objc public func acknowledgeRegistration(_ invoke: Invoke) {+ do {+ let args = try invoke.parseArgs(AcknowledgeRegistrationArgs.self)+ guard bridge.store.acknowledge(args.providerToken) else {+ invoke.reject("Registration token changed", code: "stale_token")+ return+ }+ invoke.resolve()+ } catch {+ invoke.reject("Registration acknowledgement is invalid", code: "invalid_request")+ }+ }++ @objc public func takeActivation(_ invoke: Invoke) {+ guard let activation = bridge.store.takeActivation() else {+ invoke.resolve()+ return+ }+ invoke.resolve(activation)+ }++ @objc public func listen(_ invoke: Invoke) {+ do {+ let args = try invoke.parseArgs(ListenArgs.self)+ listener = args.channel+ invoke.resolve(args.channel.id)+ } catch {+ invoke.reject("Notification listener is invalid", code: "invalid_request")+ }+ }++ @objc public func unlisten(_ invoke: Invoke) {+ do {+ let args = try invoke.parseArgs(UnlistenArgs.self)+ if listener?.id == args.registrationId { listener = nil }+ invoke.resolve()+ } catch {+ invoke.reject("Notification listener is invalid", code: "invalid_request")+ }+ }++ func signal() {+ listener?.send([:])+ }++ private func permissionState(_ settings: UNNotificationSettings) -> String {+ switch settings.authorizationStatus {+ case .authorized, .ephemeral, .provisional:+ return "granted"+ case .denied:+ return "denied"+ case .notDetermined:+ return "prompt"+ @unknown default:+ return "prompt"+ }+ }++ private func providerEnvironment() -> String {+ #if DEBUG+ return "sandbox"+ #else+ return "production"+ #endif+ }+}++@_cdecl("init_plugin_mobile_push")+func initPlugin() -> Plugin {+ MobilePushPlugin()+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/ios/Tests/MobilePushPluginTests/MobilePushPluginTests.swift b/src/desktop/src-tauri/plugins/mobile-push/ios/Tests/MobilePushPluginTests/MobilePushPluginTests.swiftnew file mode 100644index 000000000..0e99e0a63--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/ios/Tests/MobilePushPluginTests/MobilePushPluginTests.swift@@ -0,0 +1,77 @@+import XCTest+@testable import tauri_plugin_mobile_push++final class MobilePushPluginTests: XCTestCase {+ func testRouteAcceptsOnlyCanonicalAllowlistedValues() {+ XCTAssertEqual(+ MobilePushRoute.create(+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ messageId: "message_1",+ targetId: "channel-2"+ ),+ MobilePushRoute(+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ messageId: "message_1",+ targetId: "channel-2"+ )+ )+ XCTAssertNil(MobilePushRoute.create(+ notificationId: "bad",+ messageId: "message_1",+ targetId: "channel-2"+ ))+ XCTAssertNil(MobilePushRoute.create(+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ messageId: "../message",+ targetId: "channel-2"+ ))+ }++ func testRouteIgnoresTransportExtrasAndStoresOnlyThreeFields() {+ let route = MobilePushRoute.from([+ "notificationId": "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ "messageId": "message_1",+ "targetId": "channel_2",+ "aps": ["transport": true],+ ])+ XCTAssertEqual(route?.messageId, "message_1")+ XCTAssertEqual(route?.targetId, "channel_2")+ }++ func testSuccessfulPostedTokenBecomesProofAcrossAConcurrentRotation() {+ let t0 = "token-00000000000"+ let t1 = "token-11111111111"+ let t2 = "token-22222222222"+ let initial = MobilePushRegistrationState(currentToken: t0).acknowledging(t0)+ XCTAssertNil(initial.previousToken)++ let failedT1 = initial.withCurrentToken(t1)+ XCTAssertEqual(failedT1.previousToken, t0)++ let failedT2 = failedT1.withCurrentToken(t2)+ XCTAssertEqual(failedT2.previousToken, t0)+ let acknowledgedT1 = failedT2.acknowledging(t1)+ XCTAssertEqual(acknowledgedT1.previousToken, t1)++ let acknowledgedT2 = acknowledgedT1.acknowledging(t2)+ XCTAssertNil(acknowledgedT2.previousToken)+ XCTAssertEqual(acknowledgedT2.acknowledgedToken, t2)+ }++ func testStoreUsesOneStableInstallationAndConsumesActivationOnce() {+ let suite = "mobile-push-tests-\(UUID().uuidString)"+ let defaults = UserDefaults(suiteName: suite)!+ defer { defaults.removePersistentDomain(forName: suite) }+ let store = MobilePushStore(defaults: defaults)+ XCTAssertEqual(store.installationId(), store.installationId())++ let route = MobilePushRoute(+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ messageId: "message_1",+ targetId: "channel_2"+ )+ store.saveActivation(route)+ XCTAssertEqual(store.takeActivation(), route)+ XCTAssertNil(store.takeActivation())+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/acknowledgeRegistration.toml b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/acknowledgeRegistration.tomlnew file mode 100644index 000000000..933f467e7--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/acknowledgeRegistration.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-acknowledgeRegistration"+description = "Enables the acknowledgeRegistration command without any pre-configured scope."+commands.allow = ["acknowledgeRegistration"]++[[permission]]+identifier = "deny-acknowledgeRegistration"+description = "Denies the acknowledgeRegistration command without any pre-configured scope."+commands.deny = ["acknowledgeRegistration"]diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/listen.toml b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/listen.tomlnew file mode 100644index 000000000..d8283f840--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/listen.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-listen"+description = "Enables the listen command without any pre-configured scope."+commands.allow = ["listen"]++[[permission]]+identifier = "deny-listen"+description = "Denies the listen command without any pre-configured scope."+commands.deny = ["listen"]diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/snapshot.toml b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/snapshot.tomlnew file mode 100644index 000000000..0b0fd7af5--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/snapshot.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-snapshot"+description = "Enables the snapshot command without any pre-configured scope."+commands.allow = ["snapshot"]++[[permission]]+identifier = "deny-snapshot"+description = "Denies the snapshot command without any pre-configured scope."+commands.deny = ["snapshot"]diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/takeActivation.toml b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/takeActivation.tomlnew file mode 100644index 000000000..340321382--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/takeActivation.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-takeActivation"+description = "Enables the takeActivation command without any pre-configured scope."+commands.allow = ["takeActivation"]++[[permission]]+identifier = "deny-takeActivation"+description = "Denies the takeActivation command without any pre-configured scope."+commands.deny = ["takeActivation"]diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/unlisten.toml b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/unlisten.tomlnew file mode 100644index 000000000..b9db8b320--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/commands/unlisten.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-unlisten"+description = "Enables the unlisten command without any pre-configured scope."+commands.allow = ["unlisten"]++[[permission]]+identifier = "deny-unlisten"+description = "Denies the unlisten command without any pre-configured scope."+commands.deny = ["unlisten"]diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/reference.md b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/reference.mdnew file mode 100644index 000000000..445f163e3--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/autogenerated/reference.md@@ -0,0 +1,139 @@+## Permission Table++<table>+<tr>+<th>Identifier</th>+<th>Description</th>+</tr>+++<tr>+<td>++`mobile-push:allow-acknowledgeRegistration`++</td>+<td>++Enables the acknowledgeRegistration command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:deny-acknowledgeRegistration`++</td>+<td>++Denies the acknowledgeRegistration command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:allow-listen`++</td>+<td>++Enables the listen command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:deny-listen`++</td>+<td>++Denies the listen command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:allow-snapshot`++</td>+<td>++Enables the snapshot command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:deny-snapshot`++</td>+<td>++Denies the snapshot command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:allow-takeActivation`++</td>+<td>++Enables the takeActivation command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:deny-takeActivation`++</td>+<td>++Denies the takeActivation command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:allow-unlisten`++</td>+<td>++Enables the unlisten command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`mobile-push:deny-unlisten`++</td>+<td>++Denies the unlisten command without any pre-configured scope.++</td>+</tr>+</table>diff --git a/src/desktop/src-tauri/plugins/mobile-push/permissions/schemas/schema.json b/src/desktop/src-tauri/plugins/mobile-push/permissions/schemas/schema.jsonnew file mode 100644index 000000000..81dba9093--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/permissions/schemas/schema.json@@ -0,0 +1,360 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "PermissionFile",+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",+ "type": "object",+ "properties": {+ "default": {+ "description": "The default permission set for the plugin",+ "anyOf": [+ {+ "$ref": "#/definitions/DefaultPermission"+ },+ {+ "type": "null"+ }+ ]+ },+ "set": {+ "description": "A list of permissions sets defined",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionSet"+ }+ },+ "permission": {+ "description": "A list of inlined permissions",+ "default": [],+ "type": "array",+ "items": {+ "$ref": "#/definitions/Permission"+ }+ }+ },+ "definitions": {+ "DefaultPermission": {+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",+ "type": "object",+ "required": [+ "permissions"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "PermissionSet": {+ "description": "A set of direct permissions grouped together under a new name.",+ "type": "object",+ "required": [+ "description",+ "identifier",+ "permissions"+ ],+ "properties": {+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does.",+ "type": "string"+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionKind"+ }+ }+ }+ },+ "Permission": {+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",+ "type": "object",+ "required": [+ "identifier"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "commands": {+ "description": "Allowed or denied commands when using this permission.",+ "default": {+ "allow": [],+ "deny": []+ },+ "allOf": [+ {+ "$ref": "#/definitions/Commands"+ }+ ]+ },+ "scope": {+ "description": "Allowed or denied scoped when using this permission.",+ "allOf": [+ {+ "$ref": "#/definitions/Scopes"+ }+ ]+ },+ "platforms": {+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Target"+ }+ }+ }+ },+ "Commands": {+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Allowed command.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "deny": {+ "description": "Denied command, which takes priority.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "Scopes": {+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Data that defines what is allowed by the scope.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ "deny": {+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ }+ }+ },+ "Value": {+ "description": "All supported ACL values.",+ "anyOf": [+ {+ "description": "Represents a null JSON value.",+ "type": "null"+ },+ {+ "description": "Represents a [`bool`].",+ "type": "boolean"+ },+ {+ "description": "Represents a valid ACL [`Number`].",+ "allOf": [+ {+ "$ref": "#/definitions/Number"+ }+ ]+ },+ {+ "description": "Represents a [`String`].",+ "type": "string"+ },+ {+ "description": "Represents a list of other [`Value`]s.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ {+ "description": "Represents a map of [`String`] keys to [`Value`]s.",+ "type": "object",+ "additionalProperties": {+ "$ref": "#/definitions/Value"+ }+ }+ ]+ },+ "Number": {+ "description": "A valid ACL number.",+ "anyOf": [+ {+ "description": "Represents an [`i64`].",+ "type": "integer",+ "format": "int64"+ },+ {+ "description": "Represents a [`f64`].",+ "type": "number",+ "format": "double"+ }+ ]+ },+ "Target": {+ "description": "Platform target.",+ "oneOf": [+ {+ "description": "MacOS.",+ "type": "string",+ "enum": [+ "macOS"+ ]+ },+ {+ "description": "Windows.",+ "type": "string",+ "enum": [+ "windows"+ ]+ },+ {+ "description": "Linux.",+ "type": "string",+ "enum": [+ "linux"+ ]+ },+ {+ "description": "Android.",+ "type": "string",+ "enum": [+ "android"+ ]+ },+ {+ "description": "iOS.",+ "type": "string",+ "enum": [+ "iOS"+ ]+ }+ ]+ },+ "PermissionKind": {+ "type": "string",+ "oneOf": [+ {+ "description": "Enables the acknowledgeRegistration command without any pre-configured scope.",+ "type": "string",+ "const": "allow-acknowledgeRegistration",+ "markdownDescription": "Enables the acknowledgeRegistration command without any pre-configured scope."+ },+ {+ "description": "Denies the acknowledgeRegistration command without any pre-configured scope.",+ "type": "string",+ "const": "deny-acknowledgeRegistration",+ "markdownDescription": "Denies the acknowledgeRegistration command without any pre-configured scope."+ },+ {+ "description": "Enables the listen command without any pre-configured scope.",+ "type": "string",+ "const": "allow-listen",+ "markdownDescription": "Enables the listen command without any pre-configured scope."+ },+ {+ "description": "Denies the listen command without any pre-configured scope.",+ "type": "string",+ "const": "deny-listen",+ "markdownDescription": "Denies the listen command without any pre-configured scope."+ },+ {+ "description": "Enables the snapshot command without any pre-configured scope.",+ "type": "string",+ "const": "allow-snapshot",+ "markdownDescription": "Enables the snapshot command without any pre-configured scope."+ },+ {+ "description": "Denies the snapshot command without any pre-configured scope.",+ "type": "string",+ "const": "deny-snapshot",+ "markdownDescription": "Denies the snapshot command without any pre-configured scope."+ },+ {+ "description": "Enables the takeActivation command without any pre-configured scope.",+ "type": "string",+ "const": "allow-takeActivation",+ "markdownDescription": "Enables the takeActivation command without any pre-configured scope."+ },+ {+ "description": "Denies the takeActivation command without any pre-configured scope.",+ "type": "string",+ "const": "deny-takeActivation",+ "markdownDescription": "Denies the takeActivation command without any pre-configured scope."+ },+ {+ "description": "Enables the unlisten command without any pre-configured scope.",+ "type": "string",+ "const": "allow-unlisten",+ "markdownDescription": "Enables the unlisten command without any pre-configured scope."+ },+ {+ "description": "Denies the unlisten command without any pre-configured scope.",+ "type": "string",+ "const": "deny-unlisten",+ "markdownDescription": "Denies the unlisten command without any pre-configured scope."+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/src/desktop/src-tauri/plugins/mobile-push/src/desktop.rs b/src/desktop/src-tauri/plugins/mobile-push/src/desktop.rsnew file mode 100644index 000000000..9266bb89e--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/src/desktop.rs@@ -0,0 +1,42 @@+use crate::{Activation, Error, PermissionResponse, RegistrationSnapshot};+use serde::de::DeserializeOwned;+use tauri::{ipc::Channel, plugin::PluginApi, AppHandle, Runtime};++pub fn init<R: Runtime, C: DeserializeOwned>(+ _app: &AppHandle<R>,+ _api: PluginApi<R, C>,+) -> Result<MobilePush<R>, Error> {+ Ok(MobilePush(std::marker::PhantomData))+}++pub struct MobilePush<R: Runtime>(std::marker::PhantomData<R>);++impl<R: Runtime> MobilePush<R> {+ pub async fn check_permissions(&self) -> Result<PermissionResponse, Error> {+ Err(Error::unavailable("Mobile push is unavailable"))+ }++ pub async fn request_permissions(&self) -> Result<PermissionResponse, Error> {+ Err(Error::unavailable("Mobile push is unavailable"))+ }++ pub async fn snapshot(&self) -> Result<RegistrationSnapshot, Error> {+ Err(Error::unavailable("Mobile push is unavailable"))+ }++ pub async fn acknowledge_registration(&self, _provider_token: String) -> Result<(), Error> {+ Err(Error::unavailable("Mobile push is unavailable"))+ }++ pub async fn take_activation(&self) -> Result<Option<Activation>, Error> {+ Err(Error::unavailable("Mobile push is unavailable"))+ }++ pub async fn listen(&self, _channel: Channel<()>) -> Result<u64, Error> {+ Err(Error::unavailable("Mobile push is unavailable"))+ }++ pub async fn unlisten(&self, _registration_id: u64) -> Result<(), Error> {+ Err(Error::unavailable("Mobile push is unavailable"))+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/error.rs b/src/desktop/src-tauri/plugins/mobile-push/src/error.rsnew file mode 100644index 000000000..4e61f4cea--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/src/error.rs@@ -0,0 +1,30 @@+#[derive(Clone, Debug, thiserror::Error)]+#[error("[{code}] {message}")]+pub struct Error {+ pub code: String,+ pub message: String,+}++impl Error {+ pub fn unavailable(message: impl Into<String>) -> Self {+ Self {+ code: "unavailable".to_string(),+ message: message.into(),+ }+ }+}++#[cfg(mobile)]+impl From<tauri::plugin::mobile::PluginInvokeError> for Error {+ fn from(error: tauri::plugin::mobile::PluginInvokeError) -> Self {+ match error {+ tauri::plugin::mobile::PluginInvokeError::InvokeRejected(response) => Self {+ code: response.code.unwrap_or_else(|| "native_failed".to_string()),+ message: response+ .message+ .unwrap_or_else(|| "Native push operation failed".to_string()),+ },+ other => Self::unavailable(other.to_string()),+ }+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/lib.rs b/src/desktop/src-tauri/plugins/mobile-push/src/lib.rsnew file mode 100644index 000000000..dae7bf097--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/src/lib.rs@@ -0,0 +1,44 @@+use tauri::{+ plugin::{Builder, TauriPlugin},+ Manager, Runtime,+};++#[cfg(desktop)]+mod desktop;+mod error;+#[cfg(mobile)]+mod mobile;+mod models;++#[cfg(desktop)]+use desktop::MobilePush;+pub use error::Error;+#[cfg(mobile)]+use mobile::MobilePush;+pub use models::{+ AcknowledgeRequest, Activation, ListenRequest, PermissionResponse, RegistrationSnapshot,+ UnlistenRequest,+};++pub trait MobilePushExt<R: Runtime> {+ fn mobile_push(&self) -> &MobilePush<R>;+}++impl<R: Runtime, T: Manager<R>> MobilePushExt<R> for T {+ fn mobile_push(&self) -> &MobilePush<R> {+ self.state::<MobilePush<R>>().inner()+ }+}++pub fn init<R: Runtime>() -> TauriPlugin<R> {+ Builder::<R, ()>::new("mobile-push")+ .setup(|app, api| {+ #[cfg(mobile)]+ let plugin = mobile::init(app, api)?;+ #[cfg(desktop)]+ let plugin = desktop::init(app, api)?;+ app.manage(plugin);+ Ok(())+ })+ .build()+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/mobile.rs b/src/desktop/src-tauri/plugins/mobile-push/src/mobile.rsnew file mode 100644index 000000000..915e7202c--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/src/mobile.rs@@ -0,0 +1,83 @@+use crate::{+ AcknowledgeRequest, Activation, Error, ListenRequest, PermissionResponse, RegistrationSnapshot,+ UnlistenRequest,+};+use serde::de::DeserializeOwned;+use tauri::{+ ipc::Channel,+ plugin::{PluginApi, PluginHandle},+ AppHandle, Runtime,+};++#[cfg(target_os = "android")]+const PLUGIN_IDENTIFIER: &str = "ai.alook.plugin.mobilepush";++#[cfg(target_os = "ios")]+tauri::ios_plugin_binding!(init_plugin_mobile_push);++pub fn init<R: Runtime, C: DeserializeOwned>(+ _app: &AppHandle<R>,+ api: PluginApi<R, C>,+) -> Result<MobilePush<R>, Error> {+ #[cfg(target_os = "android")]+ let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "MobilePushPlugin")?;+ #[cfg(target_os = "ios")]+ let handle = api.register_ios_plugin(init_plugin_mobile_push)?;+ Ok(MobilePush(handle))+}++pub struct MobilePush<R: Runtime>(PluginHandle<R>);++impl<R: Runtime> MobilePush<R> {+ pub async fn check_permissions(&self) -> Result<PermissionResponse, Error> {+ self.0+ .run_mobile_plugin_async("checkPermissions", ())+ .await+ .map_err(Into::into)+ }++ pub async fn request_permissions(&self) -> Result<PermissionResponse, Error> {+ self.0+ .run_mobile_plugin_async("requestPermissions", ())+ .await+ .map_err(Into::into)+ }++ pub async fn snapshot(&self) -> Result<RegistrationSnapshot, Error> {+ self.0+ .run_mobile_plugin_async("snapshot", ())+ .await+ .map_err(Into::into)+ }++ pub async fn acknowledge_registration(&self, provider_token: String) -> Result<(), Error> {+ self.0+ .run_mobile_plugin_async(+ "acknowledgeRegistration",+ AcknowledgeRequest { provider_token },+ )+ .await+ .map_err(Into::into)+ }++ pub async fn take_activation(&self) -> Result<Option<Activation>, Error> {+ self.0+ .run_mobile_plugin_async("takeActivation", ())+ .await+ .map_err(Into::into)+ }++ pub async fn listen(&self, channel: Channel<()>) -> Result<u64, Error> {+ self.0+ .run_mobile_plugin_async("listen", ListenRequest { channel })+ .await+ .map_err(Into::into)+ }++ pub async fn unlisten(&self, registration_id: u64) -> Result<(), Error> {+ self.0+ .run_mobile_plugin_async("unlisten", UnlistenRequest { registration_id })+ .await+ .map_err(Into::into)+ }+}diff --git a/src/desktop/src-tauri/plugins/mobile-push/src/models.rs b/src/desktop/src-tauri/plugins/mobile-push/src/models.rsnew file mode 100644index 000000000..60d0a4ae5--- /dev/null+++ b/src/desktop/src-tauri/plugins/mobile-push/src/models.rs@@ -0,0 +1,45 @@+use serde::{Deserialize, Serialize};+use tauri::ipc::Channel;++#[derive(Clone, Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PermissionResponse {+ pub permission_state: String,+}++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct RegistrationSnapshot {+ pub installation_id: String,+ pub platform: String,+ pub provider_environment: String,+ pub provider_token: Option<String>,+ pub previous_provider_token: Option<String>,+ pub app_version: Option<String>,+}++#[derive(Clone, Debug, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Activation {+ pub notification_id: String,+ pub message_id: String,+ pub target_id: String,+}++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct AcknowledgeRequest {+ pub provider_token: String,+}++#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ListenRequest {+ pub channel: Channel<()>,+}++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct UnlistenRequest {+ pub registration_id: u64,+}diff --git a/src/desktop/src-tauri/src/lib.rs b/src/desktop/src-tauri/src/lib.rsindex f0fe45dba..88a2ab81f 100644--- a/src/desktop/src-tauri/src/lib.rs+++ b/src/desktop/src-tauri/src/lib.rs@@ -6,9 +6,15 @@ use tauri::Manager;mod mobile_share_image;#[cfg(mobile)]mod mobile_share_image_runtime;+#[cfg(any(mobile, test))]+mod mobile_system_notification;+#[cfg(mobile)]+mod mobile_system_notification_runtime;mod native_command_guard;mod native_oauth;mod native_oauth_runtime;+#[cfg(desktop)]+mod system_notifications;mod webview_recovery;#[cfg(desktop)]@@ -24,7 +30,8 @@ mod macos_window;pub fn run() {let builder = webview_recovery::register_protocol(tauri::Builder::default());#[cfg(desktop)]- let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {+ let builder = builder.plugin(tauri_plugin_single_instance::init(|app, args, _cwd| {+ system_notifications::intake_args(app, &args);commands::show_main_window(app);}));let builder = builder@@ -68,10 +75,18 @@ pub fn run() {fn run_mobile(mut builder: tauri::Builder<tauri::Wry>) {builder = builder.manage(mobile_share_image::MobileShareImageState::default())- .plugin(tauri_plugin_mobile_share_image::init());+ .plugin(tauri_plugin_mobile_share_image::init())+ .plugin(tauri_plugin_mobile_push::init());builder = builder.invoke_handler(tauri::generate_handler![mobile_share_image_runtime::mobile_share_image_copy,mobile_share_image_runtime::mobile_share_image_save,+ mobile_system_notification_runtime::mobile_system_notification_check_permission,+ mobile_system_notification_runtime::mobile_system_notification_request_permission,+ mobile_system_notification_runtime::mobile_system_notification_snapshot,+ mobile_system_notification_runtime::mobile_system_notification_acknowledge_registration,+ mobile_system_notification_runtime::mobile_system_notification_take_activation,+ mobile_system_notification_runtime::mobile_system_notification_listen,+ mobile_system_notification_runtime::mobile_system_notification_unlisten,native_oauth_runtime::native_oauth_snapshot,native_oauth_runtime::native_oauth_listen,native_oauth_runtime::native_oauth_unlisten,@@ -132,6 +147,10 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {native_oauth_runtime::native_oauth_reject_candidate,native_oauth_runtime::native_oauth_finish,native_oauth_runtime::native_oauth_cancel,+ system_notifications::desktop_system_notification_show,+ system_notifications::desktop_system_notification_listen,+ system_notifications::desktop_system_notification_take_activation,+ system_notifications::desktop_system_notification_unlisten,]);// System tray + window setup (desktop only)@@ -142,6 +161,9 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {if native_oauth_runtime::setup(app.handle()).is_err() {eprintln!("native OAuth storage unavailable");}+ if system_notifications::setup(app.handle()).is_err() {+ eprintln!("desktop system notification storage unavailable");+ }zoom::restore(app)?;commands::setup_tray(app)?;updater::auto_check_updates(app.handle().clone());@@ -180,12 +202,14 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {&& matches!(payload.event(), tauri::webview::PageLoadEvent::Started){native_oauth_runtime::retire_listener(webview.app_handle());+ system_notifications::retire_listener(webview.app_handle());}});builder = builder.on_window_event(|window, event| {if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed) {native_oauth_runtime::retire_listener(window.app_handle());+ system_notifications::retire_listener(window.app_handle());}#[cfg(target_os = "macos")]if window.label() == "main"diff --git a/src/desktop/src-tauri/src/mobile_system_notification.rs b/src/desktop/src-tauri/src/mobile_system_notification.rsnew file mode 100644index 000000000..d9da1fd00--- /dev/null+++ b/src/desktop/src-tauri/src/mobile_system_notification.rs@@ -0,0 +1,243 @@+use serde::Serialize;++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PermissionResponse {+ pub permission_state: String,+}++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct RegistrationSnapshot {+ pub installation_id: String,+ pub platform: String,+ pub provider_environment: String,+ pub provider_token: Option<String>,+ pub previous_provider_token: Option<String>,+ pub app_version: Option<String>,+}++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Activation {+ pub notification_id: String,+ pub message_id: String,+ pub target_id: String,+}++#[derive(Clone, Debug, Serialize)]+pub struct MobileSystemNotificationError {+ pub code: String,+ pub message: String,+}++impl MobileSystemNotificationError {+ pub fn new(code: &str, message: impl Into<String>) -> Self {+ Self {+ code: code.to_string(),+ message: message.into(),+ }+ }+}++fn safe_id(value: &str) -> bool {+ !value.is_empty()+ && value.len() <= 128+ && value+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))+}++fn uuid(value: &str) -> bool {+ let bytes = value.as_bytes();+ bytes.len() == 36+ && [8, 13, 18, 23]+ .into_iter()+ .all(|index| bytes[index] == b'-')+ && bytes+ .iter()+ .enumerate()+ .all(|(index, byte)| [8, 13, 18, 23].contains(&index) || byte.is_ascii_hexdigit())+}++fn valid_token(value: &str) -> bool {+ (16..=4096).contains(&value.len()) && !value.chars().any(char::is_control)+}++pub fn validate_permission(+ permission: PermissionResponse,+) -> Result<PermissionResponse, MobileSystemNotificationError> {+ if matches!(+ permission.permission_state.as_str(),+ "granted" | "denied" | "prompt"+ ) {+ Ok(permission)+ } else {+ Err(MobileSystemNotificationError::new(+ "invalid_native_response",+ "Native permission state is invalid",+ ))+ }+}++pub fn validate_snapshot(+ snapshot: RegistrationSnapshot,+) -> Result<RegistrationSnapshot, MobileSystemNotificationError> {+ if !uuid(&snapshot.installation_id)+ || !matches!(snapshot.platform.as_str(), "ios" | "android")+ || !matches!(+ snapshot.provider_environment.as_str(),+ "sandbox" | "production"+ )+ || (snapshot.platform == "android" && snapshot.provider_environment != "production")+ || snapshot+ .provider_token+ .as_deref()+ .is_some_and(|token| !valid_token(token))+ || snapshot+ .previous_provider_token+ .as_deref()+ .is_some_and(|token| !valid_token(token))+ || snapshot.previous_provider_token.is_some()+ && snapshot.previous_provider_token == snapshot.provider_token+ || snapshot+ .app_version+ .as_deref()+ .is_some_and(|version| version.is_empty() || version.len() > 128)+ {+ return Err(MobileSystemNotificationError::new(+ "invalid_native_response",+ "Native registration state is invalid",+ ));+ }+ Ok(snapshot)+}++pub fn validate_provider_token(token: &str) -> Result<(), MobileSystemNotificationError> {+ if valid_token(token) {+ Ok(())+ } else {+ Err(MobileSystemNotificationError::new(+ "invalid_request",+ "Provider token is invalid",+ ))+ }+}++pub fn validate_activation(+ activation: Option<Activation>,+) -> Result<Option<Activation>, MobileSystemNotificationError> {+ if let Some(value) = activation.as_ref() {+ if !uuid(&value.notification_id)+ || !safe_id(&value.message_id)+ || !safe_id(&value.target_id)+ {+ return Err(MobileSystemNotificationError::new(+ "invalid_native_response",+ "Native notification route is invalid",+ ));+ }+ }+ Ok(activation)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn snapshot() -> RegistrationSnapshot {+ RegistrationSnapshot {+ installation_id: "123e4567-e89b-42d3-a456-426614174000".to_string(),+ platform: "ios".to_string(),+ provider_environment: "sandbox".to_string(),+ provider_token: Some("0123456789abcdef".to_string()),+ previous_provider_token: None,+ app_version: Some("0.1.36".to_string()),+ }+ }++ #[test]+ fn accepts_only_allowlisted_permission_states() {+ for state in ["granted", "denied", "prompt"] {+ let permission = PermissionResponse {+ permission_state: state.to_string(),+ };+ assert_eq!(+ validate_permission(permission).unwrap().permission_state,+ state+ );+ }++ let error = validate_permission(PermissionResponse {+ permission_state: "unknown".to_string(),+ })+ .unwrap_err();+ assert_eq!(error.code, "invalid_native_response");+ }++ #[test]+ fn accepts_valid_provider_tokens_and_rejects_invalid_values() {+ assert!(validate_provider_token("0123456789abcdef").is_ok());+ assert!(validate_provider_token(&"a".repeat(4096)).is_ok());++ for token in [+ "short".to_string(),+ "0123456789abcde\n".to_string(),+ "a".repeat(4097),+ ] {+ let error = validate_provider_token(&token).unwrap_err();+ assert_eq!(error.code, "invalid_request");+ assert!(!error.message.contains(&token));+ }+ }++ #[test]+ fn accepts_exact_mobile_registration_state() {+ assert!(validate_snapshot(snapshot()).is_ok());+ let mut android = snapshot();+ android.platform = "android".to_string();+ android.provider_environment = "production".to_string();+ android.previous_provider_token = Some("fedcba9876543210".to_string());+ assert!(validate_snapshot(android).is_ok());+ }++ #[test]+ fn rejects_invalid_registration_state_without_echoing_tokens() {+ for mutate in [+ |value: &mut RegistrationSnapshot| value.installation_id = "bad".to_string(),+ |value: &mut RegistrationSnapshot| value.platform = "desktop".to_string(),+ |value: &mut RegistrationSnapshot| value.provider_token = Some("short".to_string()),+ |value: &mut RegistrationSnapshot| {+ value.previous_provider_token = value.provider_token.clone()+ },+ ] {+ let mut value = snapshot();+ mutate(&mut value);+ let error = validate_snapshot(value).unwrap_err();+ assert_eq!(error.code, "invalid_native_response");+ assert!(!error.message.contains("0123456789abcdef"));+ }++ let mut android = snapshot();+ android.platform = "android".to_string();+ assert!(validate_snapshot(android).is_err());+ }++ #[test]+ fn accepts_only_allowlisted_activation_shape_values() {+ let value = Activation {+ notification_id: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e".to_string(),+ message_id: "message_1".to_string(),+ target_id: "channel-2".to_string(),+ };+ assert!(validate_activation(Some(value)).is_ok());+ assert!(validate_activation(None).is_ok());++ let invalid = Activation {+ notification_id: "bad".to_string(),+ message_id: "../message".to_string(),+ target_id: "channel".to_string(),+ };+ assert!(validate_activation(Some(invalid)).is_err());+ }+}diff --git a/src/desktop/src-tauri/src/mobile_system_notification_runtime.rs b/src/desktop/src-tauri/src/mobile_system_notification_runtime.rsnew file mode 100644index 000000000..9810ea249--- /dev/null+++ b/src/desktop/src-tauri/src/mobile_system_notification_runtime.rs@@ -0,0 +1,120 @@+use crate::mobile_system_notification::{+ validate_activation, validate_permission, validate_provider_token, validate_snapshot,+ Activation, MobileSystemNotificationError, PermissionResponse, RegistrationSnapshot,+};+use crate::native_command_guard::guard;+use tauri::{ipc::Channel, Manager, WebviewWindow};+use tauri_plugin_mobile_push::{Activation as NativeActivation, MobilePushExt};++impl From<tauri_plugin_mobile_push::Error> for MobileSystemNotificationError {+ fn from(error: tauri_plugin_mobile_push::Error) -> Self {+ Self {+ code: error.code,+ message: error.message,+ }+ }+}++#[tauri::command]+pub async fn mobile_system_notification_check_permission(+ window: WebviewWindow,+) -> Result<PermissionResponse, MobileSystemNotificationError> {+ guard(&window)+ .map_err(|code| MobileSystemNotificationError::new(code, "Caller is not trusted"))?;+ let native = window+ .app_handle()+ .mobile_push()+ .check_permissions()+ .await?;+ validate_permission(PermissionResponse {+ permission_state: native.permission_state,+ })+}++#[tauri::command]+pub async fn mobile_system_notification_request_permission(+ window: WebviewWindow,+) -> Result<PermissionResponse, MobileSystemNotificationError> {+ guard(&window)+ .map_err(|code| MobileSystemNotificationError::new(code, "Caller is not trusted"))?;+ let native = window+ .app_handle()+ .mobile_push()+ .request_permissions()+ .await?;+ validate_permission(PermissionResponse {+ permission_state: native.permission_state,+ })+}++#[tauri::command]+pub async fn mobile_system_notification_snapshot(+ window: WebviewWindow,+) -> Result<RegistrationSnapshot, MobileSystemNotificationError> {+ guard(&window)+ .map_err(|code| MobileSystemNotificationError::new(code, "Caller is not trusted"))?;+ let native = window.app_handle().mobile_push().snapshot().await?;+ validate_snapshot(RegistrationSnapshot {+ installation_id: native.installation_id,+ platform: native.platform,+ provider_environment: native.provider_environment,+ provider_token: native.provider_token,+ previous_provider_token: native.previous_provider_token,+ app_version: native.app_version,+ })+}++#[tauri::command]+pub async fn mobile_system_notification_acknowledge_registration(+ window: WebviewWindow,+ provider_token: String,+) -> Result<(), MobileSystemNotificationError> {+ guard(&window)+ .map_err(|code| MobileSystemNotificationError::new(code, "Caller is not trusted"))?;+ validate_provider_token(&provider_token)?;+ window+ .app_handle()+ .mobile_push()+ .acknowledge_registration(provider_token)+ .await?;+ Ok(())+}++#[tauri::command]+pub async fn mobile_system_notification_take_activation(+ window: WebviewWindow,+) -> Result<Option<Activation>, MobileSystemNotificationError> {+ guard(&window)+ .map_err(|code| MobileSystemNotificationError::new(code, "Caller is not trusted"))?;+ let native = window.app_handle().mobile_push().take_activation().await?;+ validate_activation(native.map(|value: NativeActivation| Activation {+ notification_id: value.notification_id,+ message_id: value.message_id,+ target_id: value.target_id,+ }))+}++#[tauri::command]+pub async fn mobile_system_notification_listen(+ window: WebviewWindow,+ channel: Channel<()>,+) -> Result<u64, MobileSystemNotificationError> {+ guard(&window)+ .map_err(|code| MobileSystemNotificationError::new(code, "Caller is not trusted"))?;+ Ok(window.app_handle().mobile_push().listen(channel).await?)+}++#[tauri::command]+pub async fn mobile_system_notification_unlisten(+ window: WebviewWindow,+ registration_id: u64,+) -> Result<(), MobileSystemNotificationError> {+ guard(&window)+ .map_err(|code| MobileSystemNotificationError::new(code, "Caller is not trusted"))?;+ window+ .app_handle()+ .mobile_push()+ .unlisten(registration_id)+ .await?;+ Ok(())+}diff --git a/src/desktop/src-tauri/src/system_notifications.rs b/src/desktop/src-tauri/src/system_notifications.rsnew file mode 100644index 000000000..078fc8511--- /dev/null+++ b/src/desktop/src-tauri/src/system_notifications.rs@@ -0,0 +1,786 @@+use crate::native_command_guard::guard;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::sync::{Arc, Mutex};+use tauri::{ipc::Channel, AppHandle, Manager, WebviewWindow};+use tauri_plugin_deep_link::DeepLinkExt;+use tauri_plugin_store::{Store, StoreExt};++const RECORD_VERSION: u8 = 1;+const MAX_RECENT: usize = 256;+const ACTIVATION_SCHEME: &str = "ai.alook.desktop";+const ACTIVATION_HOST: &str = "notification";+const ACTIVATION_PATH: &str = "/open";++#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]+pub enum NotificationTarget {+ Server {+ #[serde(rename = "serverId")]+ server_id: String,+ #[serde(rename = "channelId")]+ channel_id: String,+ #[serde(rename = "messageId")]+ message_id: String,+ seq: u64,+ },+ Dm {+ #[serde(rename = "channelId")]+ channel_id: String,+ #[serde(rename = "messageId")]+ message_id: String,+ seq: u64,+ },+}++impl NotificationTarget {+ fn message_id(&self) -> &str {+ match self {+ Self::Server { message_id, .. } | Self::Dm { message_id, .. } => message_id,+ }+ }++ fn valid(&self) -> bool {+ match self {+ Self::Server {+ server_id,+ channel_id,+ message_id,+ seq,+ } => valid_id(server_id) && valid_id(channel_id) && valid_id(message_id) && *seq > 0,+ Self::Dm {+ channel_id,+ message_id,+ seq,+ } => valid_id(channel_id) && valid_id(message_id) && *seq > 0,+ }+ }+}++#[derive(Clone, Debug, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct NotificationCandidate {+ viewer_user_id: String,+ title: String,+ body: String,+ target: NotificationTarget,+}++impl NotificationCandidate {+ fn valid(&self) -> bool {+ valid_id(&self.viewer_user_id)+ && !self.title.trim().is_empty()+ && self.title.chars().count() <= 256+ && !self.body.trim().is_empty()+ && self.body.chars().count() <= 512+ && self.target.valid()+ }+}++#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct NotificationActivation {+ notification_id: String,+ target: NotificationTarget,+}++#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+struct RecentNotification {+ notification_id: String,+ viewer_user_id: String,+ message_id: String,+ target: NotificationTarget,+ activated: bool,+}++#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(deny_unknown_fields)]+struct NotificationRecord {+ version: u8,+ recent: Vec<RecentNotification>,+}++impl NotificationRecord {+ fn new() -> Self {+ Self {+ version: RECORD_VERSION,+ recent: Vec::new(),+ }+ }++ fn restore(value: serde_json::Value) -> Result<Self, &'static str> {+ let record: Self = serde_json::from_value(value).map_err(|_| "store_invalid")?;+ if record.version != RECORD_VERSION+ || record.recent.len() > MAX_RECENT+ || record.recent.iter().any(|item| {+ !valid_notification_id(&item.notification_id)+ || !valid_id(&item.viewer_user_id)+ || !valid_id(&item.message_id)+ || item.message_id != item.target.message_id()+ || !item.target.valid()+ })+ {+ return Err("store_invalid");+ }+ Ok(record)+ }++ fn claim(&mut self, candidate: &NotificationCandidate) -> Option<String> {+ if !candidate.valid() {+ return None;+ }+ let notification_id =+ deterministic_notification_id(&candidate.viewer_user_id, candidate.target.message_id());+ if self.recent.iter().any(|item| {+ item.notification_id == notification_id+ || (item.viewer_user_id == candidate.viewer_user_id+ && item.message_id == candidate.target.message_id())+ }) {+ return None;+ }+ self.recent.push(RecentNotification {+ notification_id: notification_id.clone(),+ viewer_user_id: candidate.viewer_user_id.clone(),+ message_id: candidate.target.message_id().to_string(),+ target: candidate.target.clone(),+ activated: false,+ });+ if self.recent.len() > MAX_RECENT {+ self.recent.drain(0..self.recent.len() - MAX_RECENT);+ }+ Some(notification_id)+ }++ fn rollback(&mut self, notification_id: &str) {+ self.recent+ .retain(|item| item.notification_id != notification_id);+ }++ fn activate(&mut self, notification_id: &str) -> Option<NotificationActivation> {+ let item = self+ .recent+ .iter_mut()+ .find(|item| item.notification_id == notification_id && !item.activated)?;+ item.activated = true;+ Some(NotificationActivation {+ notification_id: item.notification_id.clone(),+ target: item.target.clone(),+ })+ }+}++struct Notifications<T> {+ next_id: u64,+ current: Option<(u64, T)>,+}++impl<T> Default for Notifications<T> {+ fn default() -> Self {+ Self {+ next_id: 0,+ current: None,+ }+ }+}++impl<T> Notifications<T> {+ fn install(&mut self, channel: T) -> u64 {+ self.next_id += 1;+ self.current = Some((self.next_id, channel));+ self.next_id+ }++ fn remove(&mut self, id: u64) {+ if self+ .current+ .as_ref()+ .is_some_and(|(current, _)| *current == id)+ {+ self.current = None;+ }+ }++ fn notify(&mut self, send: impl FnOnce(&T) -> bool) {+ if self+ .current+ .as_ref()+ .is_some_and(|(_, channel)| !send(channel))+ {+ self.current = None;+ }+ }+}++pub struct DesktopSystemNotificationState {+ record: Mutex<NotificationRecord>,+ store: Arc<Store<tauri::Wry>>,+ notifications: Mutex<Notifications<Channel<()>>>,+ pending: Mutex<Option<NotificationActivation>>,+}++impl DesktopSystemNotificationState {+ fn transact<T>(+ &self,+ action: impl FnOnce(&mut NotificationRecord) -> Result<T, &'static str>,+ ) -> Result<T, &'static str> {+ let mut current = self.record.lock().map_err(|_| "store_unavailable")?;+ let mut next = current.clone();+ let result = action(&mut next)?;+ self.store.set(+ "record",+ serde_json::to_value(&next).map_err(|_| "store_unavailable")?,+ );+ if self.store.save().is_err() {+ self.store.set(+ "record",+ serde_json::to_value(&*current).map_err(|_| "store_unavailable")?,+ );+ return Err("store_unavailable");+ }+ *current = next;+ Ok(result)+ }++ fn notify(&self) {+ if let Ok(mut listeners) = self.notifications.lock() {+ listeners.notify(|channel| channel.send(()).is_ok());+ }+ }+}++fn valid_id(value: &str) -> bool {+ !value.is_empty()+ && value.len() <= 128+ && value+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))+}++fn valid_notification_id(value: &str) -> bool {+ value.len() == 36+ && value.bytes().enumerate().all(|(index, byte)| match index {+ 8 | 13 | 18 | 23 => byte == b'-',+ _ => byte.is_ascii_hexdigit(),+ })+}++fn deterministic_notification_id(viewer_user_id: &str, message_id: &str) -> String {+ let mut digest = Sha256::new();+ digest.update(b"alook:desktop-notification:v1\0");+ digest.update(viewer_user_id.as_bytes());+ digest.update(b"\0");+ digest.update(message_id.as_bytes());+ let mut bytes: [u8; 16] = digest.finalize()[..16].try_into().expect("fixed digest");+ bytes[6] = (bytes[6] & 0x0f) | 0x50;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ format!(+ "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",+ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],+ bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]+ )+}++fn activation_id_from_url(url: &url::Url) -> Option<String> {+ if url.scheme() != ACTIVATION_SCHEME+ || url.host_str() != Some(ACTIVATION_HOST)+ || url.path() != ACTIVATION_PATH+ || url.username() != ""+ || url.password().is_some()+ || url.port().is_some()+ || url.fragment().is_some()+ {+ return None;+ }+ let mut pairs = url.query_pairs();+ let (key, value) = pairs.next()?;+ if key != "id" || pairs.next().is_some() || !valid_notification_id(&value) {+ return None;+ }+ Some(value.into_owned())+}++fn activate(app: &AppHandle, notification_id: &str) {+ let Some(state) = app.try_state::<DesktopSystemNotificationState>() else {+ return;+ };+ let Ok(Some(activation)) = state.transact(|record| Ok(record.activate(notification_id))) else {+ return;+ };+ if let Ok(mut pending) = state.pending.lock() {+ *pending = Some(activation);+ } else {+ return;+ }+ crate::commands::show_main_window(app);+ state.notify();+}++fn intake(app: &AppHandle, url: &url::Url) {+ if let Some(notification_id) = activation_id_from_url(url) {+ activate(app, ¬ification_id);+ }+}++pub fn intake_args(app: &AppHandle, args: &[String]) {+ for url in args.iter().filter_map(|arg| url::Url::parse(arg).ok()) {+ intake(app, &url);+ }+}++pub fn setup(app: &AppHandle) -> Result<(), Box<dyn std::error::Error>> {+ let path = app+ .path()+ .app_data_dir()?+ .join("desktop-system-notifications.json");+ std::fs::create_dir_all(path.parent().ok_or("store_unavailable")?)?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};+ std::fs::OpenOptions::new()+ .create(true)+ .write(true)+ .mode(0o600)+ .open(&path)?;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;+ }+ let store = app.store_builder(path).disable_auto_save().build()?;+ let record = store+ .get("record")+ .and_then(|value| NotificationRecord::restore(value).ok())+ .unwrap_or_else(NotificationRecord::new);+ let state = DesktopSystemNotificationState {+ record: Mutex::new(record),+ store,+ notifications: Mutex::new(Notifications::default()),+ pending: Mutex::new(None),+ };+ state.transact(|_| Ok(()))?;+ app.manage(state);++ #[cfg(target_os = "macos")]+ install_macos_delegate(app);++ let handle = app.clone();+ app.deep_link().on_open_url(move |event| {+ for url in event.urls() {+ intake(&handle, &url);+ }+ });+ if let Some(urls) = app.deep_link().get_current()? {+ for url in urls {+ intake(app, &url);+ }+ }+ Ok(())+}++pub fn retire_listener(app: &AppHandle) {+ if let Some(state) = app.try_state::<DesktopSystemNotificationState>() {+ if let Ok(mut listeners) = state.notifications.lock() {+ listeners.current = None;+ }+ }+}++#[tauri::command]+pub async fn desktop_system_notification_show(+ window: WebviewWindow,+ state: tauri::State<'_, DesktopSystemNotificationState>,+ candidate: NotificationCandidate,+) -> Result<(), &'static str> {+ guard(&window)?;+ if !candidate.valid() {+ return Err("notification_invalid");+ }+ let Some(notification_id) = state.transact(|record| Ok(record.claim(&candidate)))? else {+ return Ok(());+ };+ if display_notification(+ window.app_handle(),+ ¬ification_id,+ &candidate.title,+ &candidate.body,+ )+ .await+ .is_err()+ {+ state.transact(|record| {+ record.rollback(¬ification_id);+ Ok(())+ })?;+ return Err("notification_unavailable");+ }+ Ok(())+}++#[tauri::command]+pub fn desktop_system_notification_listen(+ window: WebviewWindow,+ channel: Channel<()>,+) -> Result<u64, &'static str> {+ guard(&window)?;+ let state = window+ .app_handle()+ .try_state::<DesktopSystemNotificationState>()+ .ok_or("store_unavailable")?;+ let id = state+ .notifications+ .lock()+ .map_err(|_| "listener_unavailable")?+ .install(channel);+ Ok(id)+}++#[tauri::command]+pub fn desktop_system_notification_unlisten(+ window: WebviewWindow,+ state: tauri::State<'_, DesktopSystemNotificationState>,+ registration_id: u64,+) -> Result<(), &'static str> {+ guard(&window)?;+ state+ .notifications+ .lock()+ .map_err(|_| "listener_unavailable")?+ .remove(registration_id);+ Ok(())+}++#[tauri::command]+pub fn desktop_system_notification_take_activation(+ window: WebviewWindow,+ state: tauri::State<'_, DesktopSystemNotificationState>,+) -> Result<Option<NotificationActivation>, &'static str> {+ guard(&window)?;+ Ok(state+ .pending+ .lock()+ .map_err(|_| "activation_unavailable")?+ .take())+}++#[cfg(target_os = "macos")]+async fn display_notification(+ _app: &AppHandle,+ notification_id: &str,+ title: &str,+ body: &str,+) -> Result<(), ()> {+ use block2::RcBlock;+ use objc2::runtime::Bool;+ use objc2_foundation::{NSError, NSString};+ use objc2_user_notifications::{+ UNAuthorizationOptions, UNMutableNotificationContent, UNNotificationRequest,+ UNNotificationSound, UNUserNotificationCenter,+ };++ let authorization = {+ let (sender, receiver) = std::sync::mpsc::channel();+ let completion = RcBlock::new(move |granted: Bool, error: *mut NSError| {+ let _ = sender.send(macos_authorization_result(+ granted.as_bool(),+ !error.is_null(),+ ));+ });+ UNUserNotificationCenter::currentNotificationCenter()+ .requestAuthorizationWithOptions_completionHandler(+ UNAuthorizationOptions::Alert | UNAuthorizationOptions::Sound,+ &completion,+ );+ receiver+ };+ wait_for_macos_completion(authorization).await?;++ let scheduled = {+ let center = UNUserNotificationCenter::currentNotificationCenter();+ let content = UNMutableNotificationContent::new();+ content.setTitle(&NSString::from_str(title));+ content.setBody(&NSString::from_str(body));+ content.setSound(Some(&UNNotificationSound::defaultSound()));+ let request = UNNotificationRequest::requestWithIdentifier_content_trigger(+ &NSString::from_str(notification_id),+ &content,+ None,+ );+ let (sender, receiver) = std::sync::mpsc::channel();+ let completion = RcBlock::new(move |error: *mut NSError| {+ let _ = sender.send(macos_add_result(!error.is_null()));+ });+ center.addNotificationRequest_withCompletionHandler(&request, Some(&completion));+ receiver+ };+ wait_for_macos_completion(scheduled).await+}++#[cfg(any(target_os = "macos", test))]+fn macos_authorization_result(granted: bool, has_error: bool) -> Result<(), ()> {+ if granted && !has_error {+ Ok(())+ } else {+ Err(())+ }+}++#[cfg(any(target_os = "macos", test))]+fn macos_add_result(has_error: bool) -> Result<(), ()> {+ if has_error {+ Err(())+ } else {+ Ok(())+ }+}++#[cfg(target_os = "macos")]+async fn wait_for_macos_completion(+ receiver: std::sync::mpsc::Receiver<Result<(), ()>>,+) -> Result<(), ()> {+ tauri::async_runtime::spawn_blocking(move || receiver.recv().unwrap_or(Err(())))+ .await+ .map_err(|_| ())?+}++#[cfg(target_os = "macos")]+fn install_macos_delegate(app: &AppHandle) {+ use block2::DynBlock;+ use objc2::rc::Retained;+ use objc2::runtime::ProtocolObject;+ use objc2::{define_class, msg_send, AnyThread, DefinedClass};+ use objc2_foundation::{NSObject, NSObjectProtocol};+ use objc2_user_notifications::{+ UNNotification, UNNotificationPresentationOptions, UNNotificationResponse,+ UNUserNotificationCenter, UNUserNotificationCenterDelegate,+ };++ struct DelegateIvars {+ app: AppHandle,+ }++ define_class!(+ #[unsafe(super = NSObject)]+ #[thread_kind = AnyThread]+ #[ivars = DelegateIvars]+ struct Delegate;++ unsafe impl NSObjectProtocol for Delegate {}++ unsafe impl UNUserNotificationCenterDelegate for Delegate {+ #[unsafe(method(userNotificationCenter:willPresentNotification:withCompletionHandler:))]+ fn will_present(+ &self,+ _center: &UNUserNotificationCenter,+ _notification: &UNNotification,+ completion: &DynBlock<dyn Fn(UNNotificationPresentationOptions)>,+ ) {+ completion.call((UNNotificationPresentationOptions::Banner+ | UNNotificationPresentationOptions::List+ | UNNotificationPresentationOptions::Sound,));+ }++ #[unsafe(method(userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:))]+ fn did_receive(+ &self,+ _center: &UNUserNotificationCenter,+ response: &UNNotificationResponse,+ completion: &DynBlock<dyn Fn()>,+ ) {+ let identifier = response.notification().request().identifier().to_string();+ activate(&self.ivars().app, &identifier);+ completion.call(());+ }+ }+ );++ impl Delegate {+ fn new(app: AppHandle) -> Retained<Self> {+ let this = Self::alloc().set_ivars(DelegateIvars { app });+ unsafe { msg_send![super(this), init] }+ }+ }++ let delegate = Delegate::new(app.clone());+ UNUserNotificationCenter::currentNotificationCenter()+ .setDelegate(Some(ProtocolObject::from_ref(&*delegate)));+ std::mem::forget(delegate);+}++#[cfg(windows)]+async fn display_notification(+ _app: &AppHandle,+ notification_id: &str,+ title: &str,+ body: &str,+) -> Result<(), ()> {+ use windows::core::HSTRING;+ use windows::Data::Xml::Dom::XmlDocument;+ use windows::UI::Notifications::{ToastNotification, ToastNotificationManager};++ let launch =+ format!("{ACTIVATION_SCHEME}://{ACTIVATION_HOST}{ACTIVATION_PATH}?id={notification_id}");+ let xml = format!(+ "<toast activationType=\"protocol\" launch=\"{}\"><visual><binding template=\"ToastGeneric\"><text>{}</text><text>{}</text></binding></visual><audio src=\"ms-winsoundevent:Notification.Default\"/></toast>",+ escape_xml(&launch),+ escape_xml(title),+ escape_xml(body),+ );+ let document = XmlDocument::new().map_err(|_| ())?;+ document.LoadXml(&HSTRING::from(xml)).map_err(|_| ())?;+ let toast = ToastNotification::CreateToastNotification(&document).map_err(|_| ())?;+ let notifier =+ ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from("ai.alook.desktop"))+ .map_err(|_| ())?;+ notifier.Show(&toast).map_err(|_| ())+}++#[cfg(windows)]+fn escape_xml(value: &str) -> String {+ value+ .replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+ .replace('"', """)+ .replace('\'', "'")+}++#[cfg(target_os = "linux")]+async fn display_notification(+ app: &AppHandle,+ _notification_id: &str,+ title: &str,+ body: &str,+) -> Result<(), ()> {+ let handle = notify_rust::Notification::new()+ .appname("Alook")+ .summary(title)+ .body(body)+ .action("default", "Open")+ .show()+ .map_err(|_| ())?;+ let app = app.clone();+ std::thread::spawn(move || {+ handle.wait_for_action(|action| {+ if action == "default" {+ crate::commands::show_main_window(&app);+ }+ });+ });+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn target(message_id: &str) -> NotificationTarget {+ NotificationTarget::Server {+ server_id: "server_1".into(),+ channel_id: "channel_1".into(),+ message_id: message_id.into(),+ seq: 1,+ }+ }++ fn candidate(viewer: &str, message: &str) -> NotificationCandidate {+ NotificationCandidate {+ viewer_user_id: viewer.into(),+ title: "Ada".into(),+ body: "Hello".into(),+ target: target(message),+ }+ }++ #[test]+ fn deterministic_ids_are_stable_scoped_and_uuid_shaped() {+ let first = deterministic_notification_id("viewer_1", "message_1");+ assert_eq!(+ first,+ deterministic_notification_id("viewer_1", "message_1")+ );+ assert_ne!(+ first,+ deterministic_notification_id("viewer_2", "message_1")+ );+ assert_ne!(+ first,+ deterministic_notification_id("viewer_1", "message_2")+ );+ assert!(valid_notification_id(&first));+ assert_eq!(&first[14..15], "5");+ }++ #[test]+ fn claim_deduplicates_and_bounds_persisted_history() {+ let mut record = NotificationRecord::new();+ let id = record.claim(&candidate("viewer_1", "message_1")).unwrap();+ assert!(record.claim(&candidate("viewer_1", "message_1")).is_none());+ assert!(record.claim(&candidate("viewer_2", "message_1")).is_some());+ record.rollback(&id);+ assert!(record.claim(&candidate("viewer_1", "message_1")).is_some());+ for index in 2..=300 {+ assert!(record+ .claim(&candidate("viewer_1", &format!("message_{index}")))+ .is_some());+ }+ assert_eq!(record.recent.len(), MAX_RECENT);+ assert_eq!(record.recent.last().unwrap().message_id, "message_300");+ }++ #[test]+ fn activation_is_one_shot_and_restorable() {+ let mut record = NotificationRecord::new();+ let id = record.claim(&candidate("viewer_1", "message_1")).unwrap();+ assert_eq!(record.activate(&id).unwrap().target, target("message_1"));+ assert!(record.activate(&id).is_none());+ let restored = NotificationRecord::restore(serde_json::to_value(record).unwrap()).unwrap();+ assert!(restored.recent[0].activated);+ }++ #[test]+ fn restore_rejects_unknown_or_malformed_state() {+ assert!(NotificationRecord::restore(serde_json::json!({+ "version": 1,+ "recent": [],+ "extra": true+ }))+ .is_err());+ assert!(NotificationRecord::restore(serde_json::json!({+ "version": 2,+ "recent": []+ }))+ .is_err());+ }++ #[test]+ fn activation_url_parser_is_exact() {+ let id = deterministic_notification_id("viewer_1", "message_1");+ let valid = url::Url::parse(&format!(+ "{ACTIVATION_SCHEME}://{ACTIVATION_HOST}{ACTIVATION_PATH}?id={id}"+ ))+ .unwrap();+ assert_eq!(activation_id_from_url(&valid), Some(id.clone()));+ for raw in [+ format!("https://notification/open?id={id}"),+ format!("{ACTIVATION_SCHEME}://evil/open?id={id}"),+ format!("{ACTIVATION_SCHEME}://{ACTIVATION_HOST}/elsewhere?id={id}"),+ format!("{ACTIVATION_SCHEME}://{ACTIVATION_HOST}{ACTIVATION_PATH}?id={id}&next=https://evil.test"),+ ] {+ assert!(activation_id_from_url(&url::Url::parse(&raw).unwrap()).is_none());+ }+ }++ #[test]+ fn macos_completion_results_fail_closed_before_rollback() {+ assert_eq!(macos_authorization_result(true, false), Ok(()));+ assert_eq!(macos_authorization_result(false, false), Err(()));+ assert_eq!(macos_authorization_result(true, true), Err(()));+ assert_eq!(macos_add_result(false), Ok(()));+ assert_eq!(macos_add_result(true), Err(()));++ let mut record = NotificationRecord::new();+ let original = candidate("viewer_1", "message_1");+ let id = record.claim(&original).unwrap();+ assert!(macos_add_result(true).is_err());+ record.rollback(&id);+ assert_eq!(record.claim(&original), Some(id));+ }+}diff --git a/src/desktop/src-tauri/tauri.conf.json b/src/desktop/src-tauri/tauri.conf.jsonindex dd7cb9aaa..a7d6d2a2d 100644--- a/src/desktop/src-tauri/tauri.conf.json+++ b/src/desktop/src-tauri/tauri.conf.json@@ -49,7 +49,8 @@"external-links","native-oauth","native-oauth-mobile",- "mobile-share-image-mobile"+ "mobile-share-image-mobile",+ "mobile-system-notification-mobile"]}},diff --git a/src/desktop/src-tauri/tauri.dev.conf.json b/src/desktop/src-tauri/tauri.dev.conf.jsonindex 1c6fd2074..c4981ea15 100644--- a/src/desktop/src-tauri/tauri.dev.conf.json+++ b/src/desktop/src-tauri/tauri.dev.conf.json@@ -50,6 +50,27 @@"allow-mobile-share-image-copy","allow-mobile-share-image-save"]+ },+ {+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "mobile-system-notification-dev",+ "description": "Native mobile system notification orchestration for the trusted development WebView",+ "windows": [+ "main"+ ],+ "platforms": [+ "android",+ "iOS"+ ],+ "local": true,+ "remote": {+ "urls": [+ "http://localhost:3000"+ ]+ },+ "permissions": [+ "mobile-system-notification"+ ]}]}diff --git a/src/wake-worker/.deploy-version b/src/queue-worker/.deploy-versionsimilarity index 100%rename from src/wake-worker/.deploy-versionrename to src/queue-worker/.deploy-versiondiff --git a/src/queue-worker/.dev.vars.example b/src/queue-worker/.dev.vars.examplenew file mode 100644index 000000000..bf56ea584--- /dev/null+++ b/src/queue-worker/.dev.vars.example@@ -0,0 +1,13 @@+# Shared with Web so encrypted device tokens can be decrypted by this worker.+ENCRYPTION_KEY=++# Apple Push Notification service token credentials and app topic.+APNS_TEAM_ID=+APNS_KEY_ID=+APNS_PRIVATE_KEY=+APNS_TOPIC=++# Firebase Cloud Messaging HTTP v1 service-account credentials.+FCM_PROJECT_ID=+FCM_CLIENT_EMAIL=+FCM_PRIVATE_KEY=diff --git a/src/queue-worker/MIGRATION.md b/src/queue-worker/MIGRATION.mdnew file mode 100644index 000000000..a1049a89a--- /dev/null+++ b/src/queue-worker/MIGRATION.md@@ -0,0 +1,25 @@+# Queue resource migration runbook++This runbook moves the existing wake-only resources to the generic queue names. It is deliberately a create/cutover/drain migration: Cloudflare Queue names cannot be changed in place.++The companion `scripts/cloudflare/queue-migration.mjs` only prints the plan. It never invokes Wrangler and rejects `--execute`. Do not run any mutating command below without its own production authorization.++## Invariants++- New code accepts legacy `{ messageId, botUserId }` wake payloads plus both v1 task kinds.+- Web has exactly one queue producer binding. Never dual-write old and new queues.+- Keep `alook-wake-worker` consuming `alook-wake` throughout the drain.+- Do not delete a legacy resource until its depth and oldest-message age remain zero, no old producer exists, and new wake traffic is healthy.+- Creating resources, deploying code, configuring real provider secrets, and deleting resources are separate production actions.++## Authorized sequence++1. Prepare: create `alook-queue` and `alook-queue-dlq`. Confirm neither has a producer.+2. Compatible consumer: deploy `alook-queue-worker`, bound to the new Queue/DLQ, the existing D1 database, and the WS service. Set the same `ENCRYPTION_KEY` used by Web; configure APNs/FCM values separately. Verify legacy wake, v1 bot-wake, and v1 mobile-push parsing with non-production fixtures only.+3. Producer cutover: deploy Web with `TASK_QUEUE` targeting only `alook-queue` and `QUEUE_WORKER` targeting `alook-queue-worker`. Confirm the old producer binding is absent.+4. Drain and observe: use read-only queue metrics to verify `alook-wake` depth and oldest age reach zero. Confirm no old producer remains, bot wakes traverse the new chain, caught mobile-push failures are ACKed, and the new DLQ is observed.+5. Cleanup: stop. Obtain separate exact authorization, then delete `alook-wake`, `alook-wake-dlq`, and `alook-wake-worker` only. Re-run read-only checks after deletion.++## Rollback boundary++Before cleanup, roll back by returning the single Web producer binding to `alook-wake`; do not send to both queues. After cleanup, rollback requires recreating the legacy resources and therefore needs a new production plan and authorization.diff --git a/src/wake-worker/knip.json b/src/queue-worker/knip.jsonsimilarity index 100%rename from src/wake-worker/knip.jsonrename to src/queue-worker/knip.jsondiff --git a/src/wake-worker/package.json b/src/queue-worker/package.jsonsimilarity index 95%rename from src/wake-worker/package.jsonrename to src/queue-worker/package.jsonindex 15206de06..29605e06c 100644--- a/src/wake-worker/package.json+++ b/src/queue-worker/package.json@@ -1,5 +1,5 @@{- "name": "@alook/wake-worker",+ "name": "@alook/queue-worker","version": "0.1.36","private": true,"scripts": {diff --git a/src/queue-worker/src/env.d.ts b/src/queue-worker/src/env.d.tsnew file mode 100644index 000000000..58cdc15e4--- /dev/null+++ b/src/queue-worker/src/env.d.ts@@ -0,0 +1,15403 @@+/* eslint-disable */+// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example src/env.d.ts` (hash: e972cdaeeabdfd9fec81a85171f3b3db)+// Runtime types generated with [email protected] 2026-09-07 nodejs_compat+interface __BaseEnv_Env {+ DB: D1Database;+ ENCRYPTION_KEY: string;+ APNS_TEAM_ID: string;+ APNS_KEY_ID: string;+ APNS_PRIVATE_KEY: string;+ APNS_TOPIC: string;+ FCM_PROJECT_ID: string;+ FCM_CLIENT_EMAIL: string;+ FCM_PRIVATE_KEY: string;+ WS_DO_WORKER: Fetcher /* alook-ws-do */;+}+declare namespace Cloudflare {+ interface GlobalProps {+ mainModule: typeof import("./index");+ }+ interface Env extends __BaseEnv_Env {}+}+interface Env extends __BaseEnv_Env {}+type StringifyValues<EnvType extends Record<string, unknown>> = {+ [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;+};+declare namespace NodeJS {+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "ENCRYPTION_KEY" | "APNS_TEAM_ID" | "APNS_KEY_ID" | "APNS_PRIVATE_KEY" | "APNS_TOPIC" | "FCM_PROJECT_ID" | "FCM_CLIENT_EMAIL" | "FCM_PRIVATE_KEY">> {}+}++// Begin runtime types+/*! *****************************************************************************+Copyright (c) Cloudflare. All rights reserved.+Copyright (c) Microsoft Corporation. All rights reserved.++Licensed under the Apache License, Version 2.0 (the "License"); you may not use+this file except in compliance with the License. You may obtain a copy of the+License at http://www.apache.org/licenses/LICENSE-2.0+THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED+WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,+MERCHANTABLITY OR NON-INFRINGEMENT.+See the Apache Version 2.0 License for specific language governing permissions+and limitations under the License.+***************************************************************************** */+/* eslint-disable */+// noinspection JSUnusedGlobalSymbols+declare var onmessage: never;+/**+ * The **`DOMException`** interface represents an abnormal event (called an exception) that occurs as a result of calling a method or accessing a property of a web API. This is how error conditions are described in web APIs.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)+ */+declare class DOMException extends Error {+ constructor(message?: string, name?: string);+ /**+ * The **`message`** read-only property of the DOMException interface returns a string representing a message or description associated with the given error name.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message)+ */+ readonly message: string;+ /**+ * The **`name`** read-only property of the DOMException interface returns a string that contains one of the strings associated with an error name.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name)+ */+ readonly name: string;+ /**+ * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or 0 if none match.+ * @deprecated+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)+ */+ readonly code: number;+ static readonly INDEX_SIZE_ERR: number;+ static readonly DOMSTRING_SIZE_ERR: number;+ static readonly HIERARCHY_REQUEST_ERR: number;+ static readonly WRONG_DOCUMENT_ERR: number;+ static readonly INVALID_CHARACTER_ERR: number;+ static readonly NO_DATA_ALLOWED_ERR: number;+ static readonly NO_MODIFICATION_ALLOWED_ERR: number;+ static readonly NOT_FOUND_ERR: number;+ static readonly NOT_SUPPORTED_ERR: number;+ static readonly INUSE_ATTRIBUTE_ERR: number;+ static readonly INVALID_STATE_ERR: number;+ static readonly SYNTAX_ERR: number;+ static readonly INVALID_MODIFICATION_ERR: number;+ static readonly NAMESPACE_ERR: number;+ static readonly INVALID_ACCESS_ERR: number;+ static readonly VALIDATION_ERR: number;+ static readonly TYPE_MISMATCH_ERR: number;+ static readonly SECURITY_ERR: number;+ static readonly NETWORK_ERR: number;+ static readonly ABORT_ERR: number;+ static readonly URL_MISMATCH_ERR: number;+ static readonly QUOTA_EXCEEDED_ERR: number;+ static readonly TIMEOUT_ERR: number;+ static readonly INVALID_NODE_TYPE_ERR: number;+ static readonly DATA_CLONE_ERR: number;+ get stack(): any;+ set stack(value: any);+}+type WorkerGlobalScopeEventMap = {+ fetch: FetchEvent;+ scheduled: ScheduledEvent;+ queue: QueueEvent;+ unhandledrejection: PromiseRejectionEvent;+ rejectionhandled: PromiseRejectionEvent;+};+declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> {+ EventTarget: typeof EventTarget;+}+/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). *+ * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console)+ */+interface Console {+ "assert"(condition?: boolean, ...data: any[]): void;+ /**+ * The **`console.clear()`** static method clears the console if possible.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static)+ */+ clear(): void;+ /**+ * The **`console.count()`** static method logs the number of times that this particular call to count() has been called.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static)+ */+ count(label?: string): void;+ /**+ * The **`console.countReset()`** static method resets counter used with console.count().+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static)+ */+ countReset(label?: string): void;+ /**+ * The **`console.debug()`** static method outputs a message to the console at the "debug" log level. The message is only displayed to the user if the console is configured to display debug output. In most cases, the log level is configured within the console UI. This log level might correspond to the Debug or Verbose log level.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static)+ */+ debug(...data: any[]): void;+ /**+ * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. In browser consoles, the output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static)+ */+ dir(item?: any, options?: any): void;+ /**+ * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. If it is not possible to display as an element the JavaScript Object view is shown instead. The output is presented as a hierarchical listing of expandable nodes that let you see the contents of child nodes.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static)+ */+ dirxml(...data: any[]): void;+ /**+ * The **`console.error()`** static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)+ */+ error(...data: any[]): void;+ /**+ * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console.groupEnd() is called.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static)+ */+ group(...data: any[]): void;+ /**+ * The **`console.groupCollapsed()`** static method creates a new inline group in the console. Unlike console.group(), however, the new group is created collapsed. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static)+ */+ groupCollapsed(...data: any[]): void;+ /**+ * The **`console.groupEnd()`** static method exits the current inline group in the console. See Using groups in the console in the console documentation for details and examples.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static)+ */+ groupEnd(): void;+ /**+ * The **`console.info()`** static method outputs a message to the console at the "info" log level. The message is only displayed to the user if the console is configured to display info output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as a small "i" icon next to it.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static)+ */+ info(...data: any[]): void;+ /**+ * The **`console.log()`** static method outputs a message to the console.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)+ */+ log(...data: any[]): void;+ /**+ * The **`console.table()`** static method displays tabular data as a table.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static)+ */+ table(tabularData?: any, properties?: string[]): void;+ /**+ * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static)+ */+ time(label?: string): void;+ /**+ * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console.time().+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static)+ */+ timeEnd(label?: string): void;+ /**+ * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console.time().+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static)+ */+ timeLog(label?: string, ...data: any[]): void;+ /* The **`console.timeStamp()`** static method adds a single marker to the browser's Performance tool (Firefox bug 1387528, Chrome). This lets you correlate a point in your code with the other events recorded in the timeline, such as layout and paint events. */+ timeStamp(label?: string): void;+ /**+ * The **`console.trace()`** static method outputs a stack trace to the console.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static)+ */+ trace(...data: any[]): void;+ /**+ * The **`console.warn()`** static method outputs a warning message to the console at the "warning" log level. The message is only displayed to the user if the console is configured to display warning output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as yellow colors and a warning icon.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static)+ */+ warn(...data: any[]): void;+}+declare const console: Console;+type BufferSource = ArrayBufferView | ArrayBuffer;+type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;+declare namespace WebAssembly {+ class CompileError extends Error {+ constructor(message?: string);+ }+ class RuntimeError extends Error {+ constructor(message?: string);+ }+ type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128";+ interface GlobalDescriptor {+ value: ValueType;+ mutable?: boolean;+ }+ class Global {+ constructor(descriptor: GlobalDescriptor, value?: any);+ value: any;+ valueOf(): any;+ }+ type ImportValue = ExportValue | number;+ type ModuleImports = Record<string, ImportValue>;+ type Imports = Record<string, ModuleImports>;+ type ExportValue = Function | Global | Memory | Table;+ type Exports = Record<string, ExportValue>;+ class Instance {+ constructor(module: Module, imports?: Imports);+ readonly exports: Exports;+ }+ interface MemoryDescriptor {+ initial: number;+ maximum?: number;+ shared?: boolean;+ }+ class Memory {+ constructor(descriptor: MemoryDescriptor);+ readonly buffer: ArrayBuffer;+ grow(delta: number): number;+ }+ type ImportExportKind = "function" | "global" | "memory" | "table";+ interface ModuleExportDescriptor {+ kind: ImportExportKind;+ name: string;+ }+ interface ModuleImportDescriptor {+ kind: ImportExportKind;+ module: string;+ name: string;+ }+ abstract class Module {+ static customSections(module: Module, sectionName: string): ArrayBuffer[];+ static exports(module: Module): ModuleExportDescriptor[];+ static imports(module: Module): ModuleImportDescriptor[];+ }+ type TableKind = "anyfunc" | "externref";+ interface TableDescriptor {+ element: TableKind;+ initial: number;+ maximum?: number;+ }+ class Table {+ constructor(descriptor: TableDescriptor, value?: any);+ readonly length: number;+ get(index: number): any;+ grow(delta: number, value?: any): number;+ set(index: number, value?: any): void;+ }+ function instantiate(module: Module, imports?: Imports): Promise<Instance>;+ function validate(bytes: BufferSource): boolean;+}+/**+ * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker.+ * Available only in secure contexts.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope)+ */+interface ServiceWorkerGlobalScope extends WorkerGlobalScope {+ DOMException: typeof DOMException;+ WorkerGlobalScope: typeof WorkerGlobalScope;+ btoa(data: string): string;+ atob(data: string): string;+ setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;+ setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;+ clearTimeout(timeoutId: number | null): void;+ setInterval(callback: (...args: any[]) => void, msDelay?: number): number;+ setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;+ clearInterval(timeoutId: number | null): void;+ queueMicrotask(task: Function): void;+ structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;+ reportError(error: any): void;+ fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;+ self: ServiceWorkerGlobalScope;+ crypto: Crypto;+ caches: CacheStorage;+ scheduler: Scheduler;+ performance: Performance;+ Cloudflare: Cloudflare;+ readonly origin: string;+ Event: typeof Event;+ ExtendableEvent: typeof ExtendableEvent;+ CustomEvent: typeof CustomEvent;+ PromiseRejectionEvent: typeof PromiseRejectionEvent;+ FetchEvent: typeof FetchEvent;+ TailEvent: typeof TailEvent;+ TraceEvent: typeof TailEvent;+ ScheduledEvent: typeof ScheduledEvent;+ MessageEvent: typeof MessageEvent;+ CloseEvent: typeof CloseEvent;+ ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader;+ ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader;+ ReadableStream: typeof ReadableStream;+ WritableStream: typeof WritableStream;+ WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter;+ TransformStream: typeof TransformStream;+ ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy;+ CountQueuingStrategy: typeof CountQueuingStrategy;+ ErrorEvent: typeof ErrorEvent;+ MessageChannel: typeof MessageChannel;+ MessagePort: typeof MessagePort;+ EventSource: typeof EventSource;+ ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest;+ ReadableStreamDefaultController: typeof ReadableStreamDefaultController;+ ReadableByteStreamController: typeof ReadableByteStreamController;+ WritableStreamDefaultController: typeof WritableStreamDefaultController;+ TransformStreamDefaultController: typeof TransformStreamDefaultController;+ CompressionStream: typeof CompressionStream;+ DecompressionStream: typeof DecompressionStream;+ TextEncoderStream: typeof TextEncoderStream;+ TextDecoderStream: typeof TextDecoderStream;+ Headers: typeof Headers;+ Body: typeof Body;+ Request: typeof Request;+ Response: typeof Response;+ WebSocket: typeof WebSocket;+ WebSocketPair: typeof WebSocketPair;+ WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair;+ AbortController: typeof AbortController;+ AbortSignal: typeof AbortSignal;+ TextDecoder: typeof TextDecoder;+ TextEncoder: typeof TextEncoder;+ navigator: Navigator;+ Navigator: typeof Navigator;+ URL: typeof URL;+ URLSearchParams: typeof URLSearchParams;+ URLPattern: typeof URLPattern;+ Blob: typeof Blob;+ File: typeof File;+ FormData: typeof FormData;+ Crypto: typeof Crypto;+ SubtleCrypto: typeof SubtleCrypto;+ CryptoKey: typeof CryptoKey;+ CacheStorage: typeof CacheStorage;+ Cache: typeof Cache;+ FixedLengthStream: typeof FixedLengthStream;+ IdentityTransformStream: typeof IdentityTransformStream;+ HTMLRewriter: typeof HTMLRewriter;+}+declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;+declare function removeEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;+/**+ * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)+ */+declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */+declare function btoa(data: string): string;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */+declare function atob(data: string): string;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */+declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */+declare function setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */+declare function clearTimeout(timeoutId: number | null): void;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */+declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */+declare function setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */+declare function clearInterval(timeoutId: number | null): void;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */+declare function queueMicrotask(task: Function): void;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */+declare function structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */+declare function reportError(error: any): void;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */+declare function fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;+declare const self: ServiceWorkerGlobalScope;+/**+* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.+* The Workers runtime implements the full surface of this API, but with some differences in+* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)+* compared to those implemented in most browsers.+*+* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)+*/+declare const crypto: Crypto;+/**+* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.+*+* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)+*/+declare const caches: CacheStorage;+/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scheduler) */+declare const scheduler: Scheduler;+/**+* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,+* as well as timing of subrequests and other operations.+*+* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)+*/+declare const performance: Performance;+declare const Cloudflare: Cloudflare;+declare const origin: string;+declare const navigator: Navigator;+interface TestController {+}+interface ExecutionContext<Props = unknown> {+ waitUntil(promise: Promise<any>): void;+ passThroughOnException(): void;+ readonly exports: Cloudflare.Exports;+ readonly props: Props;+ cache?: CacheContext;+ readonly access?: CloudflareAccessContext;+ tracing: Tracing;+ abort(reason?: any): void;+}+type ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown, Props = unknown> = (request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, env: Env, ctx: ExecutionContext<Props>) => Response | Promise<Response>;+type ExportedHandlerConnectHandler<Env = unknown, Props = unknown> = (socket: Socket, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;+type ExportedHandlerTailHandler<Env = unknown, Props = unknown> = (events: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;+type ExportedHandlerTraceHandler<Env = unknown, Props = unknown> = (traces: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;+type ExportedHandlerTailStreamHandler<Env = unknown, Props = unknown> = (event: TailStream.TailEvent<TailStream.Onset>, env: Env, ctx: ExecutionContext<Props>) => TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;+type ExportedHandlerScheduledHandler<Env = unknown, Props = unknown> = (controller: ScheduledController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;+type ExportedHandlerQueueHandler<Env = unknown, Message = unknown, Props = unknown> = (batch: MessageBatch<Message>, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;+type ExportedHandlerTestHandler<Env = unknown, Props = unknown> = (controller: TestController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;+interface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown, Props = unknown> {+ fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata, Props>;+ connect?: ExportedHandlerConnectHandler<Env, Props>;+ tail?: ExportedHandlerTailHandler<Env, Props>;+ trace?: ExportedHandlerTraceHandler<Env, Props>;+ tailStream?: ExportedHandlerTailStreamHandler<Env, Props>;+ scheduled?: ExportedHandlerScheduledHandler<Env, Props>;+ test?: ExportedHandlerTestHandler<Env, Props>;+ email?: EmailExportedHandler<Env, Props>;+ queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage, Props>;+}+interface StructuredSerializeOptions {+ transfer?: any[];+}+declare abstract class Navigator {+ sendBeacon(url: string, body?: BodyInit): boolean;+ readonly userAgent: string;+ readonly hardwareConcurrency: number;+ readonly platform: string;+ readonly language: string;+ readonly languages: string[];+}+interface AlarmInvocationInfo {+ readonly isRetry: boolean;+ readonly retryCount: number;+ readonly scheduledTime: number;+}+interface Cloudflare {+ readonly compatibilityFlags: Record<string, boolean>;+}+interface CachePurgeError {+ code: number;+ message: string;+}+interface CachePurgeResult {+ success: boolean;+ errors: CachePurgeError[];+}+interface CachePurgeOptions {+ tags?: string[];+ pathPrefixes?: string[];+ purgeEverything?: boolean;+}+interface CacheContext {+ purge(options: CachePurgeOptions): Promise<CachePurgeResult>;+}+interface CloudflareAccessContext {+ readonly aud: string;+ getIdentity(): Promise<CloudflareAccessIdentity | undefined>;+}+declare abstract class ColoLocalActorNamespace {+ get(actorId: string): Fetcher;+}+interface DurableObject {+ fetch(request: Request): Response | Promise<Response>;+ connect?(socket: Socket): void | Promise<void>;+ alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;+ webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;+ webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;+ webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;+}+type DurableObjectStub<T extends Rpc.DurableObjectBranded | undefined = undefined> = Fetcher<T, "alarm" | "connect" | "webSocketMessage" | "webSocketClose" | "webSocketError"> & {+ readonly id: DurableObjectId;+ readonly name?: string;+};+interface DurableObjectId {+ toString(): string;+ equals(other: DurableObjectId): boolean;+ readonly name?: string;+ readonly jurisdiction?: string;+}+declare abstract class DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined> {+ newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId;+ idFromName(name: string): DurableObjectId;+ idFromString(id: string): DurableObjectId;+ get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;+ getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;+ jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace<T>;+}+type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us";+interface DurableObjectNamespaceNewUniqueIdOptions {+ jurisdiction?: DurableObjectJurisdiction;+}+type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "apac-ne" | "apac-se" | "oc" | "afr" | "me";+type DurableObjectRoutingMode = "primary-only";+interface DurableObjectNamespaceGetDurableObjectOptions {+ locationHint?: DurableObjectLocationHint;+ routingMode?: DurableObjectRoutingMode;+}+interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> {+}+interface DurableObjectState<Props = unknown> {+ waitUntil(promise: Promise<any>): void;+ readonly exports: Cloudflare.Exports;+ readonly props: Props;+ readonly id: DurableObjectId;+ readonly storage: DurableObjectStorage;+ container?: Container;+ facets: DurableObjectFacets;+ blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;+ acceptWebSocket(ws: WebSocket, tags?: string[]): void;+ getWebSockets(tag?: string): WebSocket[];+ setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void;+ getWebSocketAutoResponse(): WebSocketRequestResponsePair | null;+ getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null;+ setHibernatableWebSocketEventTimeout(timeoutMs?: number): void;+ getHibernatableWebSocketEventTimeout(): number | null;+ getTags(ws: WebSocket): string[];+ abort(reason?: string, options?: DurableObjectAbortOptions): void;+}+interface DurableObjectTransaction {+ get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;+ get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;+ list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;+ put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;+ put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;+ delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;+ delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;+ rollback(): void;+ getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;+ setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;+ deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;+}+interface DurableObjectStorage {+ get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;+ get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;+ list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;+ put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;+ put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;+ delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;+ delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;+ deleteAll(options?: DurableObjectPutOptions): Promise<void>;+ transaction<T>(closure: (txn: DurableObjectTransaction) => Promise<T>): Promise<T>;+ getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;+ setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;+ deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;+ sync(): Promise<void>;+ sql: SqlStorage;+ kv: SyncKvStorage;+ transactionSync<T>(closure: () => T): T;+ getCurrentBookmark(): Promise<string>;+ getBookmarkForTime(timestamp: number | Date): Promise<string>;+ onNextSessionRestoreBookmark(bookmark: string): Promise<string>;+}+interface DurableObjectAbortOptions {+ retryAlarm?: boolean;+}+interface DurableObjectListOptions {+ start?: string;+ startAfter?: string;+ end?: string;+ prefix?: string;+ reverse?: boolean;+ limit?: number;+ allowConcurrency?: boolean;+ noCache?: boolean;+}+interface DurableObjectGetOptions {+ allowConcurrency?: boolean;+ noCache?: boolean;+}+interface DurableObjectGetAlarmOptions {+ allowConcurrency?: boolean;+}+interface DurableObjectPutOptions {+ allowConcurrency?: boolean;+ allowUnconfirmed?: boolean;+ noCache?: boolean;+}+interface DurableObjectSetAlarmOptions {+ allowConcurrency?: boolean;+ allowUnconfirmed?: boolean;+}+declare class WebSocketRequestResponsePair {+ constructor(request: string, response: string);+ get request(): string;+ get response(): string;+}+interface DurableObjectFacets {+ get<T extends Rpc.DurableObjectBranded | undefined = undefined>(name: string, getStartupOptions: () => FacetStartupOptions<T> | Promise<FacetStartupOptions<T>>): Fetcher<T>;+ abort(name: string, reason: any): void;+ delete(name: string): void;+ clone(src: string, dst: string): void;+}+interface FacetStartupOptions<T extends Rpc.DurableObjectBranded | undefined = undefined> {+ id?: DurableObjectId | string;+ class: DurableObjectClass<T>;+}+interface AnalyticsEngineDataset {+ writeDataPoint(event?: AnalyticsEngineDataPoint): void;+}+interface AnalyticsEngineDataPoint {+ indexes?: ((ArrayBuffer | string) | null)[];+ doubles?: number[];+ blobs?: ((ArrayBuffer | string) | null)[];+}+/**+ * The **`Event`** interface represents an event which takes place on an EventTarget.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event)+ */+declare class Event {+ constructor(type: string, init?: EventInit);+ /**+ * The **`type`** read-only property of the Event interface returns a string containing the event's type. It is set when the event is constructed and is the name commonly used to refer to the specific event, such as click, load, or error.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type)+ */+ get type(): string;+ /**+ * The **`eventPhase`** read-only property of the Event interface indicates which phase of the event flow is currently being evaluated.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase)+ */+ get eventPhase(): number;+ /**+ * The read-only **`composed`** property of the Event interface returns a boolean value which indicates whether or not the event will propagate across the shadow DOM boundary into the standard DOM.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed)+ */+ get composed(): boolean;+ /**+ * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles)+ */+ get bubbles(): boolean;+ /**+ * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable)+ */+ get cancelable(): boolean;+ /**+ * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented)+ */+ get defaultPrevented(): boolean;+ /**+ * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not.+ * @deprecated+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue)+ */+ get returnValue(): boolean;+ /**+ * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget)+ */+ get currentTarget(): EventTarget | undefined;+ /**+ * The read-only **`target`** property of the Event interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)+ */+ get target(): EventTarget | undefined;+ /**+ * The deprecated **`Event.srcElement`** is an alias for the Event.target property. Use Event.target instead.+ * @deprecated+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement)+ */+ get srcElement(): EventTarget | undefined;+ /**+ * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp)+ */+ get timeStamp(): number;+ /**+ * The **`isTrusted`** read-only property of the Event interface is a boolean value that is true when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and false when the event was dispatched via EventTarget.dispatchEvent(). The only exception is the click event, which initializes the isTrusted property to false in user agents.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted)+ */+ get isTrusted(): boolean;+ /**+ * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details.+ * @deprecated+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)+ */+ get cancelBubble(): boolean;+ /**+ * The **`cancelBubble`** property of the Event interface is deprecated. Use Event.stopPropagation() instead. Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details.+ * @deprecated+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)+ */+ set cancelBubble(value: boolean);+ /**+ * The **`stopImmediatePropagation()`** method of the Event interface prevents other listeners of the same event from being called.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation)+ */+ stopImmediatePropagation(): void;+ /**+ * The **`preventDefault()`** method of the Event interface tells the user agent that the event is being explicitly handled, so its default action, such as page scrolling, link navigation, or pasting text, should not be taken.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)+ */+ preventDefault(): void;+ /**+ * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method. It also does not prevent propagation to other event-handlers of the current element. If you want to stop those, see stopImmediatePropagation().+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation)+ */+ stopPropagation(): void;+ /**+ * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. This does not include nodes in shadow trees if the shadow root was created with its ShadowRoot.mode closed.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath)+ */+ composedPath(): EventTarget[];+ static readonly NONE: number;+ static readonly CAPTURING_PHASE: number;+ static readonly AT_TARGET: number;+ static readonly BUBBLING_PHASE: number;+}+interface EventInit {+ bubbles?: boolean;+ cancelable?: boolean;+ composed?: boolean;+}+type EventListener<EventType extends Event = Event> = (event: EventType) => void;+interface EventListenerObject<EventType extends Event = Event> {+ handleEvent(event: EventType): void;+}+type EventListenerOrEventListenerObject<EventType extends Event = Event> = EventListener<EventType> | EventListenerObject<EventType>;+/**+ * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget)+ */+declare class EventTarget<EventMap extends Record<string, Event> = Record<string, Event>> {+ constructor();+ /**+ * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)+ */+ addEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;+ /**+ * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener)+ */+ removeEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;+ /**+ * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)+ */+ dispatchEvent(event: EventMap[keyof EventMap]): boolean;+}+interface EventTargetEventListenerOptions {+ capture?: boolean;+}+interface EventTargetAddEventListenerOptions {+ capture?: boolean;+ passive?: boolean;+ once?: boolean;+ signal?: AbortSignal;+}+interface EventTargetHandlerObject {+ handleEvent: (event: Event) => any | undefined;+}+/**+ * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController)+ */+declare class AbortController {+ constructor();+ /**+ * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal)+ */+ get signal(): AbortSignal;+ /**+ * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. This is able to abort fetch requests, the consumption of any response bodies, or streams.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort)+ */+ abort(reason?: any): void;+}+/**+ * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal)+ */+declare abstract class AbortSignal extends EventTarget {+ /**+ * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an abort event).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static)+ */+ static abort(reason?: any): AbortSignal;+ /**+ * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static)+ */+ static timeout(delay: number): AbortSignal;+ /**+ * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. The returned abort signal is aborted when any of the input iterable abort signals are aborted. The abort reason will be set to the reason of the first signal that is aborted. If any of the given abort signals are already aborted then so will be the returned AbortSignal.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static)+ */+ static any(signals: AbortSignal[]): AbortSignal;+ /**+ * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (true) or not (false).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted)+ */+ get aborted(): boolean;+ /**+ * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason)+ */+ get reason(): any;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */+ get onabort(): any | null;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */+ set onabort(value: any | null);+ /**+ * The **`throwIfAborted()`** method throws the signal's abort reason if the signal has been aborted; otherwise it does nothing.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted)+ */+ throwIfAborted(): void;+}+/**+ * The **`Scheduler`** interface of the Prioritized Task Scheduling API provides methods for scheduling prioritized tasks.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Scheduler)+ */+interface Scheduler {+ wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>;+}+interface SchedulerWaitOptions {+ signal?: AbortSignal;+}+/**+ * The **`ExtendableEvent`** interface extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent)+ */+declare abstract class ExtendableEvent extends Event {+ /**+ * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. It can also be used to detect whether that work was successful. In service workers, waitUntil() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil)+ */+ waitUntil(promise: Promise<any>): void;+}+/**+ * The **`CustomEvent`** interface can be used to attach custom data to an event generated by an application.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent)+ */+declare class CustomEvent<T = any> extends Event {+ constructor(type: string, init?: CustomEventCustomEventInit);+ /**+ * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail)+ */+ get detail(): T;+}+interface CustomEventCustomEventInit {+ bubbles?: boolean;+ cancelable?: boolean;+ composed?: boolean;+ detail?: any;+}+/**+ * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob)+ */+declare class Blob {+ constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions);+ /**+ * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size)+ */+ get size(): number;+ /**+ * The **`type`** read-only property of the Blob interface returns the MIME type of the file.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type)+ */+ get type(): string;+ /**+ * The **`slice()`** method of the Blob interface creates and returns a new Blob object which contains data from a subset of the blob on which it's called.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice)+ */+ slice(start?: number, end?: number, type?: string): Blob;+ /**+ * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer)+ */+ arrayBuffer(): Promise<ArrayBuffer>;+ /**+ * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes)+ */+ bytes(): Promise<Uint8Array>;+ /**+ * The **`text()`** method of the Blob interface returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text)+ */+ text(): Promise<string>;+ /**+ * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream)+ */+ stream(): ReadableStream;+}+interface BlobOptions {+ type?: string;+}+/**+ * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File)+ */+declare class File extends Blob {+ constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions);+ /**+ * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)+ */+ get name(): string;+ /**+ * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified)+ */+ get lastModified(): number;+}+interface FileOptions {+ type?: string;+ lastModified?: number;+}+/**+* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.+*+* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)+*/+declare abstract class CacheStorage {+ /**+ * The **`open()`** method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open)+ */+ open(cacheName: string): Promise<Cache>;+ readonly default: Cache;+}+/**+* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.+*+* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)+*/+declare abstract class Cache {+ /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */+ delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;+ /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */+ match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;+ /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */+ put(request: RequestInfo | URL, response: Response): Promise<void>;+}+interface CacheQueryOptions {+ ignoreMethod?: boolean;+}+/**+* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.+* The Workers runtime implements the full surface of this API, but with some differences in+* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)+* compared to those implemented in most browsers.+*+* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)+*/+declare abstract class Crypto {+ /**+ * The **`Crypto.subtle`** read-only property returns a SubtleCrypto which can then be used to perform low-level cryptographic operations.+ * Available only in secure contexts.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle)+ */+ get subtle(): SubtleCrypto;+ /**+ * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. The array given as the parameter is filled with random numbers (random in its cryptographic meaning).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues)+ */+ getRandomValues<T extends Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array>(buffer: T): T;+ /**+ * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.+ * Available only in secure contexts.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID)+ */+ randomUUID(): string;+ DigestStream: typeof DigestStream;+}+/**+ * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions.+ * Available only in secure contexts.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto)+ */+declare abstract class SubtleCrypto {+ /**+ * The **`encrypt()`** method of the SubtleCrypto interface encrypts data.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt)+ */+ encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;+ /**+ * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. It takes as arguments a key to decrypt with, some optional extra parameters, and the data to decrypt (also known as "ciphertext"). It returns a Promise which will be fulfilled with the decrypted data (also known as "plaintext").+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt)+ */+ decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;+ /**+ * The **`sign()`** method of the SubtleCrypto interface generates a digital signature.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign)+ */+ sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;+ /**+ * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify)+ */+ verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise<boolean>;+ /**+ * The **`digest()`** method of the SubtleCrypto interface generates a digest of the given data, using the specified hash function. A digest is a short fixed-length value derived from some variable-length input. Cryptographic digests should exhibit collision-resistance, meaning that it's hard to come up with two different inputs that have the same digest value.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest)+ */+ digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;+ /**+ * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey)+ */+ generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey | CryptoKeyPair>;+ /**+ * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey)+ */+ deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;+ /**+ * The **`deriveBits()`** method of the SubtleCrypto interface can be used to derive an array of bits from a base key.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits)+ */+ deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise<ArrayBuffer>;+ /**+ * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey)+ */+ importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;+ /**+ * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey)+ */+ exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>;+ /**+ * The **`wrapKey()`** method of the SubtleCrypto interface "wraps" a key. This means that it exports the key in an external, portable format, then encrypts the exported key. Wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey)+ */+ wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise<ArrayBuffer>;+ /**+ * The **`unwrapKey()`** method of the SubtleCrypto interface "unwraps" a key. This means that it takes as its input a key that has been exported and then encrypted (also called "wrapped"). It decrypts the key and then imports it, returning a CryptoKey object that can be used in the Web Crypto API.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey)+ */+ unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;+ timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean;+}+/**+ * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods generateKey(), deriveKey(), importKey(), or unwrapKey().+ * Available only in secure contexts.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey)+ */+declare abstract class CryptoKey {+ /**+ * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. It can have the following values:+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type)+ */+ readonly type: string;+ /**+ * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey().+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable)+ */+ readonly extractable: boolean;+ /**+ * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm)+ */+ readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm;+ /**+ * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages)+ */+ readonly usages: string[];+}+interface CryptoKeyPair {+ publicKey: CryptoKey;+ privateKey: CryptoKey;+}+interface JsonWebKey {+ kty: string;+ use?: string;+ key_ops?: string[];+ alg?: string;+ ext?: boolean;+ crv?: string;+ x?: string;+ y?: string;+ d?: string;+ n?: string;+ e?: string;+ p?: string;+ q?: string;+ dp?: string;+ dq?: string;+ qi?: string;+ oth?: RsaOtherPrimesInfo[];+ k?: string;+}+interface RsaOtherPrimesInfo {+ r?: string;+ d?: string;+ t?: string;+}+interface SubtleCryptoDeriveKeyAlgorithm {+ name: string;+ salt?: (ArrayBuffer | ArrayBufferView);+ iterations?: number;+ hash?: (string | SubtleCryptoHashAlgorithm);+ $public?: CryptoKey;+ info?: (ArrayBuffer | ArrayBufferView);+}+interface SubtleCryptoEncryptAlgorithm {+ name: string;+ iv?: (ArrayBuffer | ArrayBufferView);+ additionalData?: (ArrayBuffer | ArrayBufferView);+ tagLength?: number;+ counter?: (ArrayBuffer | ArrayBufferView);+ length?: number;+ label?: (ArrayBuffer | ArrayBufferView);+}+interface SubtleCryptoGenerateKeyAlgorithm {+ name: string;+ hash?: (string | SubtleCryptoHashAlgorithm);+ modulusLength?: number;+ publicExponent?: (ArrayBuffer | ArrayBufferView);+ length?: number;+ namedCurve?: string;+}+interface SubtleCryptoHashAlgorithm {+ name: string;+}+interface SubtleCryptoImportKeyAlgorithm {+ name: string;+ hash?: (string | SubtleCryptoHashAlgorithm);+ length?: number;+ namedCurve?: string;+ compressed?: boolean;+}+interface SubtleCryptoSignAlgorithm {+ name: string;+ hash?: (string | SubtleCryptoHashAlgorithm);+ dataLength?: number;+ saltLength?: number;+}+interface CryptoKeyKeyAlgorithm {+ name: string;+}+interface CryptoKeyAesKeyAlgorithm {+ name: string;+ length: number;+}+interface CryptoKeyHmacKeyAlgorithm {+ name: string;+ hash: CryptoKeyKeyAlgorithm;+ length: number;+}+interface CryptoKeyRsaKeyAlgorithm {+ name: string;+ modulusLength: number;+ publicExponent: ArrayBuffer | ArrayBufferView;+ hash?: CryptoKeyKeyAlgorithm;+}+interface CryptoKeyEllipticKeyAlgorithm {+ name: string;+ namedCurve: string;+}+interface CryptoKeyArbitraryKeyAlgorithm {+ name: string;+ hash?: CryptoKeyKeyAlgorithm;+ namedCurve?: string;+ length?: number;+}+declare class DigestStream extends WritableStream<ArrayBuffer | ArrayBufferView> {+ constructor(algorithm: string | SubtleCryptoHashAlgorithm, options?: DigestStreamOptions);+ readonly digest: Promise<ArrayBuffer>;+ get bytesWritten(): number | bigint;+}+interface DigestStreamOptions {+ toWellFormed?: boolean;+}+/**+ * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as UTF-8, ISO-8859-2, or GBK. A decoder takes an array of bytes as input and returns a JavaScript string.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)+ */+declare class TextDecoder {+ constructor(label?: string, options?: TextDecoderConstructorOptions);+ /**+ * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode)+ */+ decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string;+ get encoding(): string;+ get fatal(): boolean;+ get ignoreBOM(): boolean;+}+/**+ * The **`TextEncoder`** interface enables you to encode a JavaScript string using UTF-8.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)+ */+declare class TextEncoder {+ constructor();+ /**+ * The **`TextEncoder.encode()`** method takes a string as input, and returns a Uint8Array containing the string encoded using UTF-8.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)+ */+ encode(input?: string): Uint8Array;+ /**+ * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns an object indicating the progress of the encoding. This is potentially more performant than the encode() method — especially when the target buffer is a view into a Wasm heap.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto)+ */+ encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult;+ get encoding(): string;+}+interface TextDecoderConstructorOptions {+ fatal: boolean;+ ignoreBOM: boolean;+}+interface TextDecoderDecodeOptions {+ stream: boolean;+}+interface TextEncoderEncodeIntoResult {+ read: number;+ written: number;+}+/**+ * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent)+ */+declare class ErrorEvent extends Event {+ constructor(type: string, init?: ErrorEventErrorEventInit);+ /**+ * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename)+ */+ get filename(): string;+ /**+ * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message)+ */+ get message(): string;+ /**+ * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno)+ */+ get lineno(): number;+ /**+ * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno)+ */+ get colno(): number;+ /**+ * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error)+ */+ get error(): any;+}+interface ErrorEventErrorEventInit {+ bubbles?: boolean;+ cancelable?: boolean;+ composed?: boolean;+ message?: string;+ filename?: string;+ lineno?: number;+ colno?: number;+ error?: any;+}+/**+ * The **`MessageEvent`** interface represents a message received by a target object.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent)+ */+declare class MessageEvent extends Event {+ constructor(type: string, initializer?: MessageEventInit);+ /**+ * The **`data`** read-only property of the MessageEvent interface represents the data sent by the message emitter.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data)+ */+ readonly data: any;+ /**+ * The **`origin`** read-only property of the MessageEvent interface is a string representing the origin of the message emitter.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin)+ */+ readonly origin: string | null;+ /**+ * The **`lastEventId`** read-only property of the MessageEvent interface is a string representing a unique ID for the event.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId)+ */+ readonly lastEventId: string;+ /**+ * The **`source`** read-only property of the MessageEvent interface is a MessageEventSource (which can be a WindowProxy, MessagePort, or ServiceWorker object) representing the message emitter.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source)+ */+ readonly source: MessagePort | null;+ /**+ * The **`ports`** read-only property of the MessageEvent interface is an array of MessagePort objects containing all MessagePort objects sent with the message, in order.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports)+ */+ readonly ports: MessagePort[];+}+interface MessageEventInit {+ bubbles?: boolean;+ cancelable?: boolean;+ composed?: boolean;+ data?: any;+ origin?: string;+ lastEventId?: string;+ source?: MessagePort;+ ports?: MessagePort[];+}+/**+ * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. These events are particularly useful for telemetry and debugging purposes.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent)+ */+declare abstract class PromiseRejectionEvent extends Event {+ /**+ * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript Promise which was rejected. You can examine the event's PromiseRejectionEvent.reason property to learn why the promise was rejected.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise)+ */+ readonly promise: Promise<any>;+ /**+ * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). This in theory provides information about why the promise was rejected.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason)+ */+ readonly reason: any;+}+/**+ * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the fetch(), XMLHttpRequest.send() or navigator.sendBeacon() methods. It uses the same format a form would use if the encoding type were set to "multipart/form-data".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData)+ */+declare class FormData {+ constructor();+ /**+ * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)+ */+ append(name: string, value: string | Blob): void;+ /**+ * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)+ */+ append(name: string, value: string): void;+ /**+ * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)+ */+ append(name: string, value: Blob, filename?: string): void;+ /**+ * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a FormData object.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete)+ */+ delete(name: string): void;+ /**+ * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get)+ */+ get(name: string): (File | string) | null;+ /**+ * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a FormData object.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll)+ */+ getAll(name: string): (File | string)[];+ /**+ * The **`has()`** method of the FormData interface returns whether a FormData object contains a certain key.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has)+ */+ has(name: string): boolean;+ /**+ * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)+ */+ set(name: string, value: string | Blob): void;+ /**+ * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)+ */+ set(name: string, value: string): void;+ /**+ * The **`set()`** method of the FormData interface sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)+ */+ set(name: string, value: Blob, filename?: string): void;+ entries(): IterableIterator<[+ key: string,+ value: File | string+ ]>;+ keys(): IterableIterator<string>;+ values(): IterableIterator<(File | string)>;+ forEach<This = unknown>(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void;+ [Symbol.iterator](): IterableIterator<[+ key: string,+ value: File | string+ ]>;+}+interface ContentOptions {+ html?: boolean;+}+declare class HTMLRewriter {+ constructor();+ on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter;+ onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter;+ transform(response: Response): Response;+}+interface HTMLRewriterElementContentHandlers {+ element?(element: Element): void | Promise<void>;+ comments?(comment: Comment): void | Promise<void>;+ text?(element: Text): void | Promise<void>;+}+interface HTMLRewriterDocumentContentHandlers {+ doctype?(doctype: Doctype): void | Promise<void>;+ comments?(comment: Comment): void | Promise<void>;+ text?(text: Text): void | Promise<void>;+ end?(end: DocumentEnd): void | Promise<void>;+}+interface Doctype {+ readonly name: string | null;+ readonly publicId: string | null;+ readonly systemId: string | null;+}+interface Element {+ tagName: string;+ readonly attributes: IterableIterator<string[]>;+ readonly removed: boolean;+ readonly namespaceURI: string;+ getAttribute(name: string): string | null;+ hasAttribute(name: string): boolean;+ setAttribute(name: string, value: string): Element;+ removeAttribute(name: string): Element;+ before(content: string | ReadableStream | Response, options?: ContentOptions): Element;+ after(content: string | ReadableStream | Response, options?: ContentOptions): Element;+ prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element;+ append(content: string | ReadableStream | Response, options?: ContentOptions): Element;+ replace(content: string | ReadableStream | Response, options?: ContentOptions): Element;+ remove(): Element;+ removeAndKeepContent(): Element;+ setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element;+ onEndTag(handler: (tag: EndTag) => void | Promise<void>): void;+}+interface EndTag {+ name: string;+ before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;+ after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;+ remove(): EndTag;+}+interface Comment {+ text: string;+ readonly removed: boolean;+ before(content: string, options?: ContentOptions): Comment;+ after(content: string, options?: ContentOptions): Comment;+ replace(content: string, options?: ContentOptions): Comment;+ remove(): Comment;+}+interface Text {+ readonly text: string;+ readonly lastInTextNode: boolean;+ readonly removed: boolean;+ before(content: string | ReadableStream | Response, options?: ContentOptions): Text;+ after(content: string | ReadableStream | Response, options?: ContentOptions): Text;+ replace(content: string | ReadableStream | Response, options?: ContentOptions): Text;+ remove(): Text;+}+interface DocumentEnd {+ append(content: string, options?: ContentOptions): DocumentEnd;+}+/**+ * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent)+ */+declare abstract class FetchEvent extends ExtendableEvent {+ /**+ * The **`request`** read-only property of the FetchEvent interface returns the Request that triggered the event handler.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request)+ */+ readonly request: Request;+ /**+ * The **`respondWith()`** method of FetchEvent prevents the browser's default fetch handling, and allows you to provide a promise for a Response yourself.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith)+ */+ respondWith(promise: Response | Promise<Response>): void;+ passThroughOnException(): void;+}+type HeadersInit = Headers | Iterable<Iterable<string>> | Record<string, string>;+/**+ * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers)+ */+declare class Headers {+ constructor(init?: HeadersInit);+ /**+ * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get)+ */+ get(name: string): string | null;+ getAll(name: string): string[];+ /**+ * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. This allows Headers objects to handle having multiple Set-Cookie headers, which wasn't possible prior to its implementation.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie)+ */+ getSetCookie(): string[];+ /**+ * The **`has()`** method of the Headers interface returns a boolean stating whether a Headers object contains a certain header.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has)+ */+ has(name: string): boolean;+ /**+ * The **`set()`** method of the Headers interface sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set)+ */+ set(name: string, value: string): void;+ /**+ * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append)+ */+ append(name: string, value: string): void;+ /**+ * The **`delete()`** method of the Headers interface deletes a header from the current Headers object.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete)+ */+ delete(name: string): void;+ forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void;+ entries(): IterableIterator<[+ key: string,+ value: string+ ]>;+ keys(): IterableIterator<string>;+ values(): IterableIterator<string>;+ [Symbol.iterator](): IterableIterator<[+ key: string,+ value: string+ ]>;+}+type BodyInit = ReadableStream<Uint8Array> | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable<ArrayBuffer | ArrayBufferView> | AsyncIterable<ArrayBuffer | ArrayBufferView>;+declare abstract class Body {+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */+ get body(): ReadableStream | null;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */+ get bodyUsed(): boolean;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */+ arrayBuffer(): Promise<ArrayBuffer>;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */+ bytes(): Promise<Uint8Array>;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */+ text(): Promise<string>;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */+ json<T>(): Promise<T>;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */+ formData(): Promise<FormData>;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */+ blob(): Promise<Blob>;+}+/**+ * The **`Response`** interface of the Fetch API represents the response to a request.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)+ */+declare var Response: {+ prototype: Response;+ new (body?: BodyInit | null, init?: ResponseInit): Response;+ error(): Response;+ redirect(url: string, status?: number): Response;+ json(any: any, maybeInit?: (ResponseInit | Response)): Response;+};+/**+ * The **`Response`** interface of the Fetch API represents the response to a request.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)+ */+interface Response extends Body {+ /**+ * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone)+ */+ clone(): Response;+ /**+ * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status)+ */+ status: number;+ /**+ * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText)+ */+ statusText: string;+ /**+ * The **`headers`** read-only property of the Response interface contains the Headers object associated with the response.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers)+ */+ headers: Headers;+ /**+ * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok)+ */+ ok: boolean;+ /**+ * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected)+ */+ redirected: boolean;+ /**+ * The **`url`** read-only property of the Response interface contains the URL of the response. The value of the url property will be the final URL obtained after any redirects.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url)+ */+ url: string;+ webSocket: WebSocket | null;+ cf: any | undefined;+ /**+ * The **`type`** read-only property of the Response interface contains the type of the response. The type determines whether scripts are able to access the response body and headers.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type)+ */+ type: "default" | "error";+}+interface ResponseInit {+ status?: number;+ statusText?: string;+ headers?: HeadersInit;+ cf?: any;+ webSocket?: (WebSocket | null);+ encodeBody?: "automatic" | "manual";+}+type RequestInfo<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> = Request<CfHostMetadata, Cf> | string;+/**+ * The **`Request`** interface of the Fetch API represents a resource request.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)+ */+declare var Request: {+ prototype: Request;+ new <CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>(input: RequestInfo<CfProperties> | URL, init?: RequestInit<Cf>): Request<CfHostMetadata, Cf>;+};+/**+ * The **`Request`** interface of the Fetch API represents a resource request.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)+ */+interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> extends Body {+ /**+ * The **`clone()`** method of the Request interface creates a copy of the current Request object.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone)+ */+ clone(): Request<CfHostMetadata, Cf>;+ /**+ * The **`method`** read-only property of the Request interface contains the request's method (GET, POST, etc.)+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method)+ */+ method: string;+ /**+ * The **`url`** read-only property of the Request interface contains the URL of the request.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)+ */+ url: string;+ /**+ * The **`headers`** read-only property of the Request interface contains the Headers object associated with the request.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers)+ */+ headers: Headers;+ /**+ * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect)+ */+ redirect: string;+ fetcher: Fetcher | null;+ /**+ * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal)+ */+ signal: AbortSignal;+ cf?: Cf;+ /**+ * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity)+ */+ integrity: string;+ /**+ * The **`keepalive`** read-only property of the Request interface contains the request's keepalive setting (true or false), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive)+ */+ keepalive: boolean;+ /**+ * The **`cache`** read-only property of the Request interface contains the cache mode of the request. It controls how the request will interact with the browser's HTTP cache.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache)+ */+ cache?: "no-store" | "no-cache";+}+interface RequestInit<Cf = CfProperties> {+ /* A string to set request's method. */+ method?: string;+ /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */+ headers?: HeadersInit;+ /* A BodyInit object or null to set request's body. */+ body?: BodyInit | null;+ /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */+ redirect?: string;+ fetcher?: (Fetcher | null);+ cf?: Cf;+ /* A string indicating how the request will interact with the browser's cache to set request's cache. */+ cache?: "no-store" | "no-cache";+ /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */+ integrity?: string;+ /* An AbortSignal to set request's signal. */+ signal?: (AbortSignal | null);+ encodeResponseBody?: "automatic" | "manual";+}+type Service<T extends (new (...args: any[]) => Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher<InstanceType<T>> : T extends Rpc.WorkerEntrypointBranded ? Fetcher<T> : T extends Exclude<Rpc.EntrypointBranded, Rpc.WorkerEntrypointBranded> ? never : Fetcher<undefined>;+type Fetcher<T extends Rpc.EntrypointBranded | undefined = undefined, Reserved extends string = never> = (T extends Rpc.EntrypointBranded ? Rpc.Provider<T, Reserved | "fetch" | "connect"> : unknown) & {+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;+ connect(address: SocketAddress | string, options?: SocketOptions): Socket;+};+interface KVNamespaceListKey<Metadata, Key extends string = string> {+ name: Key;+ expiration?: number;+ metadata?: Metadata;+}+type KVNamespaceListResult<Metadata, Key extends string = string> = {+ list_complete: false;+ keys: KVNamespaceListKey<Metadata, Key>[];+ cursor: string;+ cacheStatus: string | null;+} | {+ list_complete: true;+ keys: KVNamespaceListKey<Metadata, Key>[];+ cacheStatus: string | null;+};+interface KVNamespace<Key extends string = string> {+ get(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<string | null>;+ get(key: Key, type: "text"): Promise<string | null>;+ get<ExpectedValue = unknown>(key: Key, type: "json"): Promise<ExpectedValue | null>;+ get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>;+ get(key: Key, type: "stream"): Promise<ReadableStream | null>;+ get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise<string | null>;+ get<ExpectedValue = unknown>(key: Key, options?: KVNamespaceGetOptions<"json">): Promise<ExpectedValue | null>;+ get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise<ArrayBuffer | null>;+ get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise<ReadableStream | null>;+ get(key: Array<Key>, type: "text"): Promise<Map<string, string | null>>;+ get<ExpectedValue = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, ExpectedValue | null>>;+ get(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, string | null>>;+ get(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, string | null>>;+ get<ExpectedValue = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, ExpectedValue | null>>;+ list<Metadata = unknown>(options?: KVNamespaceListOptions): Promise<KVNamespaceListResult<Metadata, Key>>;+ put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise<void>;+ getWithMetadata<Metadata = unknown>(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;+ getWithMetadata<Metadata = unknown>(key: Key, type: "text"): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;+ getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, type: "json"): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;+ getWithMetadata<Metadata = unknown>(key: Key, type: "arrayBuffer"): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;+ getWithMetadata<Metadata = unknown>(key: Key, type: "stream"): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;+ getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"text">): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;+ getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"json">): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;+ getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;+ getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"stream">): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;+ getWithMetadata<Metadata = unknown>(key: Array<Key>, type: "text"): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;+ getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;+ getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;+ getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;+ getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;+ delete(key: Key): Promise<void>;+}+interface KVNamespaceListOptions {+ limit?: number;+ prefix?: (string | null);+ cursor?: (string | null);+}+interface KVNamespaceGetOptions<Type> {+ type: Type;+ cacheTtl?: number;+}+interface KVNamespacePutOptions {+ expiration?: number;+ expirationTtl?: number;+ metadata?: (any | null);+}+interface KVNamespaceGetWithMetadataResult<Value, Metadata> {+ value: Value | null;+ metadata: Metadata | null;+ cacheStatus: string | null;+}+type QueueContentType = "text" | "bytes" | "json" | "v8";+interface Queue<Body = unknown> {+ metrics(): Promise<QueueMetrics>;+ send(message: Body, options?: QueueSendOptions): Promise<QueueSendResponse>;+ sendBatch(messages: Iterable<MessageSendRequest<Body>>, options?: QueueSendBatchOptions): Promise<QueueSendBatchResponse>;+}+interface QueueSendMetrics {+ backlogCount: number;+ backlogBytes: number;+ oldestMessageTimestamp?: Date;+}+interface QueueSendMetadata {+ metrics: QueueSendMetrics;+}+interface QueueSendResponse {+ metadata: QueueSendMetadata;+}+interface QueueSendBatchMetrics {+ backlogCount: number;+ backlogBytes: number;+ oldestMessageTimestamp?: Date;+}+interface QueueSendBatchMetadata {+ metrics: QueueSendBatchMetrics;+}+interface QueueSendBatchResponse {+ metadata: QueueSendBatchMetadata;+}+interface QueueSendOptions {+ contentType?: QueueContentType;+ delaySeconds?: number;+}+interface QueueSendBatchOptions {+ delaySeconds?: number;+}+interface MessageSendRequest<Body = unknown> {+ body: Body;+ contentType?: QueueContentType;+ delaySeconds?: number;+}+interface QueueMetrics {+ backlogCount: number;+ backlogBytes: number;+ oldestMessageTimestamp?: Date;+}+interface MessageBatchMetrics {+ backlogCount: number;+ backlogBytes: number;+ oldestMessageTimestamp?: Date;+}+interface MessageBatchMetadata {+ metrics: MessageBatchMetrics;+}+interface QueueRetryOptions {+ delaySeconds?: number;+}+interface Message<Body = unknown> {+ readonly id: string;+ readonly timestamp: Date;+ readonly body: Body;+ readonly attempts: number;+ retry(options?: QueueRetryOptions): void;+ ack(): void;+}+interface QueueEvent<Body = unknown> extends ExtendableEvent {+ readonly messages: readonly Message<Body>[];+ readonly queue: string;+ readonly metadata: MessageBatchMetadata;+ retryAll(options?: QueueRetryOptions): void;+ ackAll(): void;+}+interface MessageBatch<Body = unknown> {+ readonly messages: readonly Message<Body>[];+ readonly queue: string;+ readonly metadata: MessageBatchMetadata;+ retryAll(options?: QueueRetryOptions): void;+ ackAll(): void;+}+interface R2Error extends Error {+ readonly name: string;+ readonly code: number;+ readonly message: string;+ readonly action: string;+ readonly stack: any;+}+interface R2ListOptions {+ limit?: number;+ prefix?: string;+ cursor?: string;+ delimiter?: string;+ startAfter?: string;+ include?: ("httpMetadata" | "customMetadata")[];+}+interface R2Bucket {+ head(key: string): Promise<R2Object | null>;+ get(key: string, options: R2GetOptions & {+ onlyIf: R2Conditional | Headers;+ }): Promise<R2ObjectBody | R2Object | null>;+ get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>;+ put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & {+ onlyIf: R2Conditional | Headers;+ }): Promise<R2Object | null>;+ put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise<R2Object>;+ createMultipartUpload(key: string, options?: R2MultipartOptions): Promise<R2MultipartUpload>;+ resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload;+ delete(keys: string | string[]): Promise<void>;+ list(options?: R2ListOptions): Promise<R2Objects>;+}+interface R2MultipartUpload {+ readonly key: string;+ readonly uploadId: string;+ uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise<R2UploadedPart>;+ abort(): Promise<void>;+ complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>;+}+interface R2UploadedPart {+ partNumber: number;+ etag: string;+}+declare abstract class R2Object {+ readonly key: string;+ readonly version: string;+ readonly size: number;+ readonly etag: string;+ readonly httpEtag: string;+ readonly checksums: R2Checksums;+ readonly uploaded: Date;+ readonly httpMetadata?: R2HTTPMetadata;+ readonly customMetadata?: Record<string, string>;+ readonly range?: R2Range;+ readonly storageClass: string;+ readonly ssecKeyMd5?: string;+ writeHttpMetadata(headers: Headers): void;+}+interface R2ObjectBody extends R2Object {+ get body(): ReadableStream;+ get bodyUsed(): boolean;+ arrayBuffer(): Promise<ArrayBuffer>;+ bytes(): Promise<Uint8Array>;+ text(): Promise<string>;+ json<T>(): Promise<T>;+ blob(): Promise<Blob>;+}+type R2Range = {+ offset: number;+ length?: number;+} | {+ offset?: number;+ length: number;+} | {+ suffix: number;+};+interface R2Conditional {+ etagMatches?: string;+ etagDoesNotMatch?: string;+ uploadedBefore?: Date;+ uploadedAfter?: Date;+ secondsGranularity?: boolean;+}+interface R2GetOptions {+ onlyIf?: (R2Conditional | Headers);+ range?: (R2Range | Headers);+ ssecKey?: (ArrayBuffer | string);+}+interface R2PutOptions {+ onlyIf?: (R2Conditional | Headers);+ httpMetadata?: (R2HTTPMetadata | Headers);+ customMetadata?: Record<string, string>;+ md5?: ((ArrayBuffer | ArrayBufferView) | string);+ sha1?: ((ArrayBuffer | ArrayBufferView) | string);+ sha256?: ((ArrayBuffer | ArrayBufferView) | string);+ sha384?: ((ArrayBuffer | ArrayBufferView) | string);+ sha512?: ((ArrayBuffer | ArrayBufferView) | string);+ storageClass?: string;+ ssecKey?: (ArrayBuffer | string);+}+interface R2MultipartOptions {+ httpMetadata?: (R2HTTPMetadata | Headers);+ customMetadata?: Record<string, string>;+ storageClass?: string;+ ssecKey?: (ArrayBuffer | string);+}+interface R2Checksums {+ readonly md5?: ArrayBuffer;+ readonly sha1?: ArrayBuffer;+ readonly sha256?: ArrayBuffer;+ readonly sha384?: ArrayBuffer;+ readonly sha512?: ArrayBuffer;+ toJSON(): R2StringChecksums;+}+interface R2StringChecksums {+ md5?: string;+ sha1?: string;+ sha256?: string;+ sha384?: string;+ sha512?: string;+}+interface R2HTTPMetadata {+ contentType?: string;+ contentLanguage?: string;+ contentDisposition?: string;+ contentEncoding?: string;+ cacheControl?: string;+ cacheExpiry?: Date;+}+type R2Objects = {+ objects: R2Object[];+ delimitedPrefixes: string[];+} & ({+ truncated: true;+ cursor: string;+} | {+ truncated: false;+});+interface R2UploadPartOptions {+ ssecKey?: (ArrayBuffer | string);+}+declare abstract class ScheduledEvent extends ExtendableEvent {+ readonly scheduledTime: number;+ readonly cron: string;+ noRetry(): void;+}+interface ScheduledController {+ readonly scheduledTime: number;+ readonly cron: string;+ noRetry(): void;+}+interface QueuingStrategy<T = any> {+ highWaterMark?: (number | bigint);+ size?: (chunk: T) => number | bigint;+}+interface UnderlyingSink<W = any> {+ type?: string;+ start?: (controller: WritableStreamDefaultController) => void | Promise<void>;+ write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise<void>;+ abort?: (reason: any) => void | Promise<void>;+ close?: () => void | Promise<void>;+}+interface UnderlyingByteSource {+ type: "bytes";+ autoAllocateChunkSize?: number;+ start?: (controller: ReadableByteStreamController) => void | Promise<void>;+ pull?: (controller: ReadableByteStreamController) => void | Promise<void>;+ cancel?: (reason: any) => void | Promise<void>;+}+interface UnderlyingSource<R = any> {+ type?: "" | undefined;+ start?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;+ pull?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;+ cancel?: (reason: any) => void | Promise<void>;+ expectedLength?: (number | bigint);+}+interface Transformer<I = any, O = any> {+ readableType?: string;+ writableType?: string;+ start?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;+ transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | Promise<void>;+ flush?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;+ cancel?: (reason: any) => void | Promise<void>;+ expectedLength?: number;+}+interface StreamPipeOptions {+ preventAbort?: boolean;+ preventCancel?: boolean;+ /**+ * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.+ *+ * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.+ *+ * Errors and closures of the source and destination streams propagate as follows:+ *+ * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination.+ *+ * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source.+ *+ * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.+ *+ * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.+ *+ * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.+ */+ preventClose?: boolean;+ signal?: AbortSignal;+}+type ReadableStreamReadResult<R = any> = {+ done: false;+ value: R;+} | {+ done: true;+ value?: undefined;+};+/**+ * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)+ */+interface ReadableStream<R = any> {+ /**+ * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked)+ */+ get locked(): boolean;+ /**+ * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel)+ */+ cancel(reason?: any): Promise<void>;+ /**+ * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)+ */+ getReader(): ReadableStreamDefaultReader<R>;+ /**+ * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)+ */+ getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader;+ /**+ * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough)+ */+ pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;+ /**+ * The **`pipeTo()`** method of the ReadableStream interface pipes the current ReadableStream to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo)+ */+ pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;+ /**+ * The **`tee()`** method of the ReadableStream interface tees the current readable stream, returning a two-element array containing the two resulting branches as new ReadableStream instances.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee)+ */+ tee(): [+ ReadableStream<R>,+ ReadableStream<R>+ ];+ values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;+ [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;+}+/**+ * The **`ReadableStream`** interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)+ */+declare const ReadableStream: {+ prototype: ReadableStream;+ new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy<Uint8Array>): ReadableStream<Uint8Array>;+ new <R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;+};+/**+ * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader)+ */+declare class ReadableStreamDefaultReader<R = any> {+ constructor(stream: ReadableStream);+ get closed(): Promise<void>;+ cancel(reason?: any): Promise<void>;+ /**+ * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read)+ */+ read(): Promise<ReadableStreamReadResult<R>>;+ /**+ * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock)+ */+ releaseLock(): void;+}+/**+ * The **`ReadableStreamBYOBReader`** interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. It is used for efficient copying from underlying sources where the data is delivered as an "anonymous" sequence of bytes, such as files.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader)+ */+declare class ReadableStreamBYOBReader {+ constructor(stream: ReadableStream);+ get closed(): Promise<void>;+ cancel(reason?: any): Promise<void>;+ /**+ * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. A request for data will be satisfied from the stream's internal queues if there is any data present. If the stream queues are empty, the request may be supplied as a zero-copy transfer from the underlying byte source.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read)+ */+ read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;+ /**+ * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. After the lock is released, the reader is no longer active.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock)+ */+ releaseLock(): void;+ readAtLeast<T extends ArrayBufferView>(minElements: number, view: T): Promise<ReadableStreamReadResult<T>>;+}+interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions {+ min?: number;+}+interface ReadableStreamGetReaderOptions {+ /**+ * Creates a ReadableStreamBYOBReader and locks the stream to the new reader.+ *+ * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation.+ */+ mode: "byob";+}+/**+ * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a "pull request" for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest)+ */+declare abstract class ReadableStreamBYOBRequest {+ /**+ * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view)+ */+ get view(): Uint8Array | null;+ /**+ * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond)+ */+ respond(bytesWritten: number): void;+ /**+ * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView)+ */+ respondWithNewView(view: ArrayBuffer | ArrayBufferView): void;+ get atLeast(): number | null;+}+/**+ * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. Default controllers are for streams that are not byte streams.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController)+ */+declare abstract class ReadableStreamDefaultController<R = any> {+ /**+ * The **`desiredSize`** read-only property of the ReadableStreamDefaultController interface returns the desired size required to fill the stream's internal queue.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize)+ */+ get desiredSize(): number | null;+ /**+ * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close)+ */+ close(): void;+ /**+ * The **`enqueue()`** method of the ReadableStreamDefaultController interface enqueues a given chunk in the associated stream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue)+ */+ enqueue(chunk?: R): void;+ /**+ * The **`error()`** method of the ReadableStreamDefaultController interface causes any future interactions with the associated stream to error.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error)+ */+ error(reason: any): void;+}+/**+ * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. It allows control of the state and internal queue of a ReadableStream with an underlying byte source, and enables efficient zero-copy transfer of data from the underlying source to a consumer when the stream's internal queue is empty.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController)+ */+declare abstract class ReadableByteStreamController {+ /**+ * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or null if there are no pending requests.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest)+ */+ get byobRequest(): ReadableStreamBYOBRequest | null;+ /**+ * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its "desired size".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize)+ */+ get desiredSize(): number | null;+ /**+ * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close)+ */+ close(): void;+ /**+ * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is transferred into the stream's internal queues).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue)+ */+ enqueue(chunk: ArrayBuffer | ArrayBufferView): void;+ /**+ * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error)+ */+ error(reason: any): void;+}+/**+ * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController)+ */+declare abstract class WritableStreamDefaultController {+ /**+ * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal)+ */+ get signal(): AbortSignal;+ /**+ * The **`error()`** method of the WritableStreamDefaultController interface causes any future interactions with the associated stream to error.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error)+ */+ error(reason?: any): void;+}+/**+ * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController)+ */+declare abstract class TransformStreamDefaultController<O = any> {+ /**+ * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize)+ */+ get desiredSize(): number | null;+ /**+ * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue)+ */+ enqueue(chunk?: O): void;+ /**+ * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. Any further interactions with it will fail with the given error message, and any chunks in the queue will be discarded.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error)+ */+ error(reason: any): void;+ /**+ * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate)+ */+ terminate(): void;+}+interface ReadableWritablePair<R = any, W = any> {+ readable: ReadableStream<R>;+ /**+ * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.+ *+ * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.+ */+ writable: WritableStream<W>;+}+/**+ * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream)+ */+declare class WritableStream<W = any> {+ constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy);+ /**+ * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the WritableStream is locked to a writer.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked)+ */+ get locked(): boolean;+ /**+ * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort)+ */+ abort(reason?: any): Promise<void>;+ /**+ * The **`close()`** method of the WritableStream interface closes the associated stream. All chunks written before this method is called are sent before the returned promise is fulfilled.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close)+ */+ close(): Promise<void>;+ /**+ * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter)+ */+ getWriter(): WritableStreamDefaultWriter<W>;+}+/**+ * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the WritableStream ensuring that no other streams can write to the underlying sink.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter)+ */+declare class WritableStreamDefaultWriter<W = any> {+ constructor(stream: WritableStream);+ /**+ * The **`closed`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that fulfills if the stream becomes closed, or rejects if the stream errors or the writer's lock is released.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed)+ */+ get closed(): Promise<void>;+ /**+ * The **`ready`** read-only property of the WritableStreamDefaultWriter interface returns a Promise that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready)+ */+ get ready(): Promise<void>;+ /**+ * The **`desiredSize`** read-only property of the WritableStreamDefaultWriter interface returns the desired size required to fill the stream's internal queue.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize)+ */+ get desiredSize(): number | null;+ /**+ * The **`abort()`** method of the WritableStreamDefaultWriter interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort)+ */+ abort(reason?: any): Promise<void>;+ /**+ * The **`close()`** method of the WritableStreamDefaultWriter interface closes the associated writable stream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close)+ */+ close(): Promise<void>;+ /**+ * The **`write()`** method of the WritableStreamDefaultWriter interface writes a passed chunk of data to a WritableStream and its underlying sink, then returns a Promise that resolves to indicate the success or failure of the write operation.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write)+ */+ write(chunk?: W): Promise<void>;+ /**+ * The **`releaseLock()`** method of the WritableStreamDefaultWriter interface releases the writer's lock on the corresponding stream. After the lock is released, the writer is no longer active. If the associated stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise, the writer will appear closed.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock)+ */+ releaseLock(): void;+}+/**+ * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain transform stream concept.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream)+ */+declare class TransformStream<I = any, O = any> {+ constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);+ /**+ * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this TransformStream. This stream emits the transformed output data.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable)+ */+ get readable(): ReadableStream<O>;+ /**+ * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this TransformStream. This stream accepts input data that will be transformed and emitted to the readable stream.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable)+ */+ get writable(): WritableStream<I>;+}+declare class FixedLengthStream extends IdentityTransformStream {+ constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy);+}+declare class IdentityTransformStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {+ constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy);+}+interface IdentityTransformStreamQueuingStrategy {+ highWaterMark?: (number | bigint);+}+interface ReadableStreamValuesOptions {+ preventCancel?: boolean;+}+/**+ * The **`CompressionStream`** interface of the Compression Streams API compresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream)+ */+declare class CompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {+ constructor(format: "gzip" | "deflate" | "deflate-raw");+}+/**+ * The **`DecompressionStream`** interface of the Compression Streams API decompresses a stream of data. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream)+ */+declare class DecompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {+ constructor(format: "gzip" | "deflate" | "deflate-raw");+}+/**+ * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. It is the streaming equivalent of TextEncoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream)+ */+declare class TextEncoderStream extends TransformStream<string, Uint8Array> {+ constructor();+ get encoding(): string;+}+/**+ * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. It is the streaming equivalent of TextDecoder. It implements the same shape as a TransformStream, allowing it to be used in ReadableStream.pipeThrough() and similar methods.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream)+ */+declare class TextDecoderStream extends TransformStream<ArrayBuffer | ArrayBufferView, string> {+ constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit);+ get encoding(): string;+ get fatal(): boolean;+ get ignoreBOM(): boolean;+}+interface TextDecoderStreamTextDecoderStreamInit {+ fatal?: boolean;+ ignoreBOM?: boolean;+}+/**+ * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy)+ */+declare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {+ constructor(init: QueuingStrategyInit);+ /**+ * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark)+ */+ get highWaterMark(): number;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */+ get size(): (chunk?: any) => number;+}+/**+ * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy)+ */+declare class CountQueuingStrategy implements QueuingStrategy {+ constructor(init: QueuingStrategyInit);+ /**+ * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark)+ */+ get highWaterMark(): number;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */+ get size(): (chunk?: any) => number;+}+interface QueuingStrategyInit {+ /**+ * Creates a new ByteLengthQueuingStrategy with the provided high water mark.+ *+ * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.+ */+ highWaterMark: number;+}+interface TracePreviewInfo {+ id: string;+ slug: string;+ name: string;+}+interface ScriptVersion {+ id?: string;+ tag?: string;+ message?: string;+}+declare abstract class TailEvent extends ExtendableEvent {+ readonly events: TraceItem[];+ readonly traces: TraceItem[];+}+interface TraceItem {+ readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null;+ readonly eventTimestamp: number | null;+ readonly logs: TraceLog[];+ readonly exceptions: TraceException[];+ readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[];+ readonly scriptName: string | null;+ readonly entrypoint?: string;+ readonly scriptVersion?: ScriptVersion;+ readonly dispatchNamespace?: string;+ readonly scriptTags?: string[];+ readonly tailAttributes?: Record<string, boolean | number | string>;+ readonly preview?: TracePreviewInfo;+ readonly durableObjectId?: string;+ readonly outcome: string;+ readonly executionModel: string;+ readonly truncated: boolean;+ readonly cpuTime: number;+ readonly wallTime: number;+}+interface TraceItemAlarmEventInfo {+ readonly scheduledTime: Date;+}+interface TraceItemConnectEventInfo {+}+interface TraceItemCustomEventInfo {+}+interface TraceItemScheduledEventInfo {+ readonly scheduledTime: number;+ readonly cron: string;+}+interface TraceItemQueueEventInfo {+ readonly queue: string;+ readonly batchSize: number;+}+interface TraceItemEmailEventInfo {+ readonly mailFrom: string;+ readonly rcptTo: string;+ readonly rawSize: number;+}+interface TraceItemTailEventInfo {+ readonly consumedEvents: TraceItemTailEventInfoTailItem[];+}+interface TraceItemTailEventInfoTailItem {+ readonly scriptName: string | null;+}+interface TraceItemFetchEventInfo {+ readonly response?: TraceItemFetchEventInfoResponse;+ readonly request: TraceItemFetchEventInfoRequest;+}+interface TraceItemFetchEventInfoRequest {+ readonly cf?: any;+ readonly headers: Record<string, string>;+ readonly method: string;+ readonly url: string;+ getUnredacted(): TraceItemFetchEventInfoRequest;+}+interface TraceItemFetchEventInfoResponse {+ readonly status: number;+}+interface TraceItemJsRpcEventInfo {+ readonly rpcMethod: string;+}+interface TraceItemHibernatableWebSocketEventInfo {+ readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError;+}+interface TraceItemHibernatableWebSocketEventInfoMessage {+ readonly webSocketEventType: string;+}+interface TraceItemHibernatableWebSocketEventInfoClose {+ readonly webSocketEventType: string;+ readonly code: number;+ readonly wasClean: boolean;+}+interface TraceItemHibernatableWebSocketEventInfoError {+ readonly webSocketEventType: string;+}+interface TraceLog {+ readonly timestamp: number;+ readonly level: string;+ readonly message: any;+ readonly errorInfo?: (TraceLogErrorInfo | null)[];+}+interface TraceLogErrorInfo {+ name: string;+ message: string;+ stack?: string;+}+interface TraceException {+ readonly timestamp: number;+ readonly message: string;+ readonly name: string;+ readonly stack?: string;+}+interface TraceDiagnosticChannelEvent {+ readonly timestamp: number;+ readonly channel: string;+ readonly message: any;+}+interface TraceMetrics {+ readonly cpuTime: number;+ readonly wallTime: number;+}+interface UnsafeTraceMetrics {+ fromTrace(item: TraceItem): TraceMetrics;+}+/**+ * The **`URL`** interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)+ */+declare class URL {+ constructor(url: string | URL, base?: string | URL);+ /**+ * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin)+ */+ get origin(): string;+ /**+ * The **`href`** property of the URL interface is a string containing the whole URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)+ */+ get href(): string;+ /**+ * The **`href`** property of the URL interface is a string containing the whole URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)+ */+ set href(value: string);+ /**+ * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)+ */+ get protocol(): string;+ /**+ * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)+ */+ set protocol(value: string);+ /**+ * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)+ */+ get username(): string;+ /**+ * The **`username`** property of the URL interface is a string containing the username component of the URL. If the URL does not have a username, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)+ */+ set username(value: string);+ /**+ * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)+ */+ get password(): string;+ /**+ * The **`password`** property of the URL interface is a string containing the password component of the URL. If the URL does not have a password, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)+ */+ set password(value: string);+ /**+ * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)+ */+ get host(): string;+ /**+ * The **`host`** property of the URL interface is a string containing the host, which is the hostname, and then, if the port of the URL is nonempty, a ":", followed by the port of the URL. If the URL does not have a hostname, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)+ */+ set host(value: string);+ /**+ * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)+ */+ get hostname(): string;+ /**+ * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. If the URL does not have a hostname, this property contains an empty string, "". IPv4 and IPv6 addresses are normalized, such as stripping leading zeros, and domain names are converted to IDN.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)+ */+ set hostname(value: string);+ /**+ * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)+ */+ get port(): string;+ /**+ * The **`port`** property of the URL interface is a string containing the port number of the URL. If the port is the default for the protocol (80 for ws: and http:, 443 for wss: and https:, and 21 for ftp:), this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)+ */+ set port(value: string);+ /**+ * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)+ */+ get pathname(): string;+ /**+ * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)+ */+ set pathname(value: string);+ /**+ * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)+ */+ get search(): string;+ /**+ * The **`search`** property of the URL interface is a search string, also called a query string, that is a string containing a "?" followed by the parameters of the URL. If the URL does not have a search query, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)+ */+ set search(value: string);+ /**+ * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)+ */+ get hash(): string;+ /**+ * The **`hash`** property of the URL interface is a string containing a "#" followed by the fragment identifier of the URL. If the URL does not have a fragment identifier, this property contains an empty string, "".+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)+ */+ set hash(value: string);+ /**+ * The **`searchParams`** read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams)+ */+ get searchParams(): URLSearchParams;+ /**+ * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as URL.toString().+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON)+ */+ toJSON(): string;+ /*function toString() { [native code] }*/+ toString(): string;+ /**+ * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static)+ */+ static canParse(url: string, base?: string): boolean;+ /**+ * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static)+ */+ static parse(url: string, base?: string): URL | null;+ /**+ * The **`createObjectURL()`** static method of the URL interface creates a string containing a blob URL pointing to the object given in the parameter.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static)+ */+ static createObjectURL(object: File | Blob): string;+ /**+ * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling URL.createObjectURL().+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static)+ */+ static revokeObjectURL(object_url: string): void;+}+/**+ * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams)+ */+declare class URLSearchParams {+ constructor(init?: (Iterable<Iterable<string>> | Record<string, string> | string));+ /**+ * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size)+ */+ get size(): number;+ /**+ * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append)+ */+ append(name: string, value: string): void;+ /**+ * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete)+ */+ delete(name: string, value?: string): void;+ /**+ * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)+ */+ get(name: string): string | null;+ /**+ * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll)+ */+ getAll(name: string): string[];+ /**+ * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has)+ */+ has(name: string, value?: string): boolean;+ /**+ * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set)+ */+ set(name: string, value: string): void;+ /**+ * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns undefined. Key/value pairs are sorted by the values of the UTF-16 code units of the keys. This method uses a stable sorting algorithm (i.e., the relative order between key/value pairs with equal keys will be preserved).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort)+ */+ sort(): void;+ entries(): IterableIterator<[+ key: string,+ value: string+ ]>;+ keys(): IterableIterator<string>;+ values(): IterableIterator<string>;+ forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void;+ /*function toString() { [native code] }*/+ toString(): string;+ [Symbol.iterator](): IterableIterator<[+ key: string,+ value: string+ ]>;+}+/**+ * The **`URLPattern`** interface of the URL Pattern API matches URLs or parts of URLs against a pattern. The pattern can contain capturing groups that extract parts of the matched URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern)+ */+declare class URLPattern {+ constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions);+ /**+ * The **`protocol`** read-only property of the URLPattern interface is a string containing the pattern used to match the protocol part of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/protocol)+ */+ get protocol(): string;+ /**+ * The **`username`** read-only property of the URLPattern interface is a string containing the pattern used to match the username part of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/username)+ */+ get username(): string;+ /**+ * The **`password`** read-only property of the URLPattern interface is a string containing the pattern used to match the password part of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/password)+ */+ get password(): string;+ /**+ * The **`hostname`** read-only property of the URLPattern interface is a string containing the pattern used to match the hostname part of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hostname)+ */+ get hostname(): string;+ /**+ * The **`port`** read-only property of the URLPattern interface is a string containing the pattern used to match the port part of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/port)+ */+ get port(): string;+ /**+ * The **`pathname`** read-only property of the URLPattern interface is a string containing the pattern used to match the pathname part of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/pathname)+ */+ get pathname(): string;+ /**+ * The **`search`** read-only property of the URLPattern interface is a string containing the pattern used to match the search part of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/search)+ */+ get search(): string;+ /**+ * The **`hash`** read-only property of the URLPattern interface is a string containing the pattern used to match the fragment part of a URL.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hash)+ */+ get hash(): string;+ /**+ * The **`hasRegExpGroups`** read-only property of the URLPattern interface is a boolean indicating whether or not any of the URLPattern components contain regular expression capturing groups.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hasRegExpGroups)+ */+ get hasRegExpGroups(): boolean;+ /**+ * The **`test()`** method of the URLPattern interface takes a URL string or object of URL parts, and returns a boolean indicating if the given input matches the current pattern.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/test)+ */+ test(input?: (string | URLPatternInit), baseURL?: string): boolean;+ /**+ * The **`exec()`** method of the URLPattern interface takes a URL or object of URL parts, and returns either an object containing the results of matching the URL to the pattern, or null if the URL does not match the pattern.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/exec)+ */+ exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null;+}+interface URLPatternInit {+ protocol?: string;+ username?: string;+ password?: string;+ hostname?: string;+ port?: string;+ pathname?: string;+ search?: string;+ hash?: string;+ baseURL?: string;+}+interface URLPatternComponentResult {+ input: string;+ groups: Record<string, string>;+}+interface URLPatternResult {+ inputs: (string | URLPatternInit)[];+ protocol: URLPatternComponentResult;+ username: URLPatternComponentResult;+ password: URLPatternComponentResult;+ hostname: URLPatternComponentResult;+ port: URLPatternComponentResult;+ pathname: URLPatternComponentResult;+ search: URLPatternComponentResult;+ hash: URLPatternComponentResult;+}+interface URLPatternOptions {+ ignoreCase?: boolean;+}+/**+ * A **`CloseEvent`** is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent)+ */+declare class CloseEvent extends Event {+ constructor(type: string, initializer?: CloseEventInit);+ /**+ * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code)+ */+ readonly code: number;+ /**+ * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason)+ */+ readonly reason: string;+ /**+ * The **`wasClean`** read-only property of the CloseEvent interface returns true if the connection closed cleanly.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean)+ */+ readonly wasClean: boolean;+}+interface CloseEventInit {+ bubbles?: boolean;+ cancelable?: boolean;+ composed?: boolean;+ code?: number;+ reason?: string;+ wasClean?: boolean;+}+type WebSocketEventMap = {+ close: CloseEvent;+ message: MessageEvent;+ open: Event;+ error: ErrorEvent;+};+/**+ * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)+ */+declare var WebSocket: {+ prototype: WebSocket;+ new (url: string, protocols?: (string[] | string)): WebSocket;+ readonly READY_STATE_CONNECTING: number;+ readonly CONNECTING: number;+ readonly READY_STATE_OPEN: number;+ readonly OPEN: number;+ readonly READY_STATE_CLOSING: number;+ readonly CLOSING: number;+ readonly READY_STATE_CLOSED: number;+ readonly CLOSED: number;+};+/**+ * The **`WebSocket`** object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)+ */+interface WebSocket extends EventTarget<WebSocketEventMap> {+ accept(options?: WebSocketAcceptOptions): void;+ /**+ * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of bufferedAmount by the number of bytes needed to contain the data. If the data can't be sent (for example, because it needs to be buffered but the buffer is full), the socket is closed automatically. The browser will throw an exception if you call send() when the connection is in the CONNECTING state. If you call send() when the connection is in the CLOSING or CLOSED states, the browser will silently discard the data.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send)+ */+ send(message: (ArrayBuffer | ArrayBufferView) | string): void;+ /**+ * The **`WebSocket.close()`** method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close)+ */+ close(code?: number, reason?: string): void;+ serializeAttachment(attachment: any): void;+ deserializeAttachment(): any | null;+ /**+ * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState)+ */+ readyState: number;+ /**+ * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url)+ */+ url: string | null;+ /**+ * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object, or the empty string if no connection is established.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol)+ */+ protocol: string | null;+ /**+ * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions)+ */+ extensions: string | null;+ /**+ * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType)+ */+ binaryType: "blob" | "arraybuffer";+}+interface WebSocketAcceptOptions {+ /**+ * When set to `true`, receiving a server-initiated WebSocket Close frame will not+ * automatically send a reciprocal Close frame, leaving the connection in a half-open+ * state. This is useful for proxying scenarios where you need to coordinate closing+ * both sides independently. Defaults to `false` when the+ * `no_web_socket_half_open_by_default` compatibility flag is enabled.+ */+ allowHalfOpen?: boolean;+}+declare const WebSocketPair: {+ new (): {+ 0: WebSocket;+ 1: WebSocket;+ };+};+interface SqlStorage {+ exec<T extends Record<string, SqlStorageValue>>(query: string, ...bindings: any[]): SqlStorageCursor<T>;+ get databaseSize(): number;+ Cursor: typeof SqlStorageCursor;+ Statement: typeof SqlStorageStatement;+}+declare abstract class SqlStorageStatement {+}+type SqlStorageValue = ArrayBuffer | string | number | null;+declare abstract class SqlStorageCursor<T extends Record<string, SqlStorageValue>> {+ next(): {+ done?: false;+ value: T;+ } | {+ done: true;+ value?: never;+ };+ toArray(): T[];+ one(): T;+ raw<U extends SqlStorageValue[]>(): IterableIterator<U>;+ columnNames: string[];+ get rowsRead(): number;+ get rowsWritten(): number;+ [Symbol.iterator](): IterableIterator<T>;+}+interface Socket {+ get readable(): ReadableStream;+ get writable(): WritableStream;+ get closed(): Promise<void>;+ get opened(): Promise<SocketInfo>;+ get upgraded(): boolean;+ get secureTransport(): "on" | "off" | "starttls";+ close(): Promise<void>;+ startTls(options?: TlsOptions): Socket;+}+interface SocketOptions {+ secureTransport?: string;+ allowHalfOpen: boolean;+ highWaterMark?: (number | bigint);+}+interface SocketAddress {+ hostname: string;+ port: number;+}+interface TlsOptions {+ expectedServerHostname?: string;+}+interface SocketInfo {+ remoteAddress?: string;+ localAddress?: string;+}+/**+ * The **`EventSource`** interface is web content's interface to server-sent events.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource)+ */+declare class EventSource extends EventTarget {+ constructor(url: string, init?: EventSourceEventSourceInit);+ /**+ * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed).+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)+ */+ close(): void;+ /**+ * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)+ */+ get url(): string;+ /**+ * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)+ */+ get withCredentials(): boolean;+ /**+ * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)+ */+ get readyState(): number;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */+ get onopen(): any | null;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */+ set onopen(value: any | null);+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */+ get onmessage(): any | null;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */+ set onmessage(value: any | null);+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */+ get onerror(): any | null;+ /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */+ set onerror(value: any | null);+ static readonly CONNECTING: number;+ static readonly OPEN: number;+ static readonly CLOSED: number;+ static from(stream: ReadableStream): EventSource;+}+interface EventSourceEventSourceInit {+ withCredentials?: boolean;+ fetcher?: Fetcher;+}+interface ExecOutput {+ readonly stdout: ArrayBuffer;+ readonly stderr: ArrayBuffer;+ readonly exitCode: number;+}+interface ContainerExecOptions {+ cwd?: string;+ env?: Record<string, string>;+ user?: string;+ signal?: AbortSignal;+ pty?: boolean | ContainerExecPtyOptions;+ stdin?: ReadableStream | "pipe";+ stdout?: "pipe" | "ignore";+ stderr?: "pipe" | "ignore" | "combined";+}+interface ContainerExecPtyOptions {+ cols?: number;+ rows?: number;+}+interface ExecProcess {+ readonly stdin: WritableStream | null;+ readonly stdout: ReadableStream | null;+ readonly stderr: ReadableStream | null;+ readonly pid: number;+ readonly isPty: boolean;+ readonly exitCode: Promise<number>;+ output(): Promise<ExecOutput>;+ kill(signal?: number): void;+ resize(cols: number, rows: number): void;+}+interface Container {+ get running(): boolean;+ get images(): Record<string, string>;+ start(options?: ContainerStartupOptions): void;+ monitor(): Promise<void>;+ destroy(error?: any): Promise<void>;+ signal(signo: number): void;+ getTcpPort(port: number): Fetcher;+ setInactivityTimeout(durationMs: number | bigint): Promise<void>;+ interceptOutboundHttp(addr: string, binding: Fetcher): Promise<void>;+ interceptAllOutboundHttp(binding: Fetcher): Promise<void>;+ snapshotContainer(options: ContainerSnapshotOptions): Promise<ContainerSnapshot>;+ interceptOutboundHttps(addr: string, binding: Fetcher): Promise<void>;+ exec(cmd: string[], options?: ContainerExecOptions): Promise<ExecProcess>;+ inspect(): Promise<ContainerInfo | null>;+}+interface ContainerDirectorySnapshot {+ id: string;+ size: number;+ dir: string;+ name?: string;+}+type ContainerDirectorySnapshotRestoreParams = {+ snapshot: ContainerDirectorySnapshot;+ mountPoint?: string;+} | {+ snapshot?: undefined;+ mountPoint: string;+};+interface ContainerSnapshot {+ id: string;+ size: number;+ name?: string;+}+interface ContainerSnapshotRestoreParams {+ id: string;+}+interface ContainerSnapshotOptions {+ name?: string;+}+type ContainerStartupOptions = {+ entrypoint?: string[];+ enableInternet: boolean;+ env?: Record<string, string>;+ instance?: "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | ContainerStartResources;+ labels?: Record<string, string>;+ directorySnapshots?: ContainerDirectorySnapshotRestoreParams[];+} & ({+ image: string;+ containerSnapshot?: never;+} | {+ image?: never;+ containerSnapshot?: ContainerSnapshotRestoreParams;+});+interface ContainerInfo {+ labels: Record<string, string>;+ image: string;+}+interface ContainerStartResources {+ vcpu: number;+ memoryMib: number;+ diskMb: number;+}+/**+ * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort)+ */+declare abstract class MessagePort extends EventTarget {+ /**+ * The **`postMessage()`** method of the MessagePort interface sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage)+ */+ postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void;+ /**+ * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. This stops the flow of messages to that port.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close)+ */+ close(): void;+ /**+ * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.addEventListener; it is implied when using onmessage.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start)+ */+ start(): void;+ get onmessage(): any | null;+ set onmessage(value: any | null);+}+/**+ * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel)+ */+declare class MessageChannel {+ constructor();+ /**+ * The **`port1`** read-only property of the MessageChannel interface returns the first port of the message channel — the port attached to the context that originated the channel.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1)+ */+ readonly port1: MessagePort;+ /**+ * The **`port2`** read-only property of the MessageChannel interface returns the second port of the message channel — the port attached to the context at the other end of the channel, which the message is initially sent to.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2)+ */+ readonly port2: MessagePort;+}+interface MessagePortPostMessageOptions {+ transfer?: any[];+}+type LoopbackForExport<T extends (new (...args: any[]) => Rpc.EntrypointBranded) | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub<InstanceType<T>> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass<InstanceType<T>> : T extends ExportedHandler<any, any, any> ? LoopbackServiceStub<undefined> : undefined;+type LoopbackServiceStub<T extends Rpc.WorkerEntrypointBranded | undefined = undefined> = Fetcher<T> & (T extends CloudflareWorkersModule.WorkerEntrypoint<any, infer Props> ? (opts: {+ props?: Props;+}) => Fetcher<T> : (opts: {+ props?: any;+}) => Fetcher<T>);+type LoopbackDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined = undefined> = DurableObjectClass<T> & (T extends CloudflareWorkersModule.DurableObject<any, infer Props> ? (opts: {+ props?: Props;+}) => DurableObjectClass<T> : (opts: {+ props?: any;+}) => DurableObjectClass<T>);+interface LoopbackDurableObjectNamespace extends DurableObjectNamespace {+}+interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace {+}+interface SyncKvStorage {+ get<T = unknown>(key: string): T | undefined;+ list<T = unknown>(options?: SyncKvListOptions): Iterable<[+ string,+ T+ ]>;+ put<T>(key: string, value: T): void;+ delete(key: string): boolean;+}+interface SyncKvListOptions {+ start?: string;+ startAfter?: string;+ end?: string;+ prefix?: string;+ reverse?: boolean;+ limit?: number;+}+interface WorkerStub {+ getEntrypoint<T extends Rpc.WorkerEntrypointBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): Fetcher<T>;+ getDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass<T>;+}+interface WorkerStubEntrypointOptions {+ props?: any;+ limits?: workerdResourceLimits;+}+interface WorkerLoader {+ get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise<WorkerLoaderWorkerCode>): WorkerStub;+ load(code: WorkerLoaderWorkerCode): WorkerStub;+}+interface WorkerLoaderModule {+ js?: string;+ cjs?: string;+ text?: string;+ data?: ArrayBuffer;+ json?: any;+ py?: string;+ wasm?: ArrayBuffer | ArrayBufferView | WebAssembly.Module;+}+interface WorkerLoaderWorkerCode {+ compatibilityDate: string;+ compatibilityFlags?: string[];+ allowExperimental?: boolean;+ limits?: workerdResourceLimits;+ mainModule: string;+ modules: Record<string, string | WebAssembly.Module | WorkerLoaderModule>;+ env?: any;+ globalOutbound?: (Fetcher | null);+ tails?: Fetcher[];+ streamingTails?: Fetcher[];+}+interface workerdResourceLimits {+ cpuMs?: number;+ subRequests?: number;+}+/**+* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,+* as well as timing of subrequests and other operations.+*+* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)+*/+declare abstract class Performance {+ /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */+ get timeOrigin(): number;+ /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */+ now(): number;+ /**+ * The **`toJSON()`** method of the Performance interface is a serializer; it returns a JSON representation of the Performance object.+ *+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON)+ */+ toJSON(): object;+}+interface Tracing {+ enterSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;+ startActiveSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;+ startSpan(name: string): Span;+ getActiveSpan(): Span | undefined;+ Span: typeof Span;+}+declare abstract class Span {+ get isTraced(): boolean;+ setAttribute(key: string, value: boolean | number | string): this;+ setAttributes(attributes: Record<string, boolean | number | string | undefined>): this;+ recordException(exception: string | {+ code: string | number;+ name?: string;+ message?: string;+ stack?: string;+ } | {+ code?: string | number;+ name: string;+ message?: string;+ stack?: string;+ } | {+ code?: string | number;+ name?: string;+ message: string;+ stack?: string;+ }): void;+ end(): void;+}+/**+ * Represents the identity of a user authenticated via Cloudflare Access.+ * This matches the result of calling /cdn-cgi/access/get-identity.+ *+ * The exact structure of the returned object depends on the identity provider+ * configuration for the Access application. The fields below represent commonly+ * available properties, but additional provider-specific fields may be present.+ */+interface CloudflareAccessIdentity extends Record<string, unknown> {+ /** The user's email address, if available from the identity provider. */+ email?: string;+ /** The user's display name. */+ name?: string;+ /** The user's unique identifier. */+ user_uuid?: string;+ /** The Cloudflare account ID. */+ account_id?: string;+ /** Login timestamp (Unix epoch seconds). */+ iat?: number;+ /** The user's IP address at authentication time. */+ ip?: string;+ /** Authentication methods used (e.g., "pwd"). */+ amr?: string[];+ /** Identity provider information. */+ idp?: {+ id: string;+ type: string;+ };+ /** Geographic information about where the user authenticated. */+ geo?: {+ country: string;+ };+ /** Group memberships from the identity provider. */+ groups?: Array<{+ id: string;+ name: string;+ email?: string;+ }>;+ /** Device posture check results, keyed by check ID. */+ devicePosture?: Record<string, unknown>;+ /** True if the user connected via Cloudflare WARP. */+ is_warp?: boolean;+ /** True if the user is authenticated via Cloudflare Gateway. */+ is_gateway?: boolean;+}+// ============================================================================+// Agent Memory+//+// Public type surface for user Workers binding to an Agent Memory namespace.+// ============================================================================+/** Memory type — every memory is classified into exactly one. */+type AgentMemoryMemoryType = "fact" | "event" | "instruction" | "task";+/** Search intensity for recall. */+type AgentMemoryThinkingLevel = "low" | "medium" | "high";+/** Response verbosity for recall. */+type AgentMemoryResponseLength = "short" | "medium" | "long";+/** A conversation message passed to ingest(). */+interface AgentMemoryMessage {+ role: "system" | "user" | "assistant";+ content: string;+ /** Optional message timestamp. */+ timestamp?: Date;+}+/** Raw memory content passed to remember(). */+interface AgentMemoryIncomingMemory {+ /** Raw memory content. The service classifies and summarizes automatically. */+ content: string;+ /** Optional session identifier to associate with this memory. */+ sessionId?: string | null | undefined;+}+/** A stored memory returned from remember(), get(), and delete(). */+interface AgentMemoryMemory {+ /** Memory ID. */+ id: string;+ /** Memory type. */+ type: AgentMemoryMemoryType;+ /** Text summary. */+ summary: string;+ /** Memory text. */+ content: string;+ /** Session that created this memory. */+ sessionId: string | null;+ /** Memory creation time. */+ createdAt: Date;+ /** Memory last-update time. */+ updatedAt: Date;+}+/** Single entry in a list() response. Same shape as Memory minus full content. */+type AgentMemoryMemoryListEntry = Omit<AgentMemoryMemory, "content">;+/** A scored memory candidate in a recall result. */+interface AgentMemoryScoredCandidate {+ /** Candidate ID. */+ id: string;+ /** Text summary. */+ summary: string;+ /** Session that created this candidate, when known. */+ sessionId: string | null;+ /** Relevance score (higher is better). Comparable only within a single query. */+ score: number;+}+/** Options for the ingest() method. */+interface AgentMemoryIngestOptions {+ /** Session identifier to associate with memories created during ingestion. */+ sessionId?: string | null | undefined;+}+/** Options for the getSummary() method. */+interface AgentMemoryGetSummaryOptions {+ /** Session identifier to retrieve session summary for. */+ sessionId?: string | null | undefined;+}+/** Response from the getSummary() method. */+interface AgentMemoryGetSummaryResponse {+ /** Markdown summary. */+ summary: string;+}+/**+ * Options for the recall() method.+ *+ * `referenceDate` accepts a Date object, an ISO-8601 date string+ * (YYYY-MM-DD), or a full ISO-8601 datetime string. When provided, this+ * date is used as "today" for resolving relative time references+ * ("how many days ago", "last week") instead of the server's wall-clock time.+ */+interface AgentMemoryRecallOptions {+ /** Recall intensity: "low" (default), "medium", or "high". */+ thinkingLevel?: AgentMemoryThinkingLevel;+ /** Response verbosity: "short", "medium" (default), or "long". */+ responseLength?: AgentMemoryResponseLength;+ /** Temporal anchor for date arithmetic. */+ referenceDate?: Date | string;+}+/** Response from the recall() method. */+interface AgentMemoryRecallResult {+ /** Number of memories retrieved. */+ count: number;+ /** LLM-generated answer synthesizing the matching memories. */+ answer: string;+ /** Matching memories ranked by relevance. */+ candidates: AgentMemoryScoredCandidate[];+}+/**+ * Options for the list() method.+ *+ * `cursor` is the opaque continuation token returned by the previous page;+ * pass it back unchanged to fetch the next page. `sessionId` and `type`+ * are exact-match filters; combining them is allowed.+ */+interface AgentMemoryListMemoriesOptions {+ /** Maximum number of memories to return. Default 20, max 500. */+ limit?: number;+ /** Opaque cursor from a previous page. */+ cursor?: string;+ /** Exact-match session filter. */+ sessionId?: string;+ /** Exact-match memory-type filter. */+ type?: AgentMemoryMemoryType;+}+/** Response from the list() method. */+interface AgentMemoryListMemoriesResult {+ memories: AgentMemoryMemoryListEntry[];+ /** Continuation cursor; absent when this page exhausted the result set. */+ cursor?: string;+}+/**+ * A single Agent Memory profile, scoped to a profile name.+ *+ * Returned by {@link AgentMemoryNamespace.getProfile}.+ */+declare abstract class AgentMemoryProfile {+ /**+ * Retrieve a memory by ID.+ *+ * @param memoryId - ULID of the memory to retrieve.+ * @throws if the memory does not exist.+ */+ get(memoryId: string): Promise<AgentMemoryMemory>;+ /**+ * Delete a memory by ID.+ *+ * Removes the memory and any source messages linked by the memory's+ * source message IDs.+ *+ * @param memoryId - ULID of the memory to delete.+ * @throws if the memory does not exist.+ */+ delete(memoryId: string): Promise<AgentMemoryMemory>;+ /**+ * Store a memory in this profile. The content is automatically classified,+ * summarized, and indexed.+ *+ * @param memory - Raw memory content to persist.+ */+ remember(memory: AgentMemoryIncomingMemory): Promise<AgentMemoryMemory>;+ /**+ * Extract memories from a conversation.+ *+ * @param messages - Conversation messages to extract memories from.+ * @param options - Optional ingest options.+ */+ ingest(messages: Iterable<AgentMemoryMessage>, options?: AgentMemoryIngestOptions): Promise<void>;+ /**+ * Get a profile summary.+ *+ * @param options - Optional getSummary options.+ */+ getSummary(options?: AgentMemoryGetSummaryOptions): Promise<AgentMemoryGetSummaryResponse>;+ /**+ * Recall memories in this profile.+ *+ * @param query - Recall query matched against memory content and keywords.+ * @param options - Optional recall parameters.+ * @returns Matching memories with relevance scores and a synthesized answer.+ */+ recall(query: string, options?: AgentMemoryRecallOptions): Promise<AgentMemoryRecallResult>;+ /**+ * List active memories in this profile.+ *+ * Returns a paginated, filterable view of stored memories. Superseded+ * versions are excluded. Use the returned `cursor` (when present) to+ * fetch the next page.+ *+ * @param options - Optional pagination and filter options.+ */+ list(options?: AgentMemoryListMemoriesOptions): Promise<AgentMemoryListMemoriesResult>;+ /**+ * Soft-delete every memory and message in this profile that is tagged+ * with `sessionId`.+ *+ * Idempotent: deleting a sessionId that has no rows is a no-op.+ *+ * @param sessionId - Session to delete.+ */+ deleteSession(sessionId: string): Promise<void>;+}+/**+ * Namespace-level Agent Memory binding.+ *+ * Used as the type of an `env.MEMORY`-style binding backed by the Agent+ * Memory product.+ *+ * @example+ * ```ts+ * export default {+ * async fetch(_request: Request, env: Env): Promise<Response> {+ * const profile = await env.MEMORY.getProfile("wrangler-e2e");+ * const summary = await profile.getSummary();+ * return Response.json(summary);+ * },+ * };+ * ```+ */+declare abstract class AgentMemoryNamespace {+ /**+ * Get a memory profile by name. Profiles are isolated by namespace and+ * addressed by a compound key (namespaceId:profileName).+ *+ * @param profileName - Profile name (validated against naming rules).+ * @returns RPC target for interacting with the profile.+ */+ getProfile(profileName: string): Promise<AgentMemoryProfile>;+ /**+ * Soft-delete a profile and schedule deferred purge. Marks all+ * memories and messages as deleted.+ *+ * @param profileName - Name of the profile to delete.+ */+ deleteProfile(profileName: string): Promise<void>;+}+// ============ AI Search Error Interfaces ============+interface AiSearchInternalError extends Error {+}+interface AiSearchNotFoundError extends Error {+}+// ============ AI Search Common Types ============+/** A single message in a conversation-style search or chat request. */+type AiSearchMessage = {+ role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';+ content: string | null;+};+/**+ * Common shape for `ai_search_options` used by both single-instance and multi-instance requests.+ * Contains retrieval, query rewrite, reranking, and cache sub-options.+ */+type AiSearchOptions = {+ retrieval?: {+ /** Which retrieval backend to use. Defaults to the instance's configured index_method. */+ retrieval_type?: 'vector' | 'keyword' | 'hybrid';+ /** Fusion method for combining vector + keyword results. */+ fusion_method?: 'max' | 'rrf';+ /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */+ keyword_match_mode?: 'and' | 'or';+ /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */+ match_threshold?: number;+ /** Maximum number of results to return (1-50). Default 10. */+ max_num_results?: number;+ /** Vectorize metadata filters applied to the search. */+ filters?: VectorizeVectorMetadataFilter;+ /** Number of surrounding chunks to include for context (0-3). Default 0. */+ context_expansion?: number;+ /** If true, return only item metadata without chunk text. */+ metadata_only?: boolean;+ /** If true (default), return empty results on retrieval failure instead of throwing. */+ return_on_failure?: boolean;+ /** Boost results by metadata field values. Max 3 entries. */+ boost_by?: Array<{+ field: string;+ direction?: 'asc' | 'desc' | 'exists' | 'not_exists';+ }>;+ [key: string]: unknown;+ };+ query_rewrite?: {+ enabled?: boolean;+ model?: string;+ rewrite_prompt?: string;+ [key: string]: unknown;+ };+ reranking?: {+ enabled?: boolean;+ model?: string;+ /** Match threshold (0-1, default 0.4) */+ match_threshold?: number;+ [key: string]: unknown;+ };+ cache?: {+ enabled?: boolean;+ cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';+ };+ [key: string]: unknown;+};+// ============ AI Search Request Types ============+/**+ * Request body for single-instance search.+ * Exactly one of `query` or `messages` must be provided.+ */+type AiSearchSearchRequest = {+ /** Simple query string. */+ query: string;+ messages?: never;+ ai_search_options?: AiSearchOptions;+} | {+ query?: never;+ /** Conversation-style input. At least one user message with non-empty content is required. */+ messages: AiSearchMessage[];+ ai_search_options?: AiSearchOptions;+};+type AiSearchChatCompletionsRequest = {+ messages: AiSearchMessage[];+ model?: string;+ stream?: boolean;+ ai_search_options?: AiSearchOptions;+ [key: string]: unknown;+};+// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============+/** `ai_search_options` shape for multi-instance requests — requires `instance_ids`. */+type AiSearchMultiSearchOptions = AiSearchOptions & {+ /** Instance IDs to search across (1-10). */+ instance_ids: string[];+};+/**+ * Request for searching across multiple instances within a namespace.+ * `ai_search_options` is required and must include `instance_ids`.+ * Exactly one of `query` or `messages` must be provided.+ */+type AiSearchMultiSearchRequest = {+ /** Simple query string. */+ query: string;+ messages?: never;+ ai_search_options: AiSearchMultiSearchOptions;+} | {+ query?: never;+ /** Conversation-style input. */+ messages: AiSearchMessage[];+ ai_search_options: AiSearchMultiSearchOptions;+};+/** A search result chunk tagged with the instance it originated from. */+type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & {+ instance_id: string;+};+/** Describes a per-instance error during a multi-instance operation. */+type AiSearchMultiSearchError = {+ instance_id: string;+ message: string;+};+/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */+type AiSearchMultiSearchResponse = {+ search_query: string;+ chunks: AiSearchMultiSearchChunk[];+ errors?: AiSearchMultiSearchError[];+};+/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */+type AiSearchMultiChatCompletionsRequest = Omit<AiSearchChatCompletionsRequest, 'ai_search_options'> & {+ ai_search_options: AiSearchMultiSearchOptions;+};+/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */+type AiSearchMultiChatCompletionsResponse = Omit<AiSearchChatCompletionsResponse, 'chunks'> & {+ chunks: AiSearchMultiSearchChunk[];+ errors?: AiSearchMultiSearchError[];+};+// ============ AI Search Response Types ============+type AiSearchSearchResponse = {+ search_query: string;+ chunks: Array<{+ id: string;+ type: string;+ /** Match score (0-1) */+ score: number;+ text: string;+ item: {+ timestamp?: number;+ key: string;+ metadata?: Record<string, unknown>;+ };+ scoring_details?: {+ /** Keyword match score (0-1) */+ keyword_score?: number;+ /** Vector similarity score (0-1) */+ vector_score?: number;+ /** Keyword rank position */+ keyword_rank?: number;+ /** Vector rank position */+ vector_rank?: number;+ /** Reranking model score */+ reranking_score?: number;+ /** Fusion method used to combine results */+ fusion_method?: 'rrf' | 'max';+ [key: string]: unknown;+ };+ }>;+};+type AiSearchChatCompletionsResponse = {+ id?: string;+ object?: string;+ model?: string;+ choices: Array<{+ index?: number;+ message: {+ role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';+ content: string | null;+ [key: string]: unknown;+ };+ [key: string]: unknown;+ }>;+ chunks: AiSearchSearchResponse['chunks'];+ [key: string]: unknown;+};+type AiSearchStatsResponse = {+ queued?: number;+ running?: number;+ completed?: number;+ error?: number;+ skipped?: number;+ outdated?: number;+ last_activity?: string;+ /** Storage engine statistics. */+ engine?: {+ vectorize?: {+ vectorsCount: number;+ dimensions: number;+ };+ r2?: {+ payloadSizeBytes: number;+ metadataSizeBytes: number;+ objectCount: number;+ };+ };+};+// ============ AI Search Instance Info Types ============+type AiSearchInstanceInfo = {+ id: string;+ type?: 'r2' | 'web-crawler' | string;+ source?: string;+ source_params?: unknown;+ paused?: boolean;+ status?: string;+ namespace?: string;+ created_at?: string;+ modified_at?: string;+ token_id?: string;+ ai_gateway_id?: string;+ rewrite_query?: boolean;+ reranking?: boolean;+ embedding_model?: string;+ ai_search_model?: string;+ rewrite_model?: string;+ reranking_model?: string;+ /** @deprecated Use index_method instead. */+ hybrid_search_enabled?: boolean;+ /** Controls which storage backends are active. */+ index_method?: {+ vector?: boolean;+ keyword?: boolean;+ };+ /** Fusion method for combining vector and keyword results. */+ fusion_method?: 'max' | 'rrf';+ indexing_options?: {+ keyword_tokenizer?: 'porter' | 'trigram';+ } | null;+ retrieval_options?: {+ keyword_match_mode?: 'and' | 'or';+ boost_by?: Array<{+ field: string;+ direction?: 'asc' | 'desc' | 'exists' | 'not_exists';+ }>;+ } | null;+ chunk?: boolean;+ chunk_size?: number;+ chunk_overlap?: number;+ score_threshold?: number;+ max_num_results?: number;+ cache?: boolean;+ cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';+ custom_metadata?: Array<{+ field_name: string;+ data_type: 'text' | 'number' | 'boolean' | 'datetime';+ }>;+ /** Sync interval in seconds. */+ sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;+ metadata?: Record<string, unknown>;+ [key: string]: unknown;+};+/** Pagination, search, and ordering parameters for listing instances within a namespace. */+type AiSearchListInstancesParams = {+ page?: number;+ per_page?: number;+ /** Search instances by ID. */+ search?: string;+ /** Field to sort by. */+ order_by?: 'created_at';+ /** Sort direction. */+ order_by_direction?: 'asc' | 'desc';+};+type AiSearchListResponse = {+ result: AiSearchInstanceInfo[];+ result_info?: {+ count: number;+ page: number;+ per_page: number;+ total_count: number;+ };+};+// ============ AI Search Config Types ============+type AiSearchConfig = {+ /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */+ id: string;+ /** Instance type. Omit to create with built-in storage. */+ type?: 'r2' | 'web-crawler' | string;+ /** Source URL (required for web-crawler type). */+ source?: string;+ source_params?: unknown;+ /** Token ID (UUID format) */+ token_id?: string;+ ai_gateway_id?: string;+ /** Enable query rewriting (default false) */+ rewrite_query?: boolean;+ /** Enable reranking (default false) */+ reranking?: boolean;+ embedding_model?: string;+ ai_search_model?: string;+ rewrite_model?: string;+ reranking_model?: string;+ /** @deprecated Use index_method instead. */+ hybrid_search_enabled?: boolean;+ /** Controls which storage backends are used during indexing. Defaults to vector-only. */+ index_method?: {+ vector?: boolean;+ keyword?: boolean;+ };+ /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */+ fusion_method?: 'max' | 'rrf';+ indexing_options?: {+ keyword_tokenizer?: 'porter' | 'trigram';+ } | null;+ retrieval_options?: {+ keyword_match_mode?: 'and' | 'or';+ boost_by?: Array<{+ field: string;+ direction?: 'asc' | 'desc' | 'exists' | 'not_exists';+ }>;+ } | null;+ chunk?: boolean;+ chunk_size?: number;+ chunk_overlap?: number;+ /** Minimum similarity score (0-1) for a result to be included. */+ score_threshold?: number;+ max_num_results?: number;+ cache?: boolean;+ /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */+ cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';+ custom_metadata?: Array<{+ field_name: string;+ data_type: 'text' | 'number' | 'boolean' | 'datetime';+ }>;+ namespace?: string;+ /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */+ sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;+ metadata?: Record<string, unknown>;+ [key: string]: unknown;+};+// ============ AI Search Item Types ============+type AiSearchItemInfo = {+ id: string;+ key: string;+ status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated';+ next_action?: 'INDEX' | 'DELETE' | null;+ error?: string;+ checksum?: string;+ namespace?: string;+ chunks_count?: number | null;+ file_size?: number | null;+ source_id?: string | null;+ last_seen_at?: string;+ created_at?: string;+ metadata?: Record<string, unknown>;+ [key: string]: unknown;+};+type AiSearchItemContentResult = {+ body: ReadableStream;+ contentType: string;+ filename: string;+ size: number;+};+type AiSearchUploadItemOptions = {+ metadata?: Record<string, unknown>;+};+type AiSearchListItemsParams = {+ page?: number;+ per_page?: number;+ /** Search items by key name. */+ search?: string;+ /** Sort order for results. */+ sort_by?: 'status' | 'modified_at';+ /** Filter items by processing status. */+ status?: 'queued' | 'running' | 'completed' | 'error' | 'skipped' | 'outdated';+ /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */+ source?: string;+ /** JSON-encoded Vectorize filter for metadata filtering. */+ metadata_filter?: string;+ /** Filter items by their unique ID. Returns at most one item. */+ item_id?: string;+ /**+ * Filter items by their exact key (object key / filename). Keys are unique+ * per source, so combine with `source` to disambiguate across data sources.+ */+ key?: string;+};+type AiSearchListItemsResponse = {+ result: AiSearchItemInfo[];+ result_info?: {+ count: number;+ page: number;+ per_page: number;+ total_count: number;+ };+};+// ============ AI Search Item Logs Types ============+type AiSearchItemLogsParams = {+ /** Maximum number of log entries to return (1-100, default 50). */+ limit?: number;+ /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */+ cursor?: string;+};+type AiSearchItemLog = {+ timestamp: string;+ action: string;+ message: string;+ fileKey?: string;+ chunkCount?: number;+ processingTimeMs?: number;+ errorType?: string;+};+/** Paginated response for item processing logs (cursor-based). */+type AiSearchItemLogsResponse = {+ result: AiSearchItemLog[];+ result_info: {+ count: number;+ per_page: number;+ cursor: string | null;+ truncated: boolean;+ };+};+// ============ AI Search Item Chunks Types ============+type AiSearchItemChunksParams = {+ /** Maximum number of chunks to return (1-100, default 20). */+ limit?: number;+ /** Offset into the chunks list (default 0). */+ offset?: number;+};+/** A single indexed chunk belonging to an item, including its text content and byte range. */+type AiSearchItemChunk = {+ id: string;+ text: string;+ start_byte: number;+ end_byte: number;+ item?: {+ timestamp?: number;+ key: string;+ metadata?: Record<string, unknown>;+ };+};+/** Paginated response for item chunks (offset-based). */+type AiSearchItemChunksResponse = {+ result: AiSearchItemChunk[];+ result_info: {+ count: number;+ total: number;+ limit: number;+ offset: number;+ };+};+// ============ AI Search Job Types ============+type AiSearchJobInfo = {+ id: string;+ source: 'user' | 'schedule';+ description?: string;+ last_seen_at?: string;+ started_at?: string;+ ended_at?: string;+ end_reason?: string;+};+type AiSearchJobLog = {+ id: number;+ message: string;+ message_type: number;+ created_at: number;+};+type AiSearchCreateJobParams = {+ description?: string;+};+type AiSearchListJobsParams = {+ page?: number;+ per_page?: number;+};+type AiSearchListJobsResponse = {+ result: AiSearchJobInfo[];+ result_info?: {+ count: number;+ page: number;+ per_page: number;+ total_count: number;+ };+};+type AiSearchJobLogsParams = {+ page?: number;+ per_page?: number;+};+type AiSearchJobLogsResponse = {+ result: AiSearchJobLog[];+ result_info?: {+ count: number;+ page: number;+ per_page: number;+ total_count: number;+ };+};+// ============ AI Search Sub-Service Classes ============+/**+ * Single item service for an AI Search instance.+ * Provides info, download, sync, logs, and chunks operations on a specific item.+ */+declare abstract class AiSearchItem {+ /** Get metadata about this item. */+ info(): Promise<AiSearchItemInfo>;+ /**+ * Download the item's content.+ * @returns Object with body stream, content type, filename, and size.+ */+ download(): Promise<AiSearchItemContentResult>;+ /**+ * Trigger re-indexing of this item.+ * @returns The updated item info.+ */+ sync(): Promise<AiSearchItemInfo>;+ /**+ * Retrieve processing logs for this item (cursor-based pagination).+ * @param params Optional pagination parameters (limit, cursor).+ * @returns Paginated log entries for this item.+ */+ logs(params?: AiSearchItemLogsParams): Promise<AiSearchItemLogsResponse>;+ /**+ * List indexed chunks for this item (offset-based pagination).+ * @param params Optional pagination parameters (limit, offset).+ * @returns Paginated chunk entries for this item.+ */+ chunks(params?: AiSearchItemChunksParams): Promise<AiSearchItemChunksResponse>;+}+/**+ * Items collection service for an AI Search instance.+ * Provides list, upload, and access to individual items.+ */+declare abstract class AiSearchItems {+ /** List items in this instance. */+ list(params?: AiSearchListItemsParams): Promise<AiSearchListItemsResponse>;+ /**+ * Upload a file as an item. Behaves as an upsert: if an item with the same+ * filename already exists, it is overwritten and re-indexed.+ * @param name Filename for the uploaded item.+ * @param content File content as a ReadableStream, Blob, or string.+ * @param options Optional metadata to attach to the item.+ * @returns The created item info.+ */+ upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise<AiSearchItemInfo>;+ /**+ * Upload a file and poll until processing completes.+ * Behaves as an upsert: if an item with the same filename already exists,+ * it is overwritten and re-indexed.+ * @param name Filename for the uploaded item.+ * @param content File content as a ReadableStream, Blob, or string.+ * @param options Optional metadata and polling configuration.+ * @returns The item info after processing completes (or timeout).+ */+ uploadAndPoll(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions & {+ /** Polling interval in milliseconds (default 1000). */+ pollIntervalMs?: number;+ /** Maximum time to wait in milliseconds (default 30000). */+ timeoutMs?: number;+ }): Promise<AiSearchItemInfo>;+ /**+ * Get an item by ID.+ * @param itemId The item identifier.+ * @returns Item service for info, download, sync, logs, and chunks operations.+ */+ get(itemId: string): AiSearchItem;+ /**+ * Delete an item from the instance.+ * @param itemId The item identifier.+ */+ delete(itemId: string): Promise<void>;+}+/**+ * Single job service for an AI Search instance.+ * Provides info, logs, and cancel operations for a specific job.+ */+declare abstract class AiSearchJob {+ /** Get metadata about this job. */+ info(): Promise<AiSearchJobInfo>;+ /** Get logs for this job. */+ logs(params?: AiSearchJobLogsParams): Promise<AiSearchJobLogsResponse>;+ /**+ * Cancel a running job.+ * @returns The updated job info.+ * @throws AiSearchNotFoundError if the job does not exist.+ */+ cancel(): Promise<AiSearchJobInfo>;+}+/**+ * Jobs collection service for an AI Search instance.+ * Provides list, create, and access to individual jobs.+ */+declare abstract class AiSearchJobs {+ /** List jobs for this instance. */+ list(params?: AiSearchListJobsParams): Promise<AiSearchListJobsResponse>;+ /**+ * Create a new indexing job.+ * @param params Optional job parameters.+ * @returns The created job info.+ */+ create(params?: AiSearchCreateJobParams): Promise<AiSearchJobInfo>;+ /**+ * Get a job by ID.+ * @param jobId The job identifier.+ * @returns Job service for info, logs, and cancel operations.+ */+ get(jobId: string): AiSearchJob;+}+// ============ AI Search Binding Classes ============+/**+ * Instance-level AI Search service.+ *+ * Used as:+ * - The return type of `AiSearchNamespace.get(name)` (namespace binding)+ * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`)+ *+ * Provides search, chat, update, stats, items, and jobs operations.+ *+ * @example+ * ```ts+ * // Via namespace binding+ * const instance = env.AI_SEARCH.get("blog");+ * const results = await instance.search({+ * query: "How does caching work?",+ * });+ *+ * // Via single instance binding+ * const results = await env.BLOG_SEARCH.search({+ * messages: [{ role: "user", content: "How does caching work?" }],+ * });+ * ```+ */+declare abstract class AiSearchInstance {+ /**+ * Search the AI Search instance for relevant chunks.+ * @param params Search request with query or messages and optional AI search options.+ * @returns Search response with matching chunks and search query.+ */+ search(params: AiSearchSearchRequest): Promise<AiSearchSearchResponse>;+ /**+ * Generate chat completions with AI Search context (streaming).+ * @param params Chat completions request with stream: true.+ * @returns ReadableStream of server-sent events.+ */+ chatCompletions(params: AiSearchChatCompletionsRequest & {+ stream: true;+ }): Promise<ReadableStream>;+ /**+ * Generate chat completions with AI Search context.+ * @param params Chat completions request.+ * @returns Chat completion response with choices and RAG chunks.+ */+ chatCompletions(params: AiSearchChatCompletionsRequest): Promise<AiSearchChatCompletionsResponse>;+ /**+ * Update the instance configuration.+ * @param config Partial configuration to update.+ * @returns Updated instance info.+ */+ update(config: Partial<AiSearchConfig>): Promise<AiSearchInstanceInfo>;+ /** Get metadata about this instance. */+ info(): Promise<AiSearchInstanceInfo>;+ /**+ * Get instance statistics (item count, indexing status, etc.).+ * @returns Statistics with counts per status, last activity time, and engine details.+ */+ stats(): Promise<AiSearchStatsResponse>;+ /** Items collection — list, upload, and manage items in this instance. */+ get items(): AiSearchItems;+ /** Jobs collection — list, create, and inspect indexing jobs. */+ get jobs(): AiSearchJobs;+}+/**+ * Namespace-level AI Search service.+ *+ * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`).+ * Scoped to a single namespace. Provides dynamic instance access, creation, deletion,+ * and multi-instance search/chat operations.+ *+ * @example+ * ```ts+ * // Access an instance within the namespace+ * const blog = env.AI_SEARCH.get("blog");+ * const results = await blog.search({ query: "How does caching work?" });+ *+ * // List all instances in the namespace+ * const instances = await env.AI_SEARCH.list();+ *+ * // Create a new instance with built-in storage+ * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" });+ *+ * // Upload items into the instance+ * await tenant.items.upload("doc.pdf", fileContent);+ *+ * // Search across multiple instances+ * const multi = await env.AI_SEARCH.search({+ * query: "caching",+ * ai_search_options: { instance_ids: ["blog", "docs"] },+ * });+ *+ * // Delete an instance+ * await env.AI_SEARCH.delete("tenant-123");+ * ```+ */+declare abstract class AiSearchNamespace {+ /**+ * Get an instance by name within the bound namespace.+ * @param name Instance name.+ * @returns Instance service for search, chat, update, stats, items, and jobs.+ */+ get(name: string): AiSearchInstance;+ /**+ * List instances in the bound namespace.+ * @param params Optional pagination, search, and ordering parameters.+ * @returns Array of instance metadata with pagination info.+ */+ list(params?: AiSearchListInstancesParams): Promise<AiSearchListResponse>;+ /**+ * Create a new instance within the bound namespace.+ * @param config Instance configuration. Only `id` is required — omit `type` and `source` to create with built-in storage.+ * @returns Instance service for the newly created instance.+ *+ * @example+ * ```ts+ * // Create with built-in storage (upload items manually)+ * const instance = await env.AI_SEARCH.create({ id: "my-search" });+ *+ * // Create with web crawler source+ * const instance = await env.AI_SEARCH.create({+ * id: "docs-search",+ * type: "web-crawler",+ * source: "https://developers.cloudflare.com",+ * });+ * ```+ */+ create(config: AiSearchConfig): Promise<AiSearchInstance>;+ /**+ * Delete an instance from the bound namespace.+ * @param name Instance name to delete.+ */+ delete(name: string): Promise<void>;+ /**+ * Search across multiple instances within the bound namespace.+ * Fans out to the specified instance_ids and merges results.+ * @param params Search request with required `ai_search_options.instance_ids`.+ * @returns Search response with chunks tagged by instance_id and optional partial-failure errors.+ */+ search(params: AiSearchMultiSearchRequest): Promise<AiSearchMultiSearchResponse>;+ /**+ * Generate chat completions across multiple instances within the bound namespace (streaming).+ * Fans out to the specified instance_ids, merges context, and generates a response.+ * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`.+ * @returns ReadableStream of server-sent events.+ */+ chatCompletions(params: AiSearchMultiChatCompletionsRequest & {+ stream: true;+ }): Promise<ReadableStream>;+ /**+ * Generate chat completions across multiple instances within the bound namespace.+ * Fans out to the specified instance_ids, merges context, and generates a response.+ * @param params Chat completions request with required `ai_search_options.instance_ids`.+ * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors.+ */+ chatCompletions(params: AiSearchMultiChatCompletionsRequest): Promise<AiSearchMultiChatCompletionsResponse>;+}+type AiImageClassificationInput = {+ image: number[];+};+type AiImageClassificationOutput = {+ score?: number;+ label?: string;+}[];+declare abstract class BaseAiImageClassification {+ inputs: AiImageClassificationInput;+ postProcessedOutputs: AiImageClassificationOutput;+}+type AiImageToTextInput = {+ image: number[];+ prompt?: string;+ max_tokens?: number;+ temperature?: number;+ top_p?: number;+ top_k?: number;+ seed?: number;+ repetition_penalty?: number;+ frequency_penalty?: number;+ presence_penalty?: number;+ raw?: boolean;+ messages?: RoleScopedChatInput[];+};+type AiImageToTextOutput = {+ description: string;+};+declare abstract class BaseAiImageToText {+ inputs: AiImageToTextInput;+ postProcessedOutputs: AiImageToTextOutput;+}+type AiImageTextToTextInput = {+ image: string;+ prompt?: string;+ max_tokens?: number;+ temperature?: number;+ ignore_eos?: boolean;+ top_p?: number;+ top_k?: number;+ seed?: number;+ repetition_penalty?: number;+ frequency_penalty?: number;+ presence_penalty?: number;+ raw?: boolean;+ messages?: RoleScopedChatInput[];+};+type AiImageTextToTextOutput = {+ description: string;+};+declare abstract class BaseAiImageTextToText {+ inputs: AiImageTextToTextInput;+ postProcessedOutputs: AiImageTextToTextOutput;+}+type AiMultimodalEmbeddingsInput = {+ image: string;+ text: string[];+};+type AiIMultimodalEmbeddingsOutput = {+ data: number[][];+ shape: number[];+};+declare abstract class BaseAiMultimodalEmbeddings {+ inputs: AiImageTextToTextInput;+ postProcessedOutputs: AiImageTextToTextOutput;+}+type AiObjectDetectionInput = {+ image: number[];+};+type AiObjectDetectionOutput = {+ score?: number;+ label?: string;+}[];+declare abstract class BaseAiObjectDetection {+ inputs: AiObjectDetectionInput;+ postProcessedOutputs: AiObjectDetectionOutput;+}+type AiSentenceSimilarityInput = {+ source: string;+ sentences: string[];+};+type AiSentenceSimilarityOutput = number[];+declare abstract class BaseAiSentenceSimilarity {+ inputs: AiSentenceSimilarityInput;+ postProcessedOutputs: AiSentenceSimilarityOutput;+}+type AiAutomaticSpeechRecognitionInput = {+ audio: number[];+};+type AiAutomaticSpeechRecognitionOutput = {+ text?: string;+ words?: {+ word: string;+ start: number;+ end: number;+ }[];+ vtt?: string;+};+declare abstract class BaseAiAutomaticSpeechRecognition {+ inputs: AiAutomaticSpeechRecognitionInput;+ postProcessedOutputs: AiAutomaticSpeechRecognitionOutput;+}+type AiSummarizationInput = {+ input_text: string;+ max_length?: number;+};+type AiSummarizationOutput = {+ summary: string;+};+declare abstract class BaseAiSummarization {+ inputs: AiSummarizationInput;+ postProcessedOutputs: AiSummarizationOutput;+}+type AiTextClassificationInput = {+ text: string;+};+type AiTextClassificationOutput = {+ score?: number;+ label?: string;+}[];+declare abstract class BaseAiTextClassification {+ inputs: AiTextClassificationInput;+ postProcessedOutputs: AiTextClassificationOutput;+}+type AiTextEmbeddingsInput = {+ text: string | string[];+};+type AiTextEmbeddingsOutput = {+ shape: number[];+ data: number[][];+};+declare abstract class BaseAiTextEmbeddings {+ inputs: AiTextEmbeddingsInput;+ postProcessedOutputs: AiTextEmbeddingsOutput;+}+type RoleScopedChatInput = {+ role: "user" | "assistant" | "system" | "tool" | (string & NonNullable<unknown>);+ content: string;+ name?: string;+};+type AiTextGenerationToolLegacyInput = {+ name: string;+ description: string;+ parameters?: {+ type: "object" | (string & NonNullable<unknown>);+ properties: {+ [key: string]: {+ type: string;+ description?: string;+ };+ };+ required: string[];+ };+};+type AiTextGenerationToolInput = {+ type: "function" | (string & NonNullable<unknown>);+ function: {+ name: string;+ description: string;+ parameters?: {+ type: "object" | (string & NonNullable<unknown>);+ properties: {+ [key: string]: {+ type: string;+ description?: string;+ };+ };+ required: string[];+ };+ };+};+type AiTextGenerationFunctionsInput = {+ name: string;+ code: string;+};+type AiTextGenerationResponseFormat = {+ type: string;+ json_schema?: any;+};+type AiTextGenerationInput = {+ prompt?: string;+ raw?: boolean;+ stream?: boolean;+ max_tokens?: number;+ temperature?: number;+ top_p?: number;+ top_k?: number;+ seed?: number;+ repetition_penalty?: number;+ frequency_penalty?: number;+ presence_penalty?: number;+ messages?: RoleScopedChatInput[];+ response_format?: AiTextGenerationResponseFormat;+ tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable<unknown>);+ functions?: AiTextGenerationFunctionsInput[];+};+type AiTextGenerationToolLegacyOutput = {+ name: string;+ arguments: unknown;+};+type AiTextGenerationToolOutput = {+ id: string;+ type: "function";+ function: {+ name: string;+ arguments: string;+ };+};+type UsageTags = {+ prompt_tokens: number;+ completion_tokens: number;+ total_tokens: number;+};+type AiTextGenerationOutput = {+ response?: string;+ tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[];+ usage?: UsageTags;+};+declare abstract class BaseAiTextGeneration {+ inputs: AiTextGenerationInput;+ postProcessedOutputs: AiTextGenerationOutput;+}+type AiTextToSpeechInput = {+ prompt: string;+ lang?: string;+};+type AiTextToSpeechOutput = Uint8Array | {+ audio: string;+};+declare abstract class BaseAiTextToSpeech {+ inputs: AiTextToSpeechInput;+ postProcessedOutputs: AiTextToSpeechOutput;+}+type AiTextToImageInput = {+ prompt: string;+ negative_prompt?: string;+ height?: number;+ width?: number;+ image?: number[];+ image_b64?: string;+ mask?: number[];+ num_steps?: number;+ strength?: number;+ guidance?: number;+ seed?: number;+};+type AiTextToImageOutput = ReadableStream<Uint8Array>;+declare abstract class BaseAiTextToImage {+ inputs: AiTextToImageInput;+ postProcessedOutputs: AiTextToImageOutput;+}+type AiTranslationInput = {+ text: string;+ target_lang: string;+ source_lang?: string;+};+type AiTranslationOutput = {+ translated_text?: string;+};+declare abstract class BaseAiTranslation {+ inputs: AiTranslationInput;+ postProcessedOutputs: AiTranslationOutput;+}+/**+ * Workers AI support for OpenAI's Chat Completions API+ */+type ChatCompletionContentPartText = {+ type: "text";+ text: string;+};+type ChatCompletionContentPartImage = {+ type: "image_url";+ image_url: {+ url: string;+ detail?: "auto" | "low" | "high";+ };+};+type ChatCompletionContentPartInputAudio = {+ type: "input_audio";+ input_audio: {+ /** Base64 encoded audio data. */+ data: string;+ format: "wav" | "mp3";+ };+};+type ChatCompletionContentPartFile = {+ type: "file";+ file: {+ /** Base64 encoded file data. */+ file_data?: string;+ /** The ID of an uploaded file. */+ file_id?: string;+ filename?: string;+ };+};+type ChatCompletionContentPartRefusal = {+ type: "refusal";+ refusal: string;+};+type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPartFile;+type FunctionDefinition = {+ name: string;+ description?: string;+ parameters?: Record<string, unknown>;+ strict?: boolean | null;+};+type ChatCompletionFunctionTool = {+ type: "function";+ function: FunctionDefinition;+};+type ChatCompletionCustomToolGrammarFormat = {+ type: "grammar";+ grammar: {+ definition: string;+ syntax: "lark" | "regex";+ };+};+type ChatCompletionCustomToolTextFormat = {+ type: "text";+};+type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat;+type ChatCompletionCustomTool = {+ type: "custom";+ custom: {+ name: string;+ description?: string;+ format?: ChatCompletionCustomToolFormat;+ };+};+type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool;+type ChatCompletionMessageFunctionToolCall = {+ id: string;+ type: "function";+ function: {+ name: string;+ /** JSON-encoded arguments string. */+ arguments: string;+ };+};+type ChatCompletionMessageCustomToolCall = {+ id: string;+ type: "custom";+ custom: {+ name: string;+ input: string;+ };+};+type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall;+type ChatCompletionToolChoiceFunction = {+ type: "function";+ function: {+ name: string;+ };+};+type ChatCompletionToolChoiceCustom = {+ type: "custom";+ custom: {+ name: string;+ };+};+type ChatCompletionToolChoiceAllowedTools = {+ type: "allowed_tools";+ allowed_tools: {+ mode: "auto" | "required";+ tools: Array<Record<string, unknown>>;+ };+};+type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionToolChoiceFunction | ChatCompletionToolChoiceCustom | ChatCompletionToolChoiceAllowedTools;+type DeveloperMessage = {+ role: "developer";+ content: string | Array<{+ type: "text";+ text: string;+ }>;+ name?: string;+};+type SystemMessage = {+ role: "system";+ content: string | Array<{+ type: "text";+ text: string;+ }>;+ name?: string;+};+/**+ * Permissive merged content part used inside UserMessage arrays.+ *+ * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination+ * inside nested array items does not correctly match different branches for+ * different array elements, so the schema uses a single merged object.+ */+type UserMessageContentPart = {+ type: "text" | "image_url" | "input_audio" | "file";+ text?: string;+ image_url?: {+ url?: string;+ detail?: "auto" | "low" | "high";+ };+ input_audio?: {+ data?: string;+ format?: "wav" | "mp3";+ };+ file?: {+ file_data?: string;+ file_id?: string;+ filename?: string;+ };+};+type UserMessage = {+ role: "user";+ content: string | Array<UserMessageContentPart>;+ name?: string;+};+type AssistantMessageContentPart = {+ type: "text" | "refusal";+ text?: string;+ refusal?: string;+};+type AssistantMessage = {+ role: "assistant";+ content?: string | null | Array<AssistantMessageContentPart>;+ refusal?: string | null;+ name?: string;+ audio?: {+ id: string;+ };+ tool_calls?: Array<ChatCompletionMessageToolCall>;+ function_call?: {+ name: string;+ arguments: string;+ };+};+type ToolMessage = {+ role: "tool";+ content: string | Array<{+ type: "text";+ text: string;+ }>;+ tool_call_id: string;+};+type FunctionMessage = {+ role: "function";+ content: string;+ name: string;+};+type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage;+type ChatCompletionsResponseFormatText = {+ type: "text";+};+type ChatCompletionsResponseFormatJSONObject = {+ type: "json_object";+};+type ResponseFormatJSONSchema = {+ type: "json_schema";+ json_schema: {+ name: string;+ description?: string;+ schema?: Record<string, unknown>;+ strict?: boolean | null;+ };+};+type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema;+type ChatCompletionsStreamOptions = {+ include_usage?: boolean;+ include_obfuscation?: boolean;+};+type PredictionContent = {+ type: "content";+ content: string | Array<{+ type: "text";+ text: string;+ }>;+};+type AudioParams = {+ voice: string | {+ id: string;+ };+ format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16";+};+type WebSearchUserLocation = {+ type: "approximate";+ approximate: {+ city?: string;+ country?: string;+ region?: string;+ timezone?: string;+ };+};+type WebSearchOptions = {+ search_context_size?: "low" | "medium" | "high";+ user_location?: WebSearchUserLocation;+};+type ChatTemplateKwargs = {+ /** Whether to enable reasoning, enabled by default. */+ enable_thinking?: boolean;+ /** If false, preserves reasoning context between turns. */+ clear_thinking?: boolean;+};+/** Shared optional properties used by both Prompt and Messages input branches. */+type ChatCompletionsCommonOptions = {+ model?: string;+ audio?: AudioParams;+ frequency_penalty?: number | null;+ logit_bias?: Record<string, unknown> | null;+ logprobs?: boolean | null;+ top_logprobs?: number | null;+ max_tokens?: number | null;+ max_completion_tokens?: number | null;+ metadata?: Record<string, unknown> | null;+ modalities?: Array<"text" | "audio"> | null;+ n?: number | null;+ parallel_tool_calls?: boolean;+ prediction?: PredictionContent;+ presence_penalty?: number | null;+ reasoning_effort?: "low" | "medium" | "high" | null;+ chat_template_kwargs?: ChatTemplateKwargs;+ response_format?: ResponseFormat;+ seed?: number | null;+ service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;+ stop?: string | Array<string> | null;+ store?: boolean | null;+ stream?: boolean | null;+ stream_options?: ChatCompletionsStreamOptions;+ temperature?: number | null;+ tool_choice?: ChatCompletionToolChoiceOption;+ tools?: Array<ChatCompletionTool>;+ top_p?: number | null;+ user?: string;+ web_search_options?: WebSearchOptions;+ function_call?: "none" | "auto" | {+ name: string;+ };+ functions?: Array<FunctionDefinition>;+};+type PromptTokensDetails = {+ cached_tokens?: number;+ audio_tokens?: number;+};+type CompletionTokensDetails = {+ reasoning_tokens?: number;+ audio_tokens?: number;+ accepted_prediction_tokens?: number;+ rejected_prediction_tokens?: number;+};+type CompletionUsage = {+ prompt_tokens: number;+ completion_tokens: number;+ total_tokens: number;+ prompt_tokens_details?: PromptTokensDetails;+ completion_tokens_details?: CompletionTokensDetails;+};+type ChatCompletionTopLogprob = {+ token: string;+ logprob: number;+ bytes: Array<number> | null;+};+type ChatCompletionTokenLogprob = {+ token: string;+ logprob: number;+ bytes: Array<number> | null;+ top_logprobs: Array<ChatCompletionTopLogprob>;+};+type ChatCompletionAudio = {+ id: string;+ /** Base64 encoded audio bytes. */+ data: string;+ expires_at: number;+ transcript: string;+};+type ChatCompletionUrlCitation = {+ type: "url_citation";+ url_citation: {+ url: string;+ title: string;+ start_index: number;+ end_index: number;+ };+};+type ChatCompletionResponseMessage = {+ role: "assistant";+ content: string | null;+ refusal: string | null;+ annotations?: Array<ChatCompletionUrlCitation>;+ audio?: ChatCompletionAudio;+ tool_calls?: Array<ChatCompletionMessageToolCall>;+ function_call?: {+ name: string;+ arguments: string;+ } | null;+};+type ChatCompletionLogprobs = {+ content: Array<ChatCompletionTokenLogprob> | null;+ refusal?: Array<ChatCompletionTokenLogprob> | null;+};+type ChatCompletionChoice = {+ index: number;+ message: ChatCompletionResponseMessage;+ finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call";+ logprobs: ChatCompletionLogprobs | null;+};+type ChatCompletionsMessagesInput = {+ messages: Array<ChatCompletionMessageParam>;+} & ChatCompletionsCommonOptions;+type ChatCompletionsOutput = {+ id: string;+ object: string;+ created: number;+ model: string;+ choices: Array<ChatCompletionChoice>;+ usage?: CompletionUsage;+ system_fingerprint?: string | null;+ service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;+};+/**+ * Workers AI support for OpenAI's Responses API+ * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts+ *+ * It's a stripped down version from its source.+ * It currently supports basic function calling, json mode and accepts images as input.+ *+ * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools.+ * We plan to add those incrementally as model + platform capabilities evolve.+ */+type ResponsesInput = {+ background?: boolean | null;+ conversation?: string | ResponseConversationParam | null;+ include?: Array<ResponseIncludable> | null;+ input?: string | ResponseInput;+ instructions?: string | null;+ max_output_tokens?: number | null;+ parallel_tool_calls?: boolean | null;+ previous_response_id?: string | null;+ prompt_cache_key?: string;+ reasoning?: Reasoning | null;+ safety_identifier?: string;+ service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;+ stream?: boolean | null;+ stream_options?: StreamOptions | null;+ temperature?: number | null;+ text?: ResponseTextConfig;+ tool_choice?: ToolChoiceOptions | ToolChoiceFunction;+ tools?: Array<Tool>;+ top_p?: number | null;+ truncation?: "auto" | "disabled" | null;+};+type ResponsesOutput = {+ id?: string;+ created_at?: number;+ output_text?: string;+ error?: ResponseError | null;+ incomplete_details?: ResponseIncompleteDetails | null;+ instructions?: string | Array<ResponseInputItem> | null;+ object?: "response";+ output?: Array<ResponseOutputItem>;+ parallel_tool_calls?: boolean;+ temperature?: number | null;+ tool_choice?: ToolChoiceOptions | ToolChoiceFunction;+ tools?: Array<Tool>;+ top_p?: number | null;+ max_output_tokens?: number | null;+ previous_response_id?: string | null;+ prompt?: ResponsePrompt | null;+ reasoning?: Reasoning | null;+ safety_identifier?: string;+ service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;+ status?: ResponseStatus;+ text?: ResponseTextConfig;+ truncation?: "auto" | "disabled" | null;+ usage?: ResponseUsage;+};+type EasyInputMessage = {+ content: string | ResponseInputMessageContentList;+ role: "user" | "assistant" | "system" | "developer";+ type?: "message";+};+type ResponsesFunctionTool = {+ name: string;+ parameters: {+ [key: string]: unknown;+ } | null;+ strict: boolean | null;+ type: "function";+ description?: string | null;+};+type ResponseIncompleteDetails = {+ reason?: "max_output_tokens" | "content_filter";+};+type ResponsePrompt = {+ id: string;+ variables?: {+ [key: string]: string | ResponseInputText | ResponseInputImage;+ } | null;+ version?: string | null;+};+type Reasoning = {+ effort?: ReasoningEffort | null;+ generate_summary?: "auto" | "concise" | "detailed" | null;+ summary?: "auto" | "concise" | "detailed" | null;+};+type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText;+type ResponseContentReasoningText = {+ text: string;+ type: "reasoning_text";+};+type ResponseConversationParam = {+ id: string;+};+type ResponseCreatedEvent = {+ response: Response;+ sequence_number: number;+ type: "response.created";+};+type ResponseCustomToolCallOutput = {+ call_id: string;+ output: string | Array<ResponseInputText | ResponseInputImage>;+ type: "custom_tool_call_output";+ id?: string;+};+type ResponseError = {+ code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found";+ message: string;+};+type ResponseErrorEvent = {+ code: string | null;+ message: string;+ param: string | null;+ sequence_number: number;+ type: "error";+};+type ResponseFailedEvent = {+ response: Response;+ sequence_number: number;+ type: "response.failed";+};+type ResponseFormatText = {+ type: "text";+};+type ResponseFormatJSONObject = {+ type: "json_object";+};+type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject;+type ResponseFormatTextJSONSchemaConfig = {+ name: string;+ schema: {+ [key: string]: unknown;+ };+ type: "json_schema";+ description?: string;+ strict?: boolean | null;+};+type ResponseFunctionCallArgumentsDeltaEvent = {+ delta: string;+ item_id: string;+ output_index: number;+ sequence_number: number;+ type: "response.function_call_arguments.delta";+};+type ResponseFunctionCallArgumentsDoneEvent = {+ arguments: string;+ item_id: string;+ name: string;+ output_index: number;+ sequence_number: number;+ type: "response.function_call_arguments.done";+};+type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent;+type ResponseFunctionCallOutputItemList = Array<ResponseFunctionCallOutputItem>;+type ResponseFunctionToolCall = {+ arguments: string;+ call_id: string;+ name: string;+ type: "function_call";+ id?: string;+ status?: "in_progress" | "completed" | "incomplete";+};+interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall {+ id: string;+}+type ResponseFunctionToolCallOutputItem = {+ id: string;+ call_id: string;+ output: string | Array<ResponseInputText | ResponseInputImage>;+ type: "function_call_output";+ status?: "in_progress" | "completed" | "incomplete";+};+type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs";+type ResponseIncompleteEvent = {+ response: Response;+ sequence_number: number;+ type: "response.incomplete";+};+type ResponseInput = Array<ResponseInputItem>;+type ResponseInputContent = ResponseInputText | ResponseInputImage;+type ResponseInputImage = {+ detail: "low" | "high" | "auto";+ type: "input_image";+ /**+ * Base64 encoded image+ */+ image_url?: string | null;+};+type ResponseInputImageContent = {+ type: "input_image";+ detail?: "low" | "high" | "auto" | null;+ /**+ * Base64 encoded image+ */+ image_url?: string | null;+};+type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem;+type ResponseInputItemFunctionCallOutput = {+ call_id: string;+ output: string | ResponseFunctionCallOutputItemList;+ type: "function_call_output";+ id?: string | null;+ status?: "in_progress" | "completed" | "incomplete" | null;+};+type ResponseInputItemMessage = {+ content: ResponseInputMessageContentList;+ role: "user" | "system" | "developer";+ status?: "in_progress" | "completed" | "incomplete";+ type?: "message";+};+type ResponseInputMessageContentList = Array<ResponseInputContent>;+type ResponseInputMessageItem = {+ id: string;+ content: ResponseInputMessageContentList;+ role: "user" | "system" | "developer";+ status?: "in_progress" | "completed" | "incomplete";+ type?: "message";+};+type ResponseInputText = {+ text: string;+ type: "input_text";+};+type ResponseInputTextContent = {+ text: string;+ type: "input_text";+};+type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem;+type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem;+type ResponseOutputItemAddedEvent = {+ item: ResponseOutputItem;+ output_index: number;+ sequence_number: number;+ type: "response.output_item.added";+};+type ResponseOutputItemDoneEvent = {+ item: ResponseOutputItem;+ output_index: number;+ sequence_number: number;+ type: "response.output_item.done";+};+type ResponseOutputMessage = {+ id: string;+ content: Array<ResponseOutputText | ResponseOutputRefusal>;+ role: "assistant";+ status: "in_progress" | "completed" | "incomplete";+ type: "message";+};+type ResponseOutputRefusal = {+ refusal: string;+ type: "refusal";+};+type ResponseOutputText = {+ text: string;+ type: "output_text";+ logprobs?: Array<Logprob>;+};+type ResponseReasoningItem = {+ id: string;+ summary: Array<ResponseReasoningSummaryItem>;+ type: "reasoning";+ content?: Array<ResponseReasoningContentItem>;+ encrypted_content?: string | null;+ status?: "in_progress" | "completed" | "incomplete";+};+type ResponseReasoningSummaryItem = {+ text: string;+ type: "summary_text";+};+type ResponseReasoningContentItem = {+ text: string;+ type: "reasoning_text";+};+type ResponseReasoningTextDeltaEvent = {+ content_index: number;+ delta: string;+ item_id: string;+ output_index: number;+ sequence_number: number;+ type: "response.reasoning_text.delta";+};+type ResponseReasoningTextDoneEvent = {+ content_index: number;+ item_id: string;+ output_index: number;+ sequence_number: number;+ text: string;+ type: "response.reasoning_text.done";+};+type ResponseRefusalDeltaEvent = {+ content_index: number;+ delta: string;+ item_id: string;+ output_index: number;+ sequence_number: number;+ type: "response.refusal.delta";+};+type ResponseRefusalDoneEvent = {+ content_index: number;+ item_id: string;+ output_index: number;+ refusal: string;+ sequence_number: number;+ type: "response.refusal.done";+};+type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete";+type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent;+type ResponseCompletedEvent = {+ response: Response;+ sequence_number: number;+ type: "response.completed";+};+type ResponseTextConfig = {+ format?: ResponseFormatTextConfig;+ verbosity?: "low" | "medium" | "high" | null;+};+type ResponseTextDeltaEvent = {+ content_index: number;+ delta: string;+ item_id: string;+ logprobs: Array<Logprob>;+ output_index: number;+ sequence_number: number;+ type: "response.output_text.delta";+};+type ResponseTextDoneEvent = {+ content_index: number;+ item_id: string;+ logprobs: Array<Logprob>;+ output_index: number;+ sequence_number: number;+ text: string;+ type: "response.output_text.done";+};+type Logprob = {+ token: string;+ logprob: number;+ top_logprobs?: Array<TopLogprob>;+};+type TopLogprob = {+ token?: string;+ logprob?: number;+};+type ResponseUsage = {+ input_tokens: number;+ output_tokens: number;+ total_tokens: number;+};+type Tool = ResponsesFunctionTool;+type ToolChoiceFunction = {+ name: string;+ type: "function";+};+type ToolChoiceOptions = "none";+type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null;+type StreamOptions = {+ include_obfuscation?: boolean;+};+/** Marks keys from T that aren't in U as optional never */+type Without<T, U> = {+ [P in Exclude<keyof T, keyof U>]?: never;+};+/** Either T or U, but not both (mutually exclusive) */+type XOR<T, U> = (T & Without<U, T>) | (U & Without<T, U>);+type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = {+ text: string | string[];+ /**+ * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.+ */+ pooling?: "mean" | "cls";+} | {+ /**+ * Batch of the embeddings requests to run using async-queue+ */+ requests: {+ text: string | string[];+ /**+ * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.+ */+ pooling?: "mean" | "cls";+ }[];+};+type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = {+ shape?: number[];+ /**+ * Embeddings of the requested text values+ */+ data?: number[][];+ /**+ * The pooling method used in the embedding process.+ */+ pooling?: "mean" | "cls";+} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse;+interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse {+ /**+ * The async request id that can be used to obtain the results.+ */+ request_id?: string;+}+declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 {+ inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input;+ postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output;+}+type Ai_Cf_Openai_Whisper_Input = string | {+ /**+ * An array of integers that represent the audio data constrained to 8-bit unsigned integer values+ */+ audio: number[];+};+interface Ai_Cf_Openai_Whisper_Output {+ /**+ * The transcription+ */+ text: string;+ word_count?: number;+ words?: {+ word?: string;+ /**+ * The second this word begins in the recording+ */+ start?: number;+ /**+ * The ending second when the word completes+ */+ end?: number;+ }[];+ vtt?: string;+}+declare abstract class Base_Ai_Cf_Openai_Whisper {+ inputs: Ai_Cf_Openai_Whisper_Input;+ postProcessedOutputs: Ai_Cf_Openai_Whisper_Output;+}+type Ai_Cf_Meta_M2M100_1_2B_Input = {+ /**+ * The text to be translated+ */+ text: string;+ /**+ * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified+ */+ source_lang?: string;+ /**+ * The language code to translate the text into (e.g., 'es' for Spanish)+ */+ target_lang: string;+} | {+ /**+ * Batch of the embeddings requests to run using async-queue+ */+ requests: {+ /**+ * The text to be translated+ */+ text: string;+ /**+ * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified+ */+ source_lang?: string;+ /**+ * The language code to translate the text into (e.g., 'es' for Spanish)+ */+ target_lang: string;+ }[];+};+type Ai_Cf_Meta_M2M100_1_2B_Output = {+ /**+ * The translated text in the target language+ */+ translated_text?: string;+} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse;+interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse {+ /**+ * The async request id that can be used to obtain the results.+ */+ request_id?: string;+}+declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B {+ inputs: Ai_Cf_Meta_M2M100_1_2B_Input;+ postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output;+}+type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = {+ text: string | string[];+ /**+ * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.+ */+ pooling?: "mean" | "cls";+} | {+ /**+ * Batch of the embeddings requests to run using async-queue+ */+ requests: {+ text: string | string[];+ /**+ * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.+ */+ pooling?: "mean" | "cls";+ }[];+};+type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = {+ shape?: number[];+ /**+ * Embeddings of the requested text values+ */+ data?: number[][];+ /**+ * The pooling method used in the embedding process.+ */+ pooling?: "mean" | "cls";+} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse;+interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse {+ /**+ * The async request id that can be used to obtain the results.+ */+ request_id?: string;+}+declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 {+ inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input;+ postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output;+}+type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = {+ text: string | string[];+ /**+ * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.+ */+ pooling?: "mean" | "cls";+} | {+ /**+ * Batch of the embeddings requests to run using async-queue+ */+ requests: {+ text: string | string[];+ /**+ * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy.+ */+ pooling?: "mean" | "cls";+ }[];+};+type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = {+ shape?: number[];+ /**+ * Embeddings of the requested text values+ */+ data?: number[][];+ /**+ * The pooling method used in the embedding process.+ */+ pooling?: "mean" | "cls";+} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse;+interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse {+ /**+ * The async request id that can be used to obtain the results.+ */+ request_id?: string;+}+declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 {+ inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input;+ postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output;+}+type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt?: string;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+ image: number[] | (string & NonNullable<unknown>);+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+};+interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output {+ description?: string;+}+declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M {+ inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input;+ postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output;+}+type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | {+ /**+ * An array of integers that represent the audio data constrained to 8-bit unsigned integer values+ */+ audio: number[];+};+interface Ai_Cf_Openai_Whisper_Tiny_En_Output {+ /**+ * The transcription+ */+ text: string;+ word_count?: number;+ words?: {+ word?: string;+ /**+ * The second this word begins in the recording+ */+ start?: number;+ /**+ * The ending second when the word completes+ */+ end?: number;+ }[];+ vtt?: string;+}+declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En {+ inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input;+ postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output;+}+interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input {+ audio: string | {+ body?: object;+ contentType?: string;+ };+ /**+ * Supported tasks are 'translate' or 'transcribe'.+ */+ task?: string;+ /**+ * The language of the audio being transcribed or translated.+ */+ language?: string;+ /**+ * Preprocess the audio with a voice activity detection model.+ */+ vad_filter?: boolean;+ /**+ * A text prompt to help provide context to the model on the contents of the audio.+ */+ initial_prompt?: string;+ /**+ * The prefix appended to the beginning of the output of the transcription and can guide the transcription result.+ */+ prefix?: string;+ /**+ * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed.+ */+ beam_size?: number;+ /**+ * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops.+ */+ condition_on_previous_text?: boolean;+ /**+ * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped.+ */+ no_speech_threshold?: number;+ /**+ * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text.+ */+ compression_ratio_threshold?: number;+ /**+ * Threshold for filtering out segments with low average log probability, indicating low confidence.+ */+ log_prob_threshold?: number;+ /**+ * Optional threshold (in seconds) to skip silent periods that may cause hallucinations.+ */+ hallucination_silence_threshold?: number;+}+interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output {+ transcription_info?: {+ /**+ * The language of the audio being transcribed or translated.+ */+ language?: string;+ /**+ * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1.+ */+ language_probability?: number;+ /**+ * The total duration of the original audio file, in seconds.+ */+ duration?: number;+ /**+ * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds.+ */+ duration_after_vad?: number;+ };+ /**+ * The complete transcription of the audio.+ */+ text: string;+ /**+ * The total number of words in the transcription.+ */+ word_count?: number;+ segments?: {+ /**+ * The starting time of the segment within the audio, in seconds.+ */+ start?: number;+ /**+ * The ending time of the segment within the audio, in seconds.+ */+ end?: number;+ /**+ * The transcription of the segment.+ */+ text?: string;+ /**+ * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs.+ */+ temperature?: number;+ /**+ * The average log probability of the predictions for the words in this segment, indicating overall confidence.+ */+ avg_logprob?: number;+ /**+ * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process.+ */+ compression_ratio?: number;+ /**+ * The probability that the segment contains no speech, represented as a decimal between 0 and 1.+ */+ no_speech_prob?: number;+ words?: {+ /**+ * The individual word transcribed from the audio.+ */+ word?: string;+ /**+ * The starting time of the word within the audio, in seconds.+ */+ start?: number;+ /**+ * The ending time of the word within the audio, in seconds.+ */+ end?: number;+ }[];+ }[];+ /**+ * The transcription in WebVTT format, which includes timing and text information for use in subtitles.+ */+ vtt?: string;+}+declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo {+ inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input;+ postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output;+}+type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | {+ /**+ * Batch of the embeddings requests to run using async-queue+ */+ requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[];+};+interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts {+ /**+ * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts+ */+ query?: string;+ /**+ * List of provided contexts. Note that the index in this array is important, as the response will refer to it.+ */+ contexts: {+ /**+ * One of the provided context content+ */+ text?: string;+ }[];+ /**+ * When provided with too long context should the model error out or truncate the context to fit?+ */+ truncate_inputs?: boolean;+}+interface Ai_Cf_Baai_Bge_M3_Input_Embedding {+ text: string | string[];+ /**+ * When provided with too long context should the model error out or truncate the context to fit?+ */+ truncate_inputs?: boolean;+}+interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 {+ /**+ * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts+ */+ query?: string;+ /**+ * List of provided contexts. Note that the index in this array is important, as the response will refer to it.+ */+ contexts: {+ /**+ * One of the provided context content+ */+ text?: string;+ }[];+ /**+ * When provided with too long context should the model error out or truncate the context to fit?+ */+ truncate_inputs?: boolean;+}+interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 {+ text: string | string[];+ /**+ * When provided with too long context should the model error out or truncate the context to fit?+ */+ truncate_inputs?: boolean;+}+type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Output_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Output_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse;+interface Ai_Cf_Baai_Bge_M3_Output_Query {+ response?: {+ /**+ * Index of the context in the request+ */+ id?: number;+ /**+ * Score of the context under the index.+ */+ score?: number;+ }[];+}+interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts {+ response?: number[][];+ shape?: number[];+ /**+ * The pooling method used in the embedding process.+ */+ pooling?: "mean" | "cls";+}+interface Ai_Cf_Baai_Bge_M3_Output_Embedding {+ shape?: number[];+ /**+ * Embeddings of the requested text values+ */+ data?: number[][];+ /**+ * The pooling method used in the embedding process.+ */+ pooling?: "mean" | "cls";+}+interface Ai_Cf_Baai_Bge_M3_AsyncResponse {+ /**+ * The async request id that can be used to obtain the results.+ */+ request_id?: string;+}+declare abstract class Base_Ai_Cf_Baai_Bge_M3 {+ inputs: Ai_Cf_Baai_Bge_M3_Input;+ postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output;+}+interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input {+ /**+ * A text description of the image you want to generate.+ */+ prompt: string;+ /**+ * The number of diffusion steps; higher values can improve quality but take longer.+ */+ steps?: number;+}+interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output {+ /**+ * The generated image in Base64 format.+ */+ image?: string;+}+declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell {+ inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input;+ postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output;+}+type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages;+interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ image?: number[] | (string & NonNullable<unknown>);+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+ /**+ * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.+ */+ lora?: string;+}+interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role?: string;+ /**+ * The tool call id. If you don't know what to put here you can fall back to 000000001+ */+ tool_call_id?: string;+ content?: string | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ }[] | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ };+ }[];+ image?: number[] | (string & NonNullable<unknown>);+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ /**+ * If true, the response will be streamed back incrementally.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = {+ /**+ * The generated text response from the model+ */+ response?: string;+ /**+ * An array of tool calls requests made during the response generation+ */+ tool_calls?: {+ /**+ * The arguments passed to be passed to the tool call request+ */+ arguments?: object;+ /**+ * The name of the tool to be called+ */+ name?: string;+ }[];+};+declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct {+ inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input;+ postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output;+}+type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch;+interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.+ */+ lora?: string;+ response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role: string;+ content: string | {+ /**+ * Type of the content (text)+ */+ type?: string;+ /**+ * Text content+ */+ text?: string;+ }[];+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch {+ requests?: {+ /**+ * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique.+ */+ external_reference?: string;+ /**+ * Prompt for the text generation model+ */+ prompt?: string;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+ response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2;+ }[];+}+interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = {+ /**+ * The generated text response from the model+ */+ response: string;+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+ /**+ * An array of tool calls requests made during the response generation+ */+ tool_calls?: {+ /**+ * The arguments passed to be passed to the tool call request+ */+ arguments?: object;+ /**+ * The name of the tool to be called+ */+ name?: string;+ }[];+} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse;+interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse {+ /**+ * The async request id that can be used to obtain the results.+ */+ request_id?: string;+}+declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast {+ inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input;+ postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output;+}+interface Ai_Cf_Meta_Llama_Guard_3_8B_Input {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender must alternate between 'user' and 'assistant'.+ */+ role: "user" | "assistant";+ /**+ * The content of the message as a string.+ */+ content: string;+ }[];+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Dictate the output format of the generated response.+ */+ response_format?: {+ /**+ * Set to json_object to process and output generated text as JSON.+ */+ type?: string;+ };+}+interface Ai_Cf_Meta_Llama_Guard_3_8B_Output {+ response?: string | {+ /**+ * Whether the conversation is safe or not.+ */+ safe?: boolean;+ /**+ * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe.+ */+ categories?: string[];+ };+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+}+declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B {+ inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input;+ postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output;+}+interface Ai_Cf_Baai_Bge_Reranker_Base_Input {+ /**+ * A query you wish to perform against the provided contexts.+ */+ /**+ * Number of returned results starting with the best score.+ */+ top_k?: number;+ /**+ * List of provided contexts. Note that the index in this array is important, as the response will refer to it.+ */+ contexts: {+ /**+ * One of the provided context content+ */+ text?: string;+ }[];+}+interface Ai_Cf_Baai_Bge_Reranker_Base_Output {+ response?: {+ /**+ * Index of the context in the request+ */+ id?: number;+ /**+ * Score of the context under the index.+ */+ score?: number;+ }[];+}+declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base {+ inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input;+ postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output;+}+type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages;+interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.+ */+ lora?: string;+ response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role: string;+ /**+ * The content of the message as a string.+ */+ content: string;+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = {+ /**+ * The generated text response from the model+ */+ response: string;+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+ /**+ * An array of tool calls requests made during the response generation+ */+ tool_calls?: {+ /**+ * The arguments passed to be passed to the tool call request+ */+ arguments?: object;+ /**+ * The name of the tool to be called+ */+ name?: string;+ }[];+};+declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct {+ inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input;+ postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output;+}+type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages;+interface Ai_Cf_Qwen_Qwq_32B_Prompt {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * JSON schema that should be fulfilled for the response.+ */+ guided_json?: object;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Qwen_Qwq_32B_Messages {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role?: string;+ /**+ * The tool call id. If you don't know what to put here you can fall back to 000000001+ */+ tool_call_id?: string;+ content?: string | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ }[] | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ };+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ /**+ * JSON schema that should be fufilled for the response.+ */+ guided_json?: object;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+type Ai_Cf_Qwen_Qwq_32B_Output = {+ /**+ * The generated text response from the model+ */+ response: string;+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+ /**+ * An array of tool calls requests made during the response generation+ */+ tool_calls?: {+ /**+ * The arguments passed to be passed to the tool call request+ */+ arguments?: object;+ /**+ * The name of the tool to be called+ */+ name?: string;+ }[];+};+declare abstract class Base_Ai_Cf_Qwen_Qwq_32B {+ inputs: Ai_Cf_Qwen_Qwq_32B_Input;+ postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output;+}+type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages;+interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * JSON schema that should be fulfilled for the response.+ */+ guided_json?: object;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role?: string;+ /**+ * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001+ */+ tool_call_id?: string;+ content?: string | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ }[] | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ };+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ /**+ * JSON schema that should be fufilled for the response.+ */+ guided_json?: object;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = {+ /**+ * The generated text response from the model+ */+ response: string;+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+ /**+ * An array of tool calls requests made during the response generation+ */+ tool_calls?: {+ /**+ * The arguments passed to be passed to the tool call request+ */+ arguments?: object;+ /**+ * The name of the tool to be called+ */+ name?: string;+ }[];+};+declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct {+ inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input;+ postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output;+}+type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages;+interface Ai_Cf_Google_Gemma_3_12B_It_Prompt {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * JSON schema that should be fufilled for the response.+ */+ guided_json?: object;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Google_Gemma_3_12B_It_Messages {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role?: string;+ content?: string | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ }[];+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ /**+ * JSON schema that should be fufilled for the response.+ */+ guided_json?: object;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+type Ai_Cf_Google_Gemma_3_12B_It_Output = {+ /**+ * The generated text response from the model+ */+ response: string;+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+ /**+ * An array of tool calls requests made during the response generation+ */+ tool_calls?: {+ /**+ * The arguments passed to be passed to the tool call request+ */+ arguments?: object;+ /**+ * The name of the tool to be called+ */+ name?: string;+ }[];+};+declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It {+ inputs: Ai_Cf_Google_Gemma_3_12B_It_Input;+ postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output;+}+type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch;+interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * JSON schema that should be fulfilled for the response.+ */+ guided_json?: object;+ response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role?: string;+ /**+ * The tool call id. If you don't know what to put here you can fall back to 000000001+ */+ tool_call_id?: string;+ content?: string | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ }[] | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ };+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;+ /**+ * JSON schema that should be fufilled for the response.+ */+ guided_json?: object;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch {+ requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[];+}+interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * JSON schema that should be fulfilled for the response.+ */+ guided_json?: object;+ response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role?: string;+ /**+ * The tool call id. If you don't know what to put here you can fall back to 000000001+ */+ tool_call_id?: string;+ content?: string | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ }[] | {+ /**+ * Type of the content provided+ */+ type?: string;+ text?: string;+ image_url?: {+ /**+ * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted+ */+ url?: string;+ };+ };+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;+ /**+ * JSON schema that should be fufilled for the response.+ */+ guided_json?: object;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = {+ /**+ * The generated text response from the model+ */+ response: string;+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+ /**+ * An array of tool calls requests made during the response generation+ */+ tool_calls?: {+ /**+ * The tool call id.+ */+ id?: string;+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type?: string;+ /**+ * Details of the function tool.+ */+ function?: {+ /**+ * The name of the tool to be called+ */+ name?: string;+ /**+ * The arguments passed to be passed to the tool call request+ */+ arguments?: object;+ };+ }[];+};+declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct {+ inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input;+ postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output;+}+type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch;+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.+ */+ lora?: string;+ response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role: string;+ content: string | {+ /**+ * Type of the content (text)+ */+ type?: string;+ /**+ * Text content+ */+ text?: string;+ }[];+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch {+ requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[];+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.+ */+ lora?: string;+ response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role: string;+ content: string | {+ /**+ * Type of the content (text)+ */+ type?: string;+ /**+ * Text content+ */+ text?: string;+ }[];+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse;+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response {+ /**+ * Unique identifier for the completion+ */+ id?: string;+ /**+ * Object type identifier+ */+ object?: "chat.completion";+ /**+ * Unix timestamp of when the completion was created+ */+ created?: number;+ /**+ * Model used for the completion+ */+ model?: string;+ /**+ * List of completion choices+ */+ choices?: {+ /**+ * Index of the choice in the list+ */+ index?: number;+ /**+ * The message generated by the model+ */+ message?: {+ /**+ * Role of the message author+ */+ role: string;+ /**+ * The content of the message+ */+ content: string;+ /**+ * Internal reasoning content (if available)+ */+ reasoning_content?: string;+ /**+ * Tool calls made by the assistant+ */+ tool_calls?: {+ /**+ * Unique identifier for the tool call+ */+ id: string;+ /**+ * Type of tool call+ */+ type: "function";+ function: {+ /**+ * Name of the function to call+ */+ name: string;+ /**+ * JSON string of arguments for the function+ */+ arguments: string;+ };+ }[];+ };+ /**+ * Reason why the model stopped generating+ */+ finish_reason?: string;+ /**+ * Stop reason (may be null)+ */+ stop_reason?: string | null;+ /**+ * Log probabilities (if requested)+ */+ logprobs?: {} | null;+ }[];+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+ /**+ * Log probabilities for the prompt (if requested)+ */+ prompt_logprobs?: {} | null;+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response {+ /**+ * Unique identifier for the completion+ */+ id?: string;+ /**+ * Object type identifier+ */+ object?: "text_completion";+ /**+ * Unix timestamp of when the completion was created+ */+ created?: number;+ /**+ * Model used for the completion+ */+ model?: string;+ /**+ * List of completion choices+ */+ choices?: {+ /**+ * Index of the choice in the list+ */+ index: number;+ /**+ * The generated text completion+ */+ text: string;+ /**+ * Reason why the model stopped generating+ */+ finish_reason: string;+ /**+ * Stop reason (may be null)+ */+ stop_reason?: string | null;+ /**+ * Log probabilities (if requested)+ */+ logprobs?: {} | null;+ /**+ * Log probabilities for the prompt (if requested)+ */+ prompt_logprobs?: {} | null;+ }[];+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+}+interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse {+ /**+ * The async request id that can be used to obtain the results.+ */+ request_id?: string;+}+declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 {+ inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input;+ postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output;+}+interface Ai_Cf_Deepgram_Nova_3_Input {+ audio: {+ body: object;+ contentType: string;+ };+ /**+ * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param.+ */+ custom_topic_mode?: "extended" | "strict";+ /**+ * Custom topics you want the model to detect within your input audio or text if present Submit up to 100+ */+ custom_topic?: string;+ /**+ * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param+ */+ custom_intent_mode?: "extended" | "strict";+ /**+ * Custom intents you want the model to detect within your input audio if present+ */+ custom_intent?: string;+ /**+ * Identifies and extracts key entities from content in submitted audio+ */+ detect_entities?: boolean;+ /**+ * Identifies the dominant language spoken in submitted audio+ */+ detect_language?: boolean;+ /**+ * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0+ */+ diarize?: boolean;+ /**+ * Identify and extract key entities from content in submitted audio+ */+ dictation?: boolean;+ /**+ * Specify the expected encoding of your submitted audio+ */+ encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729";+ /**+ * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing+ */+ extra?: string;+ /**+ * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um'+ */+ filler_words?: boolean;+ /**+ * Key term prompting can boost or suppress specialized terminology and brands.+ */+ keyterm?: string;+ /**+ * Keywords can boost or suppress specialized terminology and brands.+ */+ keywords?: string;+ /**+ * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available.+ */+ language?: string;+ /**+ * Spoken measurements will be converted to their corresponding abbreviations.+ */+ measurements?: boolean;+ /**+ * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip.+ */+ mip_opt_out?: boolean;+ /**+ * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio+ */+ mode?: "general" | "medical" | "finance";+ /**+ * Transcribe each audio channel independently.+ */+ multichannel?: boolean;+ /**+ * Numerals converts numbers from written format to numerical format.+ */+ numerals?: boolean;+ /**+ * Splits audio into paragraphs to improve transcript readability.+ */+ paragraphs?: boolean;+ /**+ * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely.+ */+ profanity_filter?: boolean;+ /**+ * Add punctuation and capitalization to the transcript.+ */+ punctuate?: boolean;+ /**+ * Redaction removes sensitive information from your transcripts.+ */+ redact?: string;+ /**+ * Search for terms or phrases in submitted audio and replaces them.+ */+ replace?: string;+ /**+ * Search for terms or phrases in submitted audio.+ */+ search?: string;+ /**+ * Recognizes the sentiment throughout a transcript or text.+ */+ sentiment?: boolean;+ /**+ * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability.+ */+ smart_format?: boolean;+ /**+ * Detect topics throughout a transcript or text.+ */+ topics?: boolean;+ /**+ * Segments speech into meaningful semantic units.+ */+ utterances?: boolean;+ /**+ * Seconds to wait before detecting a pause between words in submitted audio.+ */+ utt_split?: number;+ /**+ * The number of channels in the submitted audio+ */+ channels?: number;+ /**+ * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets.+ */+ interim_results?: boolean;+ /**+ * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing+ */+ endpointing?: string;+ /**+ * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets.+ */+ vad_events?: boolean;+ /**+ * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets.+ */+ utterance_end_ms?: boolean;+}+interface Ai_Cf_Deepgram_Nova_3_Output {+ results?: {+ channels?: {+ alternatives?: {+ confidence?: number;+ transcript?: string;+ words?: {+ confidence?: number;+ end?: number;+ start?: number;+ word?: string;+ }[];+ }[];+ }[];+ summary?: {+ result?: string;+ short?: string;+ };+ sentiments?: {+ segments?: {+ text?: string;+ start_word?: number;+ end_word?: number;+ sentiment?: string;+ sentiment_score?: number;+ }[];+ average?: {+ sentiment?: string;+ sentiment_score?: number;+ };+ };+ };+}+declare abstract class Base_Ai_Cf_Deepgram_Nova_3 {+ inputs: Ai_Cf_Deepgram_Nova_3_Input;+ postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output;+}+interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input {+ queries?: string | string[];+ /**+ * Optional instruction for the task+ */+ instruction?: string;+ documents?: string | string[];+ text?: string | string[];+}+interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output {+ data?: number[][];+ shape?: number[];+}+declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B {+ inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input;+ postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output;+}+type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = {+ /**+ * readable stream with audio data and content-type specified for that data+ */+ audio: {+ body: object;+ contentType: string;+ };+ /**+ * type of data PCM data that's sent to the inference server as raw array+ */+ dtype?: "uint8" | "float32" | "float64";+} | {+ /**+ * base64 encoded audio data+ */+ audio: string;+ /**+ * type of data PCM data that's sent to the inference server as raw array+ */+ dtype?: "uint8" | "float32" | "float64";+};+interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output {+ /**+ * if true, end-of-turn was detected+ */+ is_complete?: boolean;+ /**+ * probability of the end-of-turn detection+ */+ probability?: number;+}+declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 {+ inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input;+ postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output;+}+declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B {+ inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;+ postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;+}+declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B {+ inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;+ postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;+}+interface Ai_Cf_Leonardo_Phoenix_1_0_Input {+ /**+ * A text description of the image you want to generate.+ */+ prompt: string;+ /**+ * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt+ */+ guidance?: number;+ /**+ * Random seed for reproducibility of the image generation+ */+ seed?: number;+ /**+ * The height of the generated image in pixels+ */+ height?: number;+ /**+ * The width of the generated image in pixels+ */+ width?: number;+ /**+ * The number of diffusion steps; higher values can improve quality but take longer+ */+ num_steps?: number;+ /**+ * Specify what to exclude from the generated images+ */+ negative_prompt?: string;+}+/**+ * The generated image in JPEG format+ */+type Ai_Cf_Leonardo_Phoenix_1_0_Output = string;+declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 {+ inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input;+ postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output;+}+interface Ai_Cf_Leonardo_Lucid_Origin_Input {+ /**+ * A text description of the image you want to generate.+ */+ prompt: string;+ /**+ * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt+ */+ guidance?: number;+ /**+ * Random seed for reproducibility of the image generation+ */+ seed?: number;+ /**+ * The height of the generated image in pixels+ */+ height?: number;+ /**+ * The width of the generated image in pixels+ */+ width?: number;+ /**+ * The number of diffusion steps; higher values can improve quality but take longer+ */+ num_steps?: number;+ /**+ * The number of diffusion steps; higher values can improve quality but take longer+ */+ steps?: number;+}+interface Ai_Cf_Leonardo_Lucid_Origin_Output {+ /**+ * The generated image in Base64 format.+ */+ image?: string;+}+declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin {+ inputs: Ai_Cf_Leonardo_Lucid_Origin_Input;+ postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output;+}+interface Ai_Cf_Deepgram_Aura_1_Input {+ /**+ * Speaker used to produce the audio.+ */+ speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella";+ /**+ * Encoding of the output audio.+ */+ encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";+ /**+ * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..+ */+ container?: "none" | "wav" | "ogg";+ /**+ * The text content to be converted to speech+ */+ text: string;+ /**+ * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable+ */+ sample_rate?: number;+ /**+ * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.+ */+ bit_rate?: number;+}+/**+ * The generated audio in MP3 format+ */+type Ai_Cf_Deepgram_Aura_1_Output = string;+declare abstract class Base_Ai_Cf_Deepgram_Aura_1 {+ inputs: Ai_Cf_Deepgram_Aura_1_Input;+ postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output;+}+interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input {+ /**+ * Input text to translate. Can be a single string or a list of strings.+ */+ text: string | string[];+ /**+ * Target langauge to translate to+ */+ target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva";+}+interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output {+ /**+ * Translated texts+ */+ translations: string[];+}+declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B {+ inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input;+ postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output;+}+type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch;+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.+ */+ lora?: string;+ response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role: string;+ content: string | {+ /**+ * Type of the content (text)+ */+ type?: string;+ /**+ * Text content+ */+ text?: string;+ }[];+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch {+ requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[];+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 {+ /**+ * The input text prompt for the model to generate a response.+ */+ prompt: string;+ /**+ * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.+ */+ lora?: string;+ response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 {+ /**+ * An array of message objects representing the conversation history.+ */+ messages: {+ /**+ * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').+ */+ role: string;+ content: string | {+ /**+ * Type of the content (text)+ */+ type?: string;+ /**+ * Text content+ */+ text?: string;+ }[];+ }[];+ functions?: {+ name: string;+ code: string;+ }[];+ /**+ * A list of tools available for the assistant to use.+ */+ tools?: ({+ /**+ * The name of the tool. More descriptive the better.+ */+ name: string;+ /**+ * A brief description of what the tool does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the tool.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ } | {+ /**+ * Specifies the type of tool (e.g., 'function').+ */+ type: string;+ /**+ * Details of the function tool.+ */+ function: {+ /**+ * The name of the function.+ */+ name: string;+ /**+ * A brief description of what the function does.+ */+ description: string;+ /**+ * Schema defining the parameters accepted by the function.+ */+ parameters: {+ /**+ * The type of the parameters object (usually 'object').+ */+ type: string;+ /**+ * List of required parameter names.+ */+ required?: string[];+ /**+ * Definitions of each parameter.+ */+ properties: {+ [k: string]: {+ /**+ * The data type of the parameter.+ */+ type: string;+ /**+ * A description of the expected parameter.+ */+ description: string;+ };+ };+ };+ };+ })[];+ response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3;+ /**+ * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.+ */+ raw?: boolean;+ /**+ * If true, the response will be streamed back incrementally using SSE, Server Sent Events.+ */+ stream?: boolean;+ /**+ * The maximum number of tokens to generate in the response.+ */+ max_tokens?: number;+ /**+ * Controls the randomness of the output; higher values produce more random results.+ */+ temperature?: number;+ /**+ * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses.+ */+ top_p?: number;+ /**+ * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises.+ */+ top_k?: number;+ /**+ * Random seed for reproducibility of the generation.+ */+ seed?: number;+ /**+ * Penalty for repeated tokens; higher values discourage repetition.+ */+ repetition_penalty?: number;+ /**+ * Decreases the likelihood of the model repeating the same lines verbatim.+ */+ frequency_penalty?: number;+ /**+ * Increases the likelihood of the model introducing new topics.+ */+ presence_penalty?: number;+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 {+ type?: "json_object" | "json_schema";+ json_schema?: unknown;+}+type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse;+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response {+ /**+ * Unique identifier for the completion+ */+ id?: string;+ /**+ * Object type identifier+ */+ object?: "chat.completion";+ /**+ * Unix timestamp of when the completion was created+ */+ created?: number;+ /**+ * Model used for the completion+ */+ model?: string;+ /**+ * List of completion choices+ */+ choices?: {+ /**+ * Index of the choice in the list+ */+ index?: number;+ /**+ * The message generated by the model+ */+ message?: {+ /**+ * Role of the message author+ */+ role: string;+ /**+ * The content of the message+ */+ content: string;+ /**+ * Internal reasoning content (if available)+ */+ reasoning_content?: string;+ /**+ * Tool calls made by the assistant+ */+ tool_calls?: {+ /**+ * Unique identifier for the tool call+ */+ id: string;+ /**+ * Type of tool call+ */+ type: "function";+ function: {+ /**+ * Name of the function to call+ */+ name: string;+ /**+ * JSON string of arguments for the function+ */+ arguments: string;+ };+ }[];+ };+ /**+ * Reason why the model stopped generating+ */+ finish_reason?: string;+ /**+ * Stop reason (may be null)+ */+ stop_reason?: string | null;+ /**+ * Log probabilities (if requested)+ */+ logprobs?: {} | null;+ }[];+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+ /**+ * Log probabilities for the prompt (if requested)+ */+ prompt_logprobs?: {} | null;+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response {+ /**+ * Unique identifier for the completion+ */+ id?: string;+ /**+ * Object type identifier+ */+ object?: "text_completion";+ /**+ * Unix timestamp of when the completion was created+ */+ created?: number;+ /**+ * Model used for the completion+ */+ model?: string;+ /**+ * List of completion choices+ */+ choices?: {+ /**+ * Index of the choice in the list+ */+ index: number;+ /**+ * The generated text completion+ */+ text: string;+ /**+ * Reason why the model stopped generating+ */+ finish_reason: string;+ /**+ * Stop reason (may be null)+ */+ stop_reason?: string | null;+ /**+ * Log probabilities (if requested)+ */+ logprobs?: {} | null;+ /**+ * Log probabilities for the prompt (if requested)+ */+ prompt_logprobs?: {} | null;+ }[];+ /**+ * Usage statistics for the inference request+ */+ usage?: {+ /**+ * Total number of tokens in input+ */+ prompt_tokens?: number;+ /**+ * Total number of tokens in output+ */+ completion_tokens?: number;+ /**+ * Total number of input and output tokens+ */+ total_tokens?: number;+ };+}+interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse {+ /**+ * The async request id that can be used to obtain the results.+ */+ request_id?: string;+}+declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It {+ inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input;+ postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output;+}+interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input {+ /**+ * Input text to embed. Can be a single string or a list of strings.+ */+ text: string | string[];+}+interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output {+ /**+ * Embedding vectors, where each vector is a list of floats.+ */+ data: number[][];+ /**+ * Shape of the embedding data as [number_of_embeddings, embedding_dimension].+ *+ * @minItems 2+ * @maxItems 2+ */+ shape: [+ number,+ number+ ];+}+declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B {+ inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input;+ postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output;+}+interface Ai_Cf_Deepgram_Flux_Input {+ /**+ * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM.+ */+ encoding: "linear16";+ /**+ * Sample rate of the audio stream in Hz.+ */+ sample_rate: string;+ /**+ * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9.+ */+ eager_eot_threshold?: string;+ /**+ * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9.+ */+ eot_threshold?: string;+ /**+ * A turn will be finished when this much time has passed after speech, regardless of EOT confidence.+ */+ eot_timeout_ms?: string;+ /**+ * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms.+ */+ keyterm?: string;+ /**+ * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip+ */+ mip_opt_out?: "true" | "false";+ /**+ * Label your requests for the purpose of identification during usage reporting+ */+ tag?: string;+}+/**+ * Output will be returned as websocket messages.+ */+interface Ai_Cf_Deepgram_Flux_Output {+ /**+ * The unique identifier of the request (uuid)+ */+ request_id?: string;+ /**+ * Starts at 0 and increments for each message the server sends to the client.+ */+ sequence_id?: number;+ /**+ * The type of event being reported.+ */+ event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn";+ /**+ * The index of the current turn+ */+ turn_index?: number;+ /**+ * Start time in seconds of the audio range that was transcribed+ */+ audio_window_start?: number;+ /**+ * End time in seconds of the audio range that was transcribed+ */+ audio_window_end?: number;+ /**+ * Text that was said over the course of the current turn+ */+ transcript?: string;+ /**+ * The words in the transcript+ */+ words?: {+ /**+ * The individual punctuated, properly-cased word from the transcript+ */+ word: string;+ /**+ * Confidence that this word was transcribed correctly+ */+ confidence: number;+ }[];+ /**+ * Confidence that no more speech is coming in this turn+ */+ end_of_turn_confidence?: number;+}+declare abstract class Base_Ai_Cf_Deepgram_Flux {+ inputs: Ai_Cf_Deepgram_Flux_Input;+ postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output;+}+interface Ai_Cf_Deepgram_Aura_2_En_Input {+ /**+ * Speaker used to produce the audio.+ */+ speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus";+ /**+ * Encoding of the output audio.+ */+ encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";+ /**+ * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..+ */+ container?: "none" | "wav" | "ogg";+ /**+ * The text content to be converted to speech+ */+ text: string;+ /**+ * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable+ */+ sample_rate?: number;+ /**+ * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.+ */+ bit_rate?: number;+}+/**+ * The generated audio in MP3 format+ */+type Ai_Cf_Deepgram_Aura_2_En_Output = string;+declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En {+ inputs: Ai_Cf_Deepgram_Aura_2_En_Input;+ postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output;+}+interface Ai_Cf_Deepgram_Aura_2_Es_Input {+ /**+ * Speaker used to produce the audio.+ */+ speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier";+ /**+ * Encoding of the output audio.+ */+ encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";+ /**+ * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..+ */+ container?: "none" | "wav" | "ogg";+ /**+ * The text content to be converted to speech+ */+ text: string;+ /**+ * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable+ */+ sample_rate?: number;+ /**+ * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.+ */+ bit_rate?: number;+}+/**+ * The generated audio in MP3 format+ */+type Ai_Cf_Deepgram_Aura_2_Es_Output = string;+declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es {+ inputs: Ai_Cf_Deepgram_Aura_2_Es_Input;+ postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output;+}+interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input {+ multipart: {+ body?: object;+ contentType?: string;+ };+}+interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output {+ /**+ * Generated image as Base64 string.+ */+ image?: string;+}+declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev {+ inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input;+ postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output;+}+interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input {+ multipart: {+ body?: object;+ contentType?: string;+ };+}+interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output {+ /**+ * Generated image as Base64 string.+ */+ image?: string;+}+declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B {+ inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input;+ postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output;+}+interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input {+ multipart: {+ body?: object;+ contentType?: string;+ };+}+interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output {+ /**+ * Generated image as Base64 string.+ */+ image?: string;+}+declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B {+ inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input;+ postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output;+}+declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_2 {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input {+ /**+ * Which Moondream skill to run.+ */+ task?: "query" | "caption" | "point" | "detect";+ /**+ * Input image as a public HTTPS URL or base64 data URI. Optional for `query`; required for `caption`, `point`, and `detect`.+ */+ image?: string;+ /**+ * Question for the `query` task.+ */+ question?: string;+ /**+ * Caption length for the `caption` task.+ */+ caption_length?: "short" | "normal" | "long";+ /**+ * Object phrase to locate for `point` and `detect` tasks (e.g. 'person wearing a red shirt').+ */+ target?: string;+ /**+ * Enable reasoning trace for the `query` task.+ */+ reasoning?: boolean;+ /**+ * Sampling temperature.+ */+ temperature?: number;+ /**+ * Top-p (nucleus) sampling.+ */+ top_p?: number;+ /**+ * Max tokens to generate for `query` and `caption`.+ */+ max_tokens?: number;+ /**+ * Max objects to return for `point` and `detect`.+ */+ max_objects?: number;+ /**+ * Return incremental tokens for `query` and `caption`. `point` and `detect` do not support streaming.+ */+ stream?: boolean;+}+interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output {+ /**+ * Reason the generation finished.+ */+ finish_reason: string;+ metrics: {+ /**+ * Number of input tokens consumed.+ */+ input_tokens: number;+ /**+ * Number of output tokens generated.+ */+ output_tokens: number;+ /**+ * Prefill time in milliseconds.+ */+ prefill_time_ms: number;+ /**+ * Decode time in milliseconds.+ */+ decode_time_ms: number;+ /**+ * Time to first token in milliseconds.+ */+ ttft_ms: number;+ };+ /**+ * Answer text for the `query` task. Null for other tasks.+ */+ answer?: string;+ /**+ * Caption text for the `caption` task. Null for other tasks.+ */+ caption?: string;+ /**+ * Located points for the `point` task. Null for other tasks.+ */+ points?: {+ /**+ * X coordinate.+ */+ x: number;+ /**+ * Y coordinate.+ */+ y: number;+ }[];+ /**+ * Detected bounding boxes for the `detect` task. Null for other tasks.+ */+ objects?: {+ /**+ * Minimum X coordinate.+ */+ x_min: number;+ /**+ * Minimum Y coordinate.+ */+ y_min: number;+ /**+ * Maximum X coordinate.+ */+ x_max: number;+ /**+ * Maximum Y coordinate.+ */+ y_max: number;+ }[];+ /**+ * Reasoning trace for the `query` task when reasoning=true. Null otherwise.+ */+ reasoning?: {+ /**+ * Reasoning text.+ */+ text: string;+ /**+ * Grounding information.+ */+ grounding?: {}[];+ };+}+declare abstract class Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B {+ inputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input;+ postProcessedOutputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output;+}+declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731 {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813 {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+declare abstract class Base_Ai_Cf_Qwen_Qwen3_8_27B {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_3_Flash {+ inputs: ChatCompletionsInput;+ postProcessedOutputs: ChatCompletionsOutput;+}+interface AiModels {+ "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification;+ "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage;+ "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage;+ "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage;+ "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage;+ "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage;+ "@cf/myshell-ai/melotts": BaseAiTextToSpeech;+ "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings;+ "@cf/microsoft/resnet-50": BaseAiImageClassification;+ "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration;+ "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration;+ "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration;+ "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration;+ "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration;+ "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration;+ "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration;+ "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration;+ "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration;+ "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration;+ "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration;+ "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration;+ "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration;+ "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration;+ "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration;+ "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration;+ "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration;+ "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration;+ "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration;+ "@cf/microsoft/phi-2": BaseAiTextGeneration;+ "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration;+ "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration;+ "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration;+ "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration;+ "@hf/google/gemma-7b-it": BaseAiTextGeneration;+ "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration;+ "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration;+ "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration;+ "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration;+ "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration;+ "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration;+ "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration;+ "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration;+ "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration;+ "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration;+ "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration;+ "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration;+ "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration;+ "@cf/facebook/bart-large-cnn": BaseAiSummarization;+ "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText;+ "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5;+ "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper;+ "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B;+ "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5;+ "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5;+ "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M;+ "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En;+ "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo;+ "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3;+ "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell;+ "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct;+ "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast;+ "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B;+ "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base;+ "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct;+ "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B;+ "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct;+ "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It;+ "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct;+ "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8;+ "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3;+ "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B;+ "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2;+ "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B;+ "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B;+ "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0;+ "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin;+ "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1;+ "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B;+ "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It;+ "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B;+ "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux;+ "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En;+ "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es;+ "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev;+ "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B;+ "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B;+ "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash;+ "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5;+ "@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6;+ "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B;+ "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT;+ "@cf/moonshotai/kimi-k2.7-code": Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code;+ "@cf/zai-org/glm-5.2": Base_Ai_Cf_Zai_Org_Glm_5_2;+ "@cf/moondream/moondream3.1-9B-A2B": Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B;+ "@cf/deepseek-ai/deepseek-v4-flash-0731": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731;+ "@cf/deepseek-ai/deepseek-v4-pro-0813": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813;+ "@cf/qwen/qwen3.8-27b": Base_Ai_Cf_Qwen_Qwen3_8_27B;+ "@cf/zai-org/glm-5.3-flash": Base_Ai_Cf_Zai_Org_Glm_5_3_Flash;+}+type AiOptions = {+ /**+ * Send requests as an asynchronous batch job, only works for supported models+ * https://developers.cloudflare.com/workers-ai/features/batch-api+ */+ queueRequest?: boolean;+ /**+ * Establish websocket connections, only works for supported models+ */+ websocket?: boolean;+ /**+ * Tag your requests to group and view them in Cloudflare dashboard.+ *+ * Rules:+ * Tags must only contain letters, numbers, and the symbols: : - . / @+ * Each tag can have maximum 50 characters.+ * Maximum 5 tags are allowed each request.+ * Duplicate tags will removed.+ */+ tags?: string[];+ gateway?: GatewayOptions;+ returnRawResponse?: boolean;+ prefix?: string;+ extraHeaders?: object;+ signal?: AbortSignal;+};+type AiModelsSearchParams = {+ author?: string;+ hide_experimental?: boolean;+ page?: number;+ per_page?: number;+ search?: string;+ source?: number;+ task?: string;+};+type AiModelsSearchObject = {+ id: string;+ source: number;+ name: string;+ description: string;+ task: {+ id: string;+ name: string;+ description: string;+ };+ tags: string[];+ properties: {+ property_id: string;+ value: string;+ }[];+};+type ChatCompletionsBase = ChatCompletionsMessagesInput;+type ChatCompletionsInput = ChatCompletionsMessagesInput;+interface InferenceUpstreamError extends Error {+}+interface AiInternalError extends Error {+}+type AiModelListType = Record<string, any>;+type AiAsyncBatchResponse = {+ request_id: string;+};+declare abstract class Ai<AiModelList extends AiModelListType = AiModels> {+ aiGatewayLogId: string | null;+ gateway(gatewayId: string): AiGateway;+ /**+ * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+ aiSearch(): AiSearchNamespace;+ /**+ * @deprecated AutoRAG has been replaced by AI Search.+ * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ *+ * @param autoragId Instance ID+ */+ autorag(autoragId: string): AutoRAG;+ // Batch request+ run<Name extends keyof AiModelList>(model: Name, inputs: {+ requests: AiModelList[Name]['inputs'][];+ }, options: AiOptions & {+ queueRequest: true;+ }): Promise<AiAsyncBatchResponse>;+ // Raw response+ run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {+ returnRawResponse: true;+ }): Promise<Response>;+ // WebSocket+ run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {+ websocket: true;+ }): Promise<Response>;+ // Streaming+ run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'] & {+ stream: true;+ }, options?: AiOptions): Promise<ReadableStream>;+ // Normal (default) - known model+ run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise<AiModelList[Name]['postProcessedOutputs']>;+ // Unknown model (fallback).+ //+ // The `Exclude<..., keyof AiModelList>` constraint forces TypeScript to+ // route any model name that is a literal key of `AiModelList` to one of+ // the known-model overloads above (so input/output mismatches surface as+ // type errors rather than silently falling back to `Record<string, unknown>`).+ // Names that aren't in `AiModelList` — e.g. third-party gateway models+ // like `"google/nano-banana"` — still hit this overload.+ run<Model extends string>(model: Model extends keyof AiModelList ? never : Model, inputs: Record<string, unknown>, options?: AiOptions): Promise<Record<string, unknown>>;+ models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;+ toMarkdown(): ToMarkdownService;+ toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;+ toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;+}+type GatewayRetries = {+ maxAttempts?: 1 | 2 | 3 | 4 | 5;+ retryDelayMs?: number;+ backoff?: 'constant' | 'linear' | 'exponential';+};+type GatewayOptions = {+ id: string;+ cacheKey?: string;+ cacheTtl?: number;+ skipCache?: boolean;+ metadata?: Record<string, number | string | boolean | null | bigint>;+ collectLog?: boolean;+ eventId?: string;+ requestTimeoutMs?: number;+ retries?: GatewayRetries;+};+type UniversalGatewayOptions = Exclude<GatewayOptions, 'id'> & {+ /**+ ** @deprecated+ */+ id?: string;+};+type AiGatewayPatchLog = {+ score?: number | null;+ feedback?: -1 | 1 | null;+ metadata?: Record<string, number | string | boolean | null | bigint> | null;+};+type AiGatewayLog = {+ id: string;+ provider: string;+ model: string;+ model_type?: string;+ path: string;+ duration: number;+ request_type?: string;+ request_content_type?: string;+ status_code: number;+ response_content_type?: string;+ success: boolean;+ cached: boolean;+ tokens_in?: number;+ tokens_out?: number;+ metadata?: Record<string, number | string | boolean | null | bigint>;+ step?: number;+ cost?: number;+ custom_cost?: boolean;+ request_size: number;+ request_head?: string;+ request_head_complete: boolean;+ response_size: number;+ response_head?: string;+ response_head_complete: boolean;+ created_at: Date;+};+type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly';+type AIGatewayHeaders = {+ 'cf-aig-metadata': Record<string, number | string | boolean | null | bigint> | string;+ 'cf-aig-custom-cost': {+ per_token_in?: number;+ per_token_out?: number;+ } | {+ total_cost?: number;+ } | string;+ 'cf-aig-cache-ttl': number | string;+ 'cf-aig-skip-cache': boolean | string;+ 'cf-aig-cache-key': string;+ 'cf-aig-event-id': string;+ 'cf-aig-request-timeout': number | string;+ 'cf-aig-max-attempts': number | string;+ 'cf-aig-retry-delay': number | string;+ 'cf-aig-backoff': string;+ 'cf-aig-collect-log': boolean | string;+ Authorization: string;+ 'Content-Type': string;+ [key: string]: string | number | boolean | object;+};+type AIGatewayUniversalRequest = {+ provider: AIGatewayProviders | string; // eslint-disable-line+ endpoint: string;+ headers: Partial<AIGatewayHeaders>;+ query: unknown;+};+interface AiGatewayInternalError extends Error {+}+interface AiGatewayLogNotFound extends Error {+}+declare abstract class AiGateway {+ patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;+ getLog(logId: string): Promise<AiGatewayLog>;+ run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: {+ gateway?: UniversalGatewayOptions;+ extraHeaders?: object;+ signal?: AbortSignal;+ }): Promise<Response>;+ getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line+}+// Copyright (c) 2022-2025 Cloudflare, Inc.+// Licensed under the Apache 2.0 license found in the LICENSE file or at:+// https://opensource.org/licenses/Apache-2.0+/**+ * Artifacts — Git-compatible file storage on Cloudflare Workers.+ *+ * Provides programmatic access to create, manage, and fork repositories,+ * and to issue and revoke scoped access tokens.+ */+/** Information about a repository. */+interface ArtifactsRepoInfo {+ /** Unique repository ID. */+ id: string;+ /** Repository name. */+ name: string;+ /** Repository description, or null if not set. */+ description: string | null;+ /** Default branch name (e.g. "main"). */+ defaultBranch: string;+ /** ISO 8601 creation timestamp. */+ createdAt: string;+ /** ISO 8601 last-updated timestamp. */+ updatedAt: string;+ /** ISO 8601 timestamp of the last push, or null if never pushed. */+ lastPushAt: string | null;+ /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */+ source: string | null;+ /** Whether the repository is read-only. */+ readOnly: boolean;+ /** HTTPS git remote URL. */+ remote: string;+}+/** Result of creating a repository — includes the initial access token. */+interface ArtifactsCreateRepoResult {+ /** Unique repository ID. */+ id: string;+ /** Repository name. */+ name: string;+ /** Repository description, or null if not set. */+ description: string | null;+ /** Default branch name. */+ defaultBranch: string;+ /** HTTPS git remote URL. */+ remote: string;+ /** Plaintext access token (only returned at creation time). */+ token: string;+ /** ISO 8601 token expiry timestamp. */+ tokenExpiresAt: string;+}+/** Paginated list of repositories. */+interface ArtifactsRepoListResult {+ /** Repositories in this page (without the `remote` field). */+ repos: Omit<ArtifactsRepoInfo, 'remote'>[];+ /** Total number of repositories in the namespace. */+ total: number;+ /** Cursor for the next page, if there are more results. */+ cursor?: string;+}+/** Result of creating an access token. */+interface ArtifactsCreateTokenResult {+ /** Unique token ID. */+ id: string;+ /** Plaintext token (only returned at creation time). */+ plaintext: string;+ /** Token scope: "read" or "write". */+ scope: 'read' | 'write';+ /** ISO 8601 token expiry timestamp. */+ expiresAt: string;+}+/** Token metadata (no plaintext). */+interface ArtifactsTokenInfo {+ /** Unique token ID. */+ id: string;+ /** Token scope: "read" or "write". */+ scope: 'read' | 'write';+ /** Token state: "active", "expired", or "revoked". */+ state: 'active' | 'expired' | 'revoked';+ /** ISO 8601 creation timestamp. */+ createdAt: string;+ /** ISO 8601 expiry timestamp. */+ expiresAt: string;+}+/** Paginated list of tokens for a repository. */+interface ArtifactsTokenListResult {+ /** Tokens in this page. */+ tokens: ArtifactsTokenInfo[];+ /** Total number of tokens for the repository. */+ total: number;+}+/**+ * Handle for a single repository. Returned by Artifacts.get().+ *+ * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.+ */+interface ArtifactsRepo extends ArtifactsRepoInfo {+ /**+ * Create an access token for this repo.+ * @param scope Token scope: "write" (default) or "read".+ * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000).+ * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range.+ */+ createToken(scope?: 'write' | 'read', ttl?: number): Promise<ArtifactsCreateTokenResult>;+ /** List tokens for this repo (metadata only, no plaintext). */+ listTokens(): Promise<ArtifactsTokenListResult>;+ /**+ * Revoke a token by plaintext or ID.+ * @param tokenOrId Plaintext token or token ID.+ * @returns true if revoked, false if not found.+ * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty.+ */+ revokeToken(tokenOrId: string): Promise<boolean>;+ // ── Fork ──+ /**+ * Fork this repo to a new repo.+ * @param name Target repository name.+ * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true).+ * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.+ * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.+ * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running.+ */+ fork(name: string, opts?: {+ description?: string;+ readOnly?: boolean;+ defaultBranchOnly?: boolean;+ }): Promise<ArtifactsCreateRepoResult>;+}+// ── Error types ──────────────────────────────────────────────────────────────+/**+ * Error codes returned by Artifacts binding operations.+ *+ * Each code maps to a numeric code available on `ArtifactsError.numericCode`.+ */+type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR';+/**+ * Error thrown by Artifacts binding operations.+ *+ * Uses a string `.code` discriminator following the Cloudflare platform+ * convention (StreamError, ImagesError, etc.). The `.numericCode` matches+ * the REST API `errors[].code` values.+ */+interface ArtifactsError extends Error {+ readonly name: 'ArtifactsError';+ /** String error code for programmatic matching. */+ readonly code: ArtifactsErrorCode;+ /** Numeric error code matching the REST API. */+ readonly numericCode: number;+}+// ── Binding ──────────────────────────────────────────────────────────────────+/**+ * Artifacts binding — namespace-level operations.+ *+ * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.+ */+interface Artifacts {+ /**+ * Create a new repository with an initial access token.+ * @param name Repository name (alphanumeric, dots, hyphens, underscores).+ * @param opts Optional: readOnly flag, description, default branch name.+ * @returns Repo metadata with initial token.+ * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.+ * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists.+ */+ create(name: string, opts?: {+ readOnly?: boolean;+ description?: string;+ setDefaultBranch?: string;+ }): Promise<ArtifactsCreateRepoResult>;+ /**+ * Get a handle to an existing repository.+ * @param name Repository name.+ * @returns Repo handle.+ * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist.+ * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing.+ * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking.+ */+ get(name: string): Promise<ArtifactsRepo>;+ /**+ * Import a repository from an external git remote.+ * @param params Source URL and optional branch/depth, plus target name and options.+ * @returns Repo metadata with initial token.+ * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid.+ * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS.+ * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository.+ * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication.+ * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist.+ * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached.+ * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits.+ * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.+ */+ import(params: {+ source: {+ url: string;+ branch?: string;+ depth?: number;+ };+ target: {+ name: string;+ opts?: {+ description?: string;+ readOnly?: boolean;+ };+ };+ }): Promise<ArtifactsCreateRepoResult>;+ /**+ * List repositories with cursor-based pagination.+ * @param opts Optional: limit (1–200, default 50), cursor for next page.+ */+ list(opts?: {+ limit?: number;+ cursor?: string;+ }): Promise<ArtifactsRepoListResult>;+ /**+ * Delete a repository and all associated tokens.+ * @param name Repository name.+ * @returns true if deleted, false if not found.+ * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.+ */+ delete(name: string): Promise<boolean>;+}+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+interface AutoRAGInternalError extends Error {+}+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+interface AutoRAGNotFoundError extends Error {+}+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+interface AutoRAGUnauthorizedError extends Error {+}+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+interface AutoRAGNameNotSetError extends Error {+}+type ComparisonFilter = {+ key: string;+ type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';+ value: string | number | boolean;+};+type CompoundFilter = {+ type: 'and' | 'or';+ filters: ComparisonFilter[];+};+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+type AutoRagSearchRequest = {+ query: string;+ filters?: CompoundFilter | ComparisonFilter;+ max_num_results?: number;+ ranking_options?: {+ ranker?: string;+ score_threshold?: number;+ };+ reranking?: {+ enabled?: boolean;+ model?: string;+ };+ rewrite_query?: boolean;+};+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+type AutoRagAiSearchRequest = AutoRagSearchRequest & {+ stream?: boolean;+ system_prompt?: string;+};+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+type AutoRagAiSearchRequestStreaming = Omit<AutoRagAiSearchRequest, 'stream'> & {+ stream: true;+};+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+type AutoRagSearchResponse = {+ object: 'vector_store.search_results.page';+ search_query: string;+ data: {+ file_id: string;+ filename: string;+ score: number;+ attributes: Record<string, string | number | boolean | null>;+ content: {+ type: 'text';+ text: string;+ }[];+ }[];+ has_more: boolean;+ next_page: string | null;+};+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+type AutoRagListResponse = {+ id: string;+ enable: boolean;+ type: string;+ source: string;+ vectorize_name: string;+ paused: boolean;+ status: string;+}[];+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+type AutoRagAiSearchResponse = AutoRagSearchResponse & {+ response: string;+};+/**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+declare abstract class AutoRAG {+ /**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+ list(): Promise<AutoRagListResponse>;+ /**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+ search(params: AutoRagSearchRequest): Promise<AutoRagSearchResponse>;+ /**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+ aiSearch(params: AutoRagAiSearchRequestStreaming): Promise<Response>;+ /**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+ aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse>;+ /**+ * @deprecated Use the standalone AI Search Workers binding instead.+ * See https://developers.cloudflare.com/ai-search/usage/workers-binding/+ */+ aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse | Response>;+}+type BrowserRunLifecycleEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';+type BrowserRunResourceType = 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'prefetch' | 'eventsource' | 'websocket' | 'manifest' | 'signedexchange' | 'ping' | 'cspviolationreport' | 'preflight' | 'other';+/** Options fields shared by all quick actions. */+interface BrowserRunBaseOptions {+ /** Adds `<script>` tags into the page with the desired URL or content.+ * @see https://pptr.dev/api/puppeteer.frameaddscripttagoptions+ */+ addScriptTag?: Array<{+ content?: string;+ url?: string;+ type?: string;+ id?: string;+ }>;+ /** Adds `<link rel="stylesheet">` or `<style>` tags into the page.+ * @see https://pptr.dev/api/puppeteer.frameaddstyletagoptions+ */+ addStyleTag?: Array<{+ content?: string;+ url?: string;+ }>;+ /** Provide credentials for HTTP authentication. @see https://pptr.dev/api/puppeteer.credentials */+ authenticate?: {+ username: string;+ password: string;+ };+ /** Set cookies before navigating. @see https://pptr.dev/api/puppeteer.cookieparam */+ cookies?: Array<{+ name: string;+ value: string;+ url?: string;+ domain?: string;+ path?: string;+ secure?: boolean;+ httpOnly?: boolean;+ sameSite?: 'Strict' | 'Lax' | 'None';+ expires?: number;+ priority?: 'Low' | 'Medium' | 'High';+ sameParty?: boolean;+ sourceScheme?: 'Unset' | 'NonSecure' | 'Secure';+ sourcePort?: number;+ partitionKey?: string;+ }>;+ /** Emulate a specific CSS media type (e.g. `"screen"`, `"print"`). */+ emulateMediaType?: string;+ /** Navigation options. @see https://pptr.dev/api/puppeteer.gotooptions */+ gotoOptions?: {+ /** Navigation timeout in milliseconds (max 60 000). @default 30000 */+ timeout?: number;+ /** When to consider navigation complete. @default "domcontentloaded" */+ waitUntil?: BrowserRunLifecycleEvent | BrowserRunLifecycleEvent[];+ referer?: string;+ referrerPolicy?: string;+ };+ /** Block requests matching these regex patterns. Mutually exclusive with `allowRequestPattern`. */+ rejectRequestPattern?: string[];+ /** Only allow requests matching these regex patterns. Mutually exclusive with `rejectRequestPattern`. */+ allowRequestPattern?: string[];+ /** Block requests of these resource types. Mutually exclusive with `allowResourceTypes`. */+ rejectResourceTypes?: BrowserRunResourceType[];+ /** Only allow requests of these resource types. Mutually exclusive with `rejectResourceTypes`. */+ allowResourceTypes?: BrowserRunResourceType[];+ /** Additional HTTP headers sent with every request. */+ setExtraHTTPHeaders?: Record<string, string>;+ /** Whether JavaScript is enabled on the page. */+ setJavaScriptEnabled?: boolean;+ /** Override the default user agent string.+ * @default "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"+ * */+ userAgent?: string;+ /** Set the browser viewport size.+ * @see https://pptr.dev/api/puppeteer.viewport+ * @default {width:1920,height:1080}+ * */+ viewport?: {+ width: number;+ height: number;+ deviceScaleFactor?: number;+ isMobile?: boolean;+ isLandscape?: boolean;+ hasTouch?: boolean;+ };+ /** Wait for a CSS selector to appear in the page before proceeding.+ * @see https://pptr.dev/api/puppeteer.waitforselectoroptions+ */+ waitForSelector?: {+ selector: string;+ hidden?: true;+ visible?: true;+ /** Timeout in milliseconds. Max 120000 */+ timeout?: number;+ };+ /** Wait for a fixed delay in milliseconds before proceeding. Max 120000 */+ waitForTimeout?: number;+ /** When true, continue on best-effort when awaited events fail or timeout. */+ bestAttempt?: boolean;+ /** Maximum duration in milliseconds for the browser action after page load. Max 120000 */+ actionTimeout?: number;+ /** Cache time to live in seconds (0-86400). Set to 0 to disable.+ * @default 5+ */+ cacheTTL?: number;+}+/**+ * Backend selection, mixed into the options of the quick actions that support it.+ * Deliberately not part of `BrowserRunBaseOptions`: `scrape`, `links` and `snapshot`+ * reject an alternate backend, so they must not accept the field.+ */+interface BrowserRunAlternateBackendOptions {+ /** Render with an alternate browser backend instead of the default one. */+ browser?: 'kitesurf';+}+/** Common options shared by all quick actions. Exactly one of `url` or `html` must be provided.*/+type BrowserRunCommonOptions = (BrowserRunBaseOptions & {+ /** URL to navigate to, e.g. `"https://example.com"`. */+ url: string;+}) | (BrowserRunBaseOptions & {+ /** Set the HTML content of the page directly. */+ html: string;+});+type BrowserRunPuppeteerScreenshotOptions = {+ /** @default "png" */+ type?: 'png' | 'jpeg' | 'webp';+ /** @default "binary" */+ encoding?: 'binary' | 'base64';+ quality?: number;+ fullPage?: boolean;+ clip?: {+ x: number;+ y: number;+ width: number;+ height: number;+ scale?: number;+ };+ omitBackground?: boolean;+ optimizeForSpeed?: boolean;+ captureBeyondViewport?: boolean;+ fromSurface?: boolean;+};+type BrowserRunScreenshotOptions = BrowserRunCommonOptions & {+ /** CSS selector of the element to screenshot. */+ selector?: string;+ /** When true, scroll the entire page before taking the screenshot. */+ scrollPage?: boolean;+ /** @see https://pptr.dev/api/puppeteer.screenshotoptions */+ screenshotOptions?: BrowserRunPuppeteerScreenshotOptions;+} & BrowserRunAlternateBackendOptions;+type BrowserRunPDFOptions = BrowserRunCommonOptions & {+ /** @see https://pptr.dev/api/puppeteer.pdfoptions */+ pdfOptions?: {+ /** @default 1 */+ scale?: number;+ /** @default false */+ displayHeaderFooter?: boolean;+ headerTemplate?: string;+ footerTemplate?: string;+ /** @default false */+ printBackground?: boolean;+ /** @default false */+ landscape?: boolean;+ pageRanges?: string;+ /** @default "letter" */+ format?: 'letter' | 'legal' | 'tabloid' | 'ledger' | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';+ width?: string | number;+ height?: string | number;+ /** @default false */+ preferCSSPageSize?: boolean;+ margin?: {+ top?: string | number;+ right?: string | number;+ bottom?: string | number;+ left?: string | number;+ };+ /** @default false */+ omitBackground?: boolean;+ /** @default true */+ tagged?: boolean;+ /** @default false */+ outline?: boolean;+ /** @default 30000 */+ timeout?: number;+ };+} & BrowserRunAlternateBackendOptions;+type BrowserRunScrapeOptions = BrowserRunCommonOptions & {+ /** CSS selectors to scrape. At least one element is required. */+ elements: Array<{+ selector: string;+ }>;+};+type BrowserRunLinksOptions = BrowserRunCommonOptions & {+ /** When true, only return links that are visible on the page. @default false */+ visibleLinksOnly?: boolean;+ /** When true, exclude links pointing to external domains. @default false */+ excludeExternalLinks?: boolean;+};+type BrowserRunSnapshotFormat = 'content' | 'screenshot' | 'markdown' | 'accessibilityTree';+type BrowserRunSnapshotOptions = BrowserRunCommonOptions & {+ /** Which representations of the page to return. At least two distinct formats+ * are required; request a single format from its dedicated action instead.+ * @default ["content","screenshot"]+ */+ formats?: BrowserRunSnapshotFormat[];+ /** @see https://pptr.dev/api/puppeteer.screenshotoptions */+ screenshotOptions?: Omit<BrowserRunPuppeteerScreenshotOptions, 'encoding'>;+};+/** Options for the `accessibilityTree` quick action. */+type BrowserRunAccessibilityTreeOptions = BrowserRunCommonOptions & {+ /** When true, prune nodes that carry no semantic meaning, such as generic+ * containers. Defaults to true, or to false when `root` is set so that the+ * requested subtree is returned as-is.+ */+ interestingOnly?: boolean;+ /** CSS selector limiting the tree to the matching element's subtree.+ * A selector that matches nothing yields `accessibilityTree: null` with+ * HTTP 200; a malformed selector is an error.+ */+ root?: string;+} & BrowserRunAlternateBackendOptions;+interface BrowserRunJsonBaseOptions {+ /** Custom AI models to try in order. Max 3. Falls back to next on error. */+ custom_ai?: Array<{+ /** Model ID in `<provider>/<model_name>` format, e.g. `"workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast"`. */+ model: string;+ /** Bearer token. Not needed for workers-ai models. */+ authorization?: string;+ }>;+}+/**+ * Options for the `json` quick action.+ * At least one of `prompt` or `response_format` must be provided.+ */+type BrowserRunJsonOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions & BrowserRunJsonBaseOptions & ({+ /** Natural-language prompt describing what data to extract. */+ prompt: string;+ /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */+ response_format?: AiTextGenerationResponseFormat;+} | {+ /** Natural-language prompt describing what data to extract. */+ prompt?: string;+ /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */+ response_format: AiTextGenerationResponseFormat;+});+type BrowserRunContentOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;+type BrowserRunMarkdownOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;+type BrowserRunRedirectHop = {+ /** URL that returned the redirect. */+ url: string;+ /** HTTP status of the redirect. */+ status: number;+ /** Redirect response headers, including `location`. */+ headers: Record<string, string>;+};+type BrowserRunResponseMeta = {+ /** HTTP status code of the rendered page */+ status: number;+ /** Page title */+ title: string;+ /** Origin response headers, lowercased. Repeated headers are joined with a newline. Credential and transport-only headers that do not survive rendering are omitted. */+ headers?: Record<string, string>;+ /** URL that served the response, after any redirects the browser followed. */+ finalUrl?: string;+ /** HTTP redirects followed to reach `finalUrl`, oldest first. Omitted for direct navigation and for client-side redirects such as meta refresh. An empty array means redirects occurred but their intermediate responses could not be read. */+ redirectChain?: BrowserRunRedirectHop[];+};+/**+ * A node in the page's accessibility tree, as exposed to assistive technology.+ * `role` is the only field always present; the rest are populated when the+ * underlying element defines them.+ * @see https://pptr.dev/api/puppeteer.serializedaxnode+ */+interface BrowserRunSerializedAXNode {+ /** The ARIA role, e.g. `"button"`, `"heading"`, `"RootWebArea"`. */+ role: string;+ /** The `aria-autocomplete` value. */+ autocomplete?: string;+ /** Checked state of a checkbox, radio, or menu item. */+ checked?: boolean | 'mixed';+ /** Accessible description, typically from `aria-describedby` or `title`. */+ description?: string;+ disabled?: boolean;+ expanded?: boolean;+ /** Whether the element currently holds keyboard focus. */+ focused?: boolean;+ /** The kind of popup the element triggers, e.g. `"menu"`, `"dialog"`. */+ haspopup?: string;+ /** The `aria-invalid` value. */+ invalid?: string;+ /** Keyboard shortcuts bound to the element, from `aria-keyshortcuts`. */+ keyshortcuts?: string;+ /** Hierarchical level, e.g. the heading level of an `<h2>`. */+ level?: number;+ /** Whether the element is a modal dialog. */+ modal?: boolean;+ /** Whether a text input accepts multiple lines. */+ multiline?: boolean;+ /** Whether more than one option can be selected. */+ multiselectable?: boolean;+ /** Accessible name, e.g. a button's label or an image's alt text. */+ name?: string;+ orientation?: string;+ /** Pressed state of a toggle button. */+ pressed?: boolean | 'mixed';+ readonly?: boolean;+ required?: boolean;+ /** Author-supplied role description, from `aria-roledescription`. */+ roledescription?: string;+ selected?: boolean;+ /** Current value of an input or range element. */+ value?: string | number;+ valuemax?: number;+ valuemin?: number;+ /** Human-readable form of `value`, from `aria-valuetext`. */+ valuetext?: string;+ /** Child nodes. Absent for leaf nodes. */+ children?: BrowserRunSerializedAXNode[];+}+/** Success response for `content` action. */+type BrowserRunContentSuccessResponse = {+ success: true;+ /** Extracted HTML content */+ result: string;+ meta: BrowserRunResponseMeta;+};+/** Success response for `links` action. */+type BrowserRunLinksSuccessResponse = {+ success: true;+ /** Extracted links */+ result: string[];+ meta: BrowserRunResponseMeta;+};+/** Success response for `scrape` action. */+type BrowserRunScrapeSuccessResponse = {+ success: true;+ result: Array<{+ /** The CSS selector used to find elements. */+ selector: string;+ /** Array of elements matching the selector. */+ results: Array<{+ /** Outer HTML of the element. */+ html: string;+ /** Text content of the element. */+ text: string;+ /** Width of the element in pixels. */+ width: number;+ /** Height of the element in pixels. */+ height: number;+ /** Top position of the element relative to the viewport in pixels. */+ top: number;+ /** Left position of the element relative to the viewport in pixels. */+ left: number;+ /** Array of HTML attributes on the element. */+ attributes: Array<{+ /** Attribute name. */+ name: string;+ /** Attribute value. */+ value: string;+ }>;+ }>;+ }>;+ meta: BrowserRunResponseMeta;+};+/** Success response for `snapshot` action. Each field is present only when the+ * corresponding entry was requested in `formats`.+ */+type BrowserRunSnapshotSuccessResponse = {+ success: true;+ result: {+ /** HTML content of the page. */+ content?: string;+ /** Base64-encoded screenshot image. */+ screenshot?: string;+ /** Markdown content. Prefixed with YAML frontmatter (e.g. `title`) when the+ * page provides that metadata.+ */+ markdown?: string;+ /** Root of the page's accessibility tree. */+ accessibilityTree?: BrowserRunSerializedAXNode;+ };+ meta: BrowserRunResponseMeta;+};+/** Success response for `accessibilityTree` action. */+type BrowserRunAccessibilityTreeSuccessResponse = {+ success: true;+ result: {+ /** Root of the accessibility tree, or `null` when `root` matched no element. */+ accessibilityTree: BrowserRunSerializedAXNode | null;+ };+ meta: BrowserRunResponseMeta;+};+/** Success response for `json` action. */+type BrowserRunJsonSuccessResponse = {+ success: true;+ /** JSON data extracted from the page using an AI model */+ result: Record<string, unknown>;+ meta: BrowserRunResponseMeta;+};+/** Success response for `markdown` action. */+type BrowserRunMarkdownSuccessResponse = {+ success: true;+ /** Extracted markdown content */+ result: string;+ meta: BrowserRunResponseMeta;+};+/** Error response for BrowserRun actions. */+type BrowserRunErrorResponse = {+ success: false;+ errors: {+ message: string;+ code?: number;+ detail?: string;+ path?: string;+ }[];+};+/** Error response for BrowserRun `json` action. */+type BrowserRunJsonErrorResponse = BrowserRunErrorResponse & {+ /** Raw AI response text for debugging */+ rawAiResponse?: string;+};+/**+ * Browser Run API binding for automating headless browsers.+ * @see https://developers.cloudflare.com/browser-run/+ */+declare abstract class BrowserRun {+ /**+ * Send a raw HTTP request to the Browser Run API.+ * Used by libraries like `@cloudflare/puppeteer` to acquire and connect to a browser instance.+ * @see https://developers.cloudflare.com/browser-run/+ */+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;+ /**+ * Take a screenshot of a web page.+ * @param action - Must be `'screenshot'`.+ * @param options - Screenshot options including viewport, selectors, and image format.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - Binary image data with `Content-Type: image/png`, `image/jpeg`, or `image/webp` (when `encoding: 'binary'`, the default)+ * - Data URI string with `Content-Type: text/plain` (when `encoding: 'base64'`)+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'screenshot', options: BrowserRunScreenshotOptions): Promise<Response>;+ /**+ * Generate a PDF of a web page.+ * @param action - Must be `'pdf'`.+ * @param options - PDF generation options including page size, margins, and headers/footers.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - Binary PDF data with `Content-Type: application/pdf`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'pdf', options: BrowserRunPDFOptions): Promise<Response>;+ /**+ * Get the HTML content of a web page.+ * @param action - Must be `'content'`.+ * @param options - Navigation and page interaction options.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunContentSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'content', options: BrowserRunContentOptions): Promise<Response>;+ /**+ * Scrape elements from a web page by CSS selector.+ * @param action - Must be `'scrape'`.+ * @param options - Scrape options with CSS selectors for elements to extract.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunScrapeSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'scrape', options: BrowserRunScrapeOptions): Promise<Response>;+ /**+ * Extract all links from a web page.+ * @param action - Must be `'links'`.+ * @param options - Options to filter visible or internal links only.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunLinksSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'links', options: BrowserRunLinksOptions): Promise<Response>;+ /**+ * Get several representations of a web page in one request.+ * @param action - Must be `'snapshot'`.+ * @param options - Snapshot options including the `formats` to return and+ * screenshot settings (encoding is always base64).+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunSnapshotSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'snapshot', options: BrowserRunSnapshotOptions): Promise<Response>;+ /**+ * Extract structured JSON data from a web page using AI.+ * @param action - Must be `'json'`.+ * @param options - JSON extraction options with prompt or response_format schema.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunJsonSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures+ * - HTTP 422/500 for AI extraction failures (may include `rawAiResponse` field)+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'json', options: BrowserRunJsonOptions): Promise<Response>;+ /**+ * Convert a web page to Markdown.+ * @param action - Must be `'markdown'`.+ * @param options - Navigation and page interaction options.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunMarkdownSuccessResponse` JSON with `Content-Type: application/json`+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'markdown', options: BrowserRunMarkdownOptions): Promise<Response>;+ /**+ * Get the accessibility tree of a web page.+ * @param action - Must be `'accessibilityTree'`.+ * @param options - Options to scope the tree to a subtree and to control+ * whether semantically uninteresting nodes are pruned.+ * @returns A `Response` containing one of:+ *+ * **Success (HTTP 200):**+ * - `BrowserRunAccessibilityTreeSuccessResponse` JSON with `Content-Type: application/json`+ * - `result.accessibilityTree` is `null` when `root` matched no element+ *+ * **Error:**+ * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)+ * - HTTP 422 for a malformed `root` selector+ * - HTTP 500 with code `2017` or `2018` when the tree could not be built+ *+ * **Headers:**+ * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)+ */+ quickAction(action: 'accessibilityTree', options: BrowserRunAccessibilityTreeOptions): Promise<Response>;+}+/**+ * In addition to the properties you can set in the RequestInit dict+ * that you pass as an argument to the Request constructor, you can+ * set certain properties of a `cf` object to control how Cloudflare+ * features are applied to that new Request.+ *+ * Note: Currently, these properties cannot be tested in the+ * playground.+ */+interface RequestInitCfProperties extends Record<string, unknown> {+ cacheEverything?: boolean;+ /**+ * A request's cache key is what determines if two requests are+ * "the same" for caching purposes. If a request has the same cache key+ * as some previous request, then we can serve the same cached response for+ * both. (e.g. 'some-key')+ *+ * Only available for Enterprise customers.+ */+ cacheKey?: string;+ /**+ * This allows you to append additional Cache-Tag response headers+ * to the origin response without modifications to the origin server.+ * This will allow for greater control over the Purge by Cache Tag feature+ * utilizing changes only in the Workers process.+ *+ * Only available for Enterprise customers.+ */+ cacheTags?: string[];+ /**+ * Force response to be cached for a given number of seconds. (e.g. 300)+ */+ cacheTtl?: number;+ /**+ * Force response to be cached for a given number of seconds based on the Origin status code.+ * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 })+ */+ cacheTtlByStatus?: Record<string, number>;+ /**+ * Controls whether Cloudflare uses range requests when fetching the response+ * from the origin.+ *+ * - `"on"`: enable origin range requests for this request.+ * - `"off"`: disable origin range requests for this request.+ */+ originRangeRequests?: "on" | "off";+ /** Controls how responses with a `Vary` header are cached for this request. */+ vary?: RequestInitCfPropertiesVary;+ /**+ * Explicit Cache-Control header value to set on the response stored in cache.+ * This gives full control over cache directives (e.g. 'public, max-age=3600, s-maxage=86400').+ *+ * Cannot be used together with `cacheTtl` or the `cache` request option (`no-store`/`no-cache`),+ * as these are mutually exclusive cache control mechanisms. Setting both will throw a TypeError.+ *+ * Can be used together with `cacheTtlByStatus`.+ */+ cacheControl?: string;+ /**+ * Whether the response should be eligible for Cache Reserve storage.+ */+ cacheReserveEligible?: boolean;+ /**+ * Whether to respect strong ETags (as opposed to weak ETags) from the origin.+ */+ respectStrongEtag?: boolean;+ /**+ * Whether to strip ETag headers from the origin response before caching.+ */+ stripEtags?: boolean;+ /**+ * Whether to strip Last-Modified headers from the origin response before caching.+ */+ stripLastModified?: boolean;+ /**+ * Whether to enable Cache Deception Armor, which protects against web cache+ * deception attacks by verifying the Content-Type matches the URL extension.+ */+ cacheDeceptionArmor?: boolean;+ /**+ * Minimum file size in bytes for a response to be eligible for Cache Reserve storage.+ */+ cacheReserveMinimumFileSize?: number;+ scrapeShield?: boolean;+ apps?: boolean;+ /**+ * Controls whether an outbound gRPC-web subrequest from this Worker is+ * converted to gRPC at the Cloudflare edge.+ *+ * - `"passthrough"`: forward the subrequest unchanged as gRPC-web (default).+ * - `"convert"`: convert the gRPC-web subrequest to gRPC at the edge.+ *+ * Provides per-request control over the same edge conversion behavior+ * gated by the `auto_grpc_convert` compatibility flag.+ */+ grpcWeb?: "passthrough" | "convert";+ image?: RequestInitCfPropertiesImage;+ minify?: RequestInitCfPropertiesImageMinify;+ mirage?: boolean;+ polish?: "lossy" | "lossless" | "off";+ r2?: RequestInitCfPropertiesR2;+ /**+ * Redirects the request to an alternate origin server. You can use this,+ * for example, to implement load balancing across several origins.+ * (e.g.us-east.example.com)+ *+ * Note - For security reasons, the hostname set in resolveOverride must+ * be proxied on the same Cloudflare zone of the incoming request.+ * Otherwise, the setting is ignored. CNAME hosts are allowed, so to+ * resolve to a host under a different domain or a DNS only domain first+ * declare a CNAME record within your own zone’s DNS mapping to the+ * external hostname, set proxy on Cloudflare, then set resolveOverride+ * to point to that CNAME record.+ */+ resolveOverride?: string;+}+/**+ * Controls how Workers Standard Vary handles a request header listed by an+ * origin `Vary` response header:+ *+ * - `"normalize"`: normalize the request header value before it is used in the+ * cache variance key.+ * - `"passthrough"`: use the raw request header value in the cache variance+ * key.+ * - `"bypass"`: bypass cache when the header appears in the origin `Vary`+ * response header.+ */+type RequestInitCfPropertiesVaryAction = "normalize" | "passthrough" | "bypass";+/** Configuration for Workers Standard Vary support. */+interface RequestInitCfPropertiesVary {+ /** The fallback action for varied request headers not listed in `headers`. */+ default: RequestInitCfPropertiesVaryHeader;+ /**+ * Lowercase request header names and their Vary configuration.+ *+ * The `accept` header can include `media_types`, the `accept-language`+ * header can include `languages`, and other headers support only `action`.+ */+ headers?: RequestInitCfPropertiesVaryHeaders;+}+/** Common Vary behavior for a single request header. */+interface RequestInitCfPropertiesVaryHeader {+ /** How this request header contributes to cache variance. */+ action: RequestInitCfPropertiesVaryAction;+}+/** Vary behavior for the `accept` request header. */+interface RequestInitCfPropertiesVaryAcceptHeader extends RequestInitCfPropertiesVaryHeader {+ /**+ * Media types to keep when normalizing the `Accept` request header.+ *+ * Named `media_types` to match the serialized `cf.vary` configuration.+ */+ media_types?: string[];+}+/** Vary behavior for the `accept-language` request header. */+interface RequestInitCfPropertiesVaryAcceptLanguageHeader extends RequestInitCfPropertiesVaryHeader {+ /**+ * Language tags to keep when normalizing the `Accept-Language` request+ * header.+ */+ languages?: string[];+}+/**+ * Lowercase request header names and their Vary behavior.+ *+ * The index signature allows arbitrary custom request headers beyond the+ * well-known `accept` and `accept-language` specializations.+ */+interface RequestInitCfPropertiesVaryHeaders {+ accept?: RequestInitCfPropertiesVaryAcceptHeader;+ "accept-language"?: RequestInitCfPropertiesVaryAcceptLanguageHeader;+ [header: string]: RequestInitCfPropertiesVaryHeader | RequestInitCfPropertiesVaryAcceptHeader | RequestInitCfPropertiesVaryAcceptLanguageHeader | undefined;+}+interface BasicImageTransformations {+ /**+ * Maximum width in image pixels. The value must be an integer.+ */+ width?: number;+ /**+ * Maximum height in image pixels. The value must be an integer.+ */+ height?: number;+ /**+ * When cropping with fit: "cover", this defines the side or point that should+ * be left uncropped. The value is either a string+ * "left", "right", "top", "bottom", "auto", or "center" (the default),+ * or an object {x, y} containing focal point coordinates in the original+ * image expressed as fractions ranging from 0.0 (top or left) to 1.0+ * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will+ * crop bottom or left and right sides as necessary, but won’t crop anything+ * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to+ * preserve as much as possible around a point at 20% of the height of the+ * source image.+ */+ gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates;+ /**+ * Specifies how closely the image is cropped toward detected faces when combined+ * with the gravity=face option. Accepts a valid range between 0.0 (includes as much+ * of the background as possible) and 1.0 (crops the image as closely to the face as+ * possible). The default is 0.+ */+ zoom?: number;+ /**+ * Resizing mode as a string. It affects interpretation of width and height+ * options:+ * - scale-down: Similar to contain, but the image is never enlarged. If+ * the image is larger than given width or height, it will be resized.+ * Otherwise its original size will be kept.+ * - scale-up: Similar to contain, but the image is never shrunk. If the+ * image is smaller than the given width or height, it will be resized.+ * Otherwise its original size will be kept.+ * - contain: Resizes to maximum size that fits within the given width and+ * height. If only a single dimension is given (e.g. only width), the+ * image will be shrunk or enlarged to exactly match that dimension.+ * Aspect ratio is always preserved.+ * - cover: Resizes (shrinks or enlarges) to fill the entire area of width+ * and height. If the image has an aspect ratio different from the ratio+ * of width and height, it will be cropped to fit.+ * - crop: The image will be shrunk and cropped to fit within the area+ * specified by width and height. The image will not be enlarged. For images+ * smaller than the given dimensions it's the same as scale-down. For+ * images larger than the given dimensions, it's the same as cover.+ * See also trim.+ * - pad: Resizes to the maximum size that fits within the given width and+ * height, and then fills the remaining area with a background color+ * (white by default). Use of this mode is not recommended, as the same+ * effect can be more efficiently achieved with the contain mode and the+ * CSS object-fit: contain property.+ * - squeeze: Stretches and deforms to the width and height given, even if it+ * breaks aspect ratio+ */+ fit?: "scale-down" | "scale-up" | "contain" | "cover" | "crop" | "pad" | "squeeze";+ /**+ * Allows you to trim your image. Takes dpr into account and is performed before+ * resizing or rotation.+ *+ * It can be used as:+ * - left, top, right, bottom - it will specify the number of pixels to cut+ * off each side+ * - width, height - the width/height you'd like to end up with - can be used+ * in combination with the properties above+ * - border - this will automatically trim the surroundings of an image based on+ * it's color. It consists of three properties:+ * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit)+ * - tolerance: difference from color to treat as color+ * - keep: the number of pixels of border to keep+ */+ trim?: "border" | {+ top?: number;+ bottom?: number;+ left?: number;+ right?: number;+ width?: number;+ height?: number;+ border?: boolean | {+ color?: string;+ tolerance?: number;+ keep?: number;+ };+ };+ /**+ * Background color to add underneath the image. Applies only to images with+ * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…),+ * hsl(…), etc.)+ */+ background?: string;+ /**+ * Flips the images horizontally, vertically, or both. Flipping is applied before+ * rotation, so if you apply flip=h,rotate=90 then the image will be flipped+ * horizontally, then rotated by 90 degrees.+ */+ flip?: 'h' | 'v' | 'hv';+ /**+ * Number of degrees (90, 180, 270) to rotate the image by. width and height+ * options refer to axes after rotation.+ */+ rotate?: 0 | 90 | 180 | 270 | 360;+ /**+ * Strength of sharpening filter to apply to the image. Floating-point+ * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a+ * recommended value for downscaled images.+ */+ sharpen?: number;+ /**+ * Radius of a blur filter (approximate gaussian). Maximum supported radius+ * is 250.+ */+ blur?: number;+ /**+ * Increase contrast by a factor. A value of 1.0 equals no change, a value of+ * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is+ * ignored.+ */+ contrast?: number;+ /**+ * Increase brightness by a factor. A value of 1.0 equals no change, a value+ * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright.+ * 0 is ignored.+ */+ brightness?: number;+ /**+ * Increase exposure by a factor. A value of 1.0 equals no change, a value of+ * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored.+ */+ gamma?: number;+ /**+ * Increase contrast by a factor. A value of 1.0 equals no change, a value of+ * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is+ * ignored.+ */+ saturation?: number;+ /**+ * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it+ * easier to specify higher-DPI sizes in <img srcset>.+ */+ dpr?: number;+ /**+ * Adds a border around the image. The border is added after resizing. Border+ * width takes dpr into account, and can be specified either using a single+ * width property, or individually for each side.+ */+ border?: {+ color: string;+ width: number;+ } | {+ color: string;+ top: number;+ right: number;+ bottom: number;+ left: number;+ };+ /**+ * Image segmentation using artificial intelligence models. Sets pixels not+ * within selected segment area to transparent e.g "foreground" sets every+ * background pixel as transparent.+ */+ segment?: "foreground";+ /**+ * Controls the algorithm used when an image needs to be enlarged. This+ * parameter works with any fit mode that upscales, such as `contain`,+ * `cover`, and `scale-up`. It has no effect when `fit=scale-down` or when+ * the target dimensions are smaller than the source.+ * - interpolate: Uses bicubic interpolation, which may reduce image quality.+ * This is the default behavior when `upscale` is not specified.+ * - generate: Uses AI upscaling to produce sharper, more detailed results+ * when enlarging images.+ */+ upscale?: "interpolate" | "generate";+}+interface BasicImageTransformationsGravityCoordinates {+ x?: number;+ y?: number;+ mode?: 'remainder' | 'box-center';+}+interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {+ /**+ * Absolute URL of the image file to use for the drawing. It can be any of+ * the supported file formats. For drawing of watermarks or non-rectangular+ * overlays we recommend using PNG or WebP images.+ */+ url: string;+ /**+ * Floating-point number between 0 (transparent) and 1 (opaque).+ * For example, opacity: 0.5 makes overlay semitransparent.+ */+ opacity?: number;+ /**+ * - If set to true, the overlay image will be tiled to cover the entire+ * area. This is useful for stock-photo-like watermarks.+ * - If set to "x", the overlay image will be tiled horizontally only+ * (form a line).+ * - If set to "y", the overlay image will be tiled vertically only+ * (form a line).+ */+ repeat?: true | "x" | "y";+ /**+ * How to combine the foreground and backdrop pixels to create the result+ */+ composite?:+ /** Foreground drawn on top of backdrop (default) */+ 'over'+ /** Foreground shown only where backdrop is opaque */+ | 'in'+ /** Foreground drawn on top, but clipped to the backdrop's shape */+ | 'atop'+ /** Foreground shown only where backdrop is transparent */+ | 'out'+ /** Foreground and backdrop visible only where the other is not */+ | 'xor'+ /** Foreground and backdrop channels added (brightening) */+ | 'lighter';+ /**+ * Position of the overlay image relative to a given edge. Each property is+ * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10+ * positions left side of the overlay 10 pixels from the left edge of the+ * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom+ * of the background image.+ *+ * Setting both left & right, or both top & bottom is an error.+ *+ * If no position is specified, the image will be centered.+ */+ top?: number;+ left?: number;+ bottom?: number;+ right?: number;+}+interface RequestInitCfPropertiesImage extends BasicImageTransformations {+ /**+ * Quality setting from 1-100 (useful values are in 60-90 range). Lower values+ * make images look worse, but load faster. The default is 85. It applies only+ * to JPEG and WebP images. It doesn’t have any effect on PNG.+ */+ quality?: number | "low" | "medium-low" | "medium-high" | "high";+ /**+ * Output format to generate. It can be:+ * - avif: generate images in AVIF format.+ * - webp: generate images in Google WebP format. Set quality to 100 to get+ * the WebP-lossless format.+ * - json: instead of generating an image, outputs information about the+ * image, in JSON format. The JSON object will contain image size+ * (before and after resizing), source image’s MIME type, file size, etc.+ * - jpeg: generate images in JPEG format.+ * - png: generate images in PNG format.+ */+ format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg";+ /**+ * Whether to preserve animation frames from input files. Default is true.+ * Setting it to false reduces animations to still images. This setting is+ * recommended when enlarging images or processing arbitrary user content,+ * because large GIF animations can weigh tens or even hundreds of megabytes.+ * It is also useful to set anim:false when using format:"json" to get the+ * response quicker without the number of frames.+ */+ anim?: boolean;+ /**+ * What EXIF data should be preserved in the output image. Note that EXIF+ * rotation and embedded color profiles are always applied ("baked in" into+ * the image), and aren't affected by this option. Note that if the Polish+ * feature is enabled, all metadata may have been removed already and this+ * option may have no effect.+ * - keep: Preserve most of EXIF metadata, including GPS location if there's+ * any.+ * - copyright: Only keep the copyright tag, and discard everything else.+ * This is the default behavior for JPEG files.+ * - none: Discard all invisible EXIF metadata. Currently WebP and PNG+ * output formats always discard metadata.+ */+ metadata?: "keep" | "copyright" | "none";+ /**+ * Overlays are drawn in the order they appear in the array (last array+ * entry is the topmost layer).+ */+ draw?: RequestInitCfPropertiesImageDraw[];+ /**+ * Fetching image from authenticated origin. Setting this property will+ * pass authentication headers (Authorization, Cookie, etc.) through to+ * the origin.+ */+ "origin-auth"?: "share-publicly";+ /**+ * Slightly reduces latency on a cache miss by selecting a+ * quickest-to-compress file format, at a cost of increased file size and+ * lower image quality. It will usually override the format option and choose+ * JPEG over WebP or AVIF. We do not recommend using this option, except in+ * unusual circumstances like resizing uncacheable dynamically-generated+ * images.+ */+ compression?: "fast";+}+interface RequestInitCfPropertiesImageMinify {+ javascript?: boolean;+ css?: boolean;+ html?: boolean;+}+interface RequestInitCfPropertiesR2 {+ /**+ * Colo id of bucket that an object is stored in+ */+ bucketColoId?: number;+}+/**+ * Request metadata provided by Cloudflare's edge.+ */+type IncomingRequestCfProperties<HostMetadata = unknown> = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield;+interface IncomingRequestCfPropertiesBase extends Record<string, unknown> {+ /**+ * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request.+ *+ * @example 395747+ */+ asn?: number;+ /**+ * The organization which owns the ASN of the incoming request.+ *+ * @example "Google Cloud"+ */+ asOrganization?: string;+ /**+ * The original value of the `Accept-Encoding` header if Cloudflare modified it.+ *+ * @example "gzip, deflate, br"+ */+ clientAcceptEncoding?: string;+ /**+ * The number of milliseconds it took for the request to reach your worker.+ *+ * @example 22+ */+ clientTcpRtt?: number;+ /**+ * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code)+ * airport code of the data center that the request hit.+ *+ * @example "DFW"+ */+ colo: string;+ /**+ * Represents the upstream's response to a+ * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html)+ * from cloudflare.+ *+ * For workers with no upstream, this will always be `1`.+ *+ * @example 3+ */+ edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus;+ /**+ * The HTTP Protocol the request used.+ *+ * @example "HTTP/2"+ */+ httpProtocol: string;+ /**+ * The browser-requested prioritization information in the request object.+ *+ * If no information was set, defaults to the empty string `""`+ *+ * @example "weight=192;exclusive=0;group=3;group-weight=127"+ * @default ""+ */+ requestPriority: string;+ /**+ * The TLS version of the connection to Cloudflare.+ * In requests served over plaintext (without TLS), this property is the empty string `""`.+ *+ * @example "TLSv1.3"+ */+ tlsVersion: string;+ /**+ * The cipher for the connection to Cloudflare.+ * In requests served over plaintext (without TLS), this property is the empty string `""`.+ *+ * @example "AEAD-AES128-GCM-SHA256"+ */+ tlsCipher: string;+ /**+ * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake.+ *+ * If the incoming request was served over plaintext (without TLS) this field is undefined.+ */+ tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata;+}+interface IncomingRequestCfPropertiesBotManagementBase {+ /**+ * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot,+ * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human).+ *+ * @example 54+ */+ score: number;+ /**+ * A boolean value that is true if the request comes from a good bot, like Google or Bing.+ * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots).+ */+ verifiedBot: boolean;+ /**+ * A boolean value that is true if the request originates from a+ * Cloudflare-verified proxy service.+ */+ corporateProxy: boolean;+ /**+ * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources.+ */+ staticResource: boolean;+ /**+ * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request).+ */+ detectionIds: number[];+}+interface IncomingRequestCfPropertiesBotManagement {+ /**+ * Results of Cloudflare's Bot Management analysis+ */+ botManagement: IncomingRequestCfPropertiesBotManagementBase;+ /**+ * Duplicate of `botManagement.score`.+ *+ * @deprecated+ */+ clientTrustScore: number;+}+interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement {+ /**+ * Results of Cloudflare's Bot Management analysis+ */+ botManagement: IncomingRequestCfPropertiesBotManagementBase & {+ /**+ * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients+ * across different destination IPs, Ports, and X509 certificates.+ */+ ja3Hash: string;+ };+}+interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> {+ /**+ * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/).+ *+ * This field is only present if you have Cloudflare for SaaS enabled on your account+ * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)).+ */+ hostMetadata?: HostMetadata;+}+interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield {+ /**+ * Information about the client certificate presented to Cloudflare.+ *+ * This is populated when the incoming request is served over TLS using+ * either Cloudflare Access or API Shield (mTLS)+ * and the presented SSL certificate has a valid+ * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number)+ * (i.e., not `null` or `""`).+ *+ * Otherwise, a set of placeholder values are used.+ *+ * The property `certPresented` will be set to `"1"` when+ * the object is populated (i.e. the above conditions were met).+ */+ tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder;+}+/**+ * Metadata about the request's TLS handshake+ */+interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata {+ /**+ * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal+ *+ * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"+ */+ clientHandshake: string;+ /**+ * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal+ *+ * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"+ */+ serverHandshake: string;+ /**+ * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal+ *+ * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"+ */+ clientFinished: string;+ /**+ * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal+ *+ * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"+ */+ serverFinished: string;+}+/**+ * Geographic data about the request's origin.+ */+interface IncomingRequestCfPropertiesGeographicInformation {+ /**+ * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from.+ *+ * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR.+ *+ * If Cloudflare is unable to determine where the request originated this property is omitted.+ *+ * The country code `"T1"` is used for requests originating on TOR.+ *+ * @example "GB"+ */+ country?: Iso3166Alpha2Code | "T1";+ /**+ * If present, this property indicates that the request originated in the EU+ *+ * @example "1"+ */+ isEUCountry?: "1";+ /**+ * A two-letter code indicating the continent the request originated from.+ *+ * @example "AN"+ */+ continent?: ContinentCode;+ /**+ * The city the request originated from+ *+ * @example "Austin"+ */+ city?: string;+ /**+ * Postal code of the incoming request+ *+ * @example "78701"+ */+ postalCode?: string;+ /**+ * Latitude of the incoming request+ *+ * @example "30.27130"+ */+ latitude?: string;+ /**+ * Longitude of the incoming request+ *+ * @example "-97.74260"+ */+ longitude?: string;+ /**+ * Timezone of the incoming request+ *+ * @example "America/Chicago"+ */+ timezone?: string;+ /**+ * If known, the ISO 3166-2 name for the first level region associated with+ * the IP address of the incoming request+ *+ * @example "Texas"+ */+ region?: string;+ /**+ * If known, the ISO 3166-2 code for the first-level region associated with+ * the IP address of the incoming request+ *+ * @example "TX"+ */+ regionCode?: string;+ /**+ * Metro code (DMA) of the incoming request+ *+ * @example "635"+ */+ metroCode?: string;+}+/** Data about the incoming request's TLS certificate */+interface IncomingRequestCfPropertiesTLSClientAuth {+ /** Always `"1"`, indicating that the certificate was presented */+ certPresented: "1";+ /**+ * Result of certificate verification.+ *+ * @example "FAILED:self signed certificate"+ */+ certVerified: Exclude<CertVerificationStatus, "NONE">;+ /** The presented certificate's revokation status.+ *+ * - A value of `"1"` indicates the certificate has been revoked+ * - A value of `"0"` indicates the certificate has not been revoked+ */+ certRevoked: "1" | "0";+ /**+ * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)+ *+ * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"+ */+ certIssuerDN: string;+ /**+ * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)+ *+ * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"+ */+ certSubjectDN: string;+ /**+ * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)+ *+ * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"+ */+ certIssuerDNRFC2253: string;+ /**+ * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)+ *+ * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"+ */+ certSubjectDNRFC2253: string;+ /** The certificate issuer's distinguished name (legacy policies) */+ certIssuerDNLegacy: string;+ /** The certificate subject's distinguished name (legacy policies) */+ certSubjectDNLegacy: string;+ /**+ * The certificate's serial number+ *+ * @example "00936EACBE07F201DF"+ */+ certSerial: string;+ /**+ * The certificate issuer's serial number+ *+ * @example "2489002934BDFEA34"+ */+ certIssuerSerial: string;+ /**+ * The certificate's Subject Key Identifier+ *+ * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"+ */+ certSKI: string;+ /**+ * The certificate issuer's Subject Key Identifier+ *+ * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"+ */+ certIssuerSKI: string;+ /**+ * The certificate's SHA-1 fingerprint+ *+ * @example "6b9109f323999e52259cda7373ff0b4d26bd232e"+ */+ certFingerprintSHA1: string;+ /**+ * The certificate's SHA-256 fingerprint+ *+ * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea"+ */+ certFingerprintSHA256: string;+ /**+ * The effective starting date of the certificate+ *+ * @example "Dec 22 19:39:00 2018 GMT"+ */+ certNotBefore: string;+ /**+ * The effective expiration date of the certificate+ *+ * @example "Dec 22 19:39:00 2018 GMT"+ */+ certNotAfter: string;+ /**+ * The client leaf certificate in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)+ * format (`:base64-DER:`). Empty if no client certificate was presented or if+ * the leaf certificate exceeded 10 KB (see {@link certRFC9440TooLarge}).+ *+ * Suitable for forwarding to an origin via the `Client-Cert` HTTP header.+ */+ certRFC9440: string;+ /**+ * `true` if the leaf certificate exceeded 10 KB and was omitted from+ * {@link certRFC9440}.+ */+ certRFC9440TooLarge: boolean;+ /**+ * The intermediate certificate chain in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)+ * format as a comma-separated list. Empty if no intermediates were sent or+ * if the chain exceeded 16 KB (see {@link certChainRFC9440TooLarge}).+ *+ * Suitable for forwarding to an origin via the `Client-Cert-Chain` HTTP header.+ */+ certChainRFC9440: string;+ /**+ * `true` if the intermediate chain exceeded 16 KB and was omitted from+ * {@link certChainRFC9440}.+ */+ certChainRFC9440TooLarge: boolean;+}+/** Placeholder values for TLS Client Authorization */+interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {+ certPresented: "0";+ certVerified: "NONE";+ certRevoked: "0";+ certIssuerDN: "";+ certSubjectDN: "";+ certIssuerDNRFC2253: "";+ certSubjectDNRFC2253: "";+ certIssuerDNLegacy: "";+ certSubjectDNLegacy: "";+ certSerial: "";+ certIssuerSerial: "";+ certSKI: "";+ certIssuerSKI: "";+ certFingerprintSHA1: "";+ certFingerprintSHA256: "";+ certNotBefore: "";+ certNotAfter: "";+ certRFC9440: "";+ certRFC9440TooLarge: false;+ certChainRFC9440: "";+ certChainRFC9440TooLarge: false;+}+/** Possible outcomes of TLS verification */+declare type CertVerificationStatus =+/** Authentication succeeded */+"SUCCESS"+/** No certificate was presented */+ | "NONE"+/** Failed because the certificate was self-signed */+ | "FAILED:self signed certificate"+/** Failed because the certificate failed a trust chain check */+ | "FAILED:unable to verify the first certificate"+/** Failed because the certificate not yet valid */+ | "FAILED:certificate is not yet valid"+/** Failed because the certificate is expired */+ | "FAILED:certificate has expired"+/** Failed for another unspecified reason */+ | "FAILED";+/**+ * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare.+ */+declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */+/** ISO 3166-1 Alpha-2 codes */+declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW";+/** The 2-letter continent codes Cloudflare uses */+declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA";+type CfProperties<HostMetadata = unknown> = IncomingRequestCfProperties<HostMetadata> | RequestInitCfProperties;+interface D1Meta {+ duration: number;+ size_after: number;+ rows_read: number;+ rows_written: number;+ last_row_id: number;+ changed_db: boolean;+ changes: number;+ /**+ * The region of the database instance that executed the query.+ */+ served_by_region?: string;+ /**+ * The three letters airport code of the colo that executed the query.+ */+ served_by_colo?: string;+ /**+ * True if-and-only-if the database instance that executed the query was the primary.+ */+ served_by_primary?: boolean;+ timings?: {+ /**+ * The duration of the SQL query execution by the database instance. It doesn't include any network time.+ */+ sql_duration_ms: number;+ };+ /**+ * Number of total attempts to execute the query, due to automatic retries.+ * Note: All other fields in the response like `timings` only apply to the last attempt.+ */+ total_attempts?: number;+}+interface D1Response {+ success: true;+ meta: D1Meta & Record<string, unknown>;+ error?: never;+}+type D1Result<T = unknown> = D1Response & {+ results: T[];+};+interface D1ExecResult {+ count: number;+ duration: number;+}+type D1SessionConstraint =+// Indicates that the first query should go to the primary, and the rest queries+// using the same D1DatabaseSession will go to any replica that is consistent with+// the bookmark maintained by the session (returned by the first query).+'first-primary'+// Indicates that the first query can go anywhere (primary or replica), and the rest queries+// using the same D1DatabaseSession will go to any replica that is consistent with+// the bookmark maintained by the session (returned by the first query).+ | 'first-unconstrained';+type D1SessionBookmark = string;+declare abstract class D1Database {+ prepare(query: string): D1PreparedStatement;+ batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;+ exec(query: string): Promise<D1ExecResult>;+ /**+ * Creates a new D1 Session anchored at the given constraint or the bookmark.+ * All queries executed using the created session will have sequential consistency,+ * meaning that all writes done through the session will be visible in subsequent reads.+ *+ * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session.+ */+ withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession;+ /**+ * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases.+ */+ dump(): Promise<ArrayBuffer>;+}+declare abstract class D1DatabaseSession {+ prepare(query: string): D1PreparedStatement;+ batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;+ /**+ * @returns The latest session bookmark across all executed queries on the session.+ * If no query has been executed yet, `null` is returned.+ */+ getBookmark(): D1SessionBookmark | null;+}+declare abstract class D1PreparedStatement {+ bind(...values: unknown[]): D1PreparedStatement;+ first<T = unknown>(colName: string): Promise<T | null>;+ first<T = Record<string, unknown>>(): Promise<T | null>;+ run<T = Record<string, unknown>>(): Promise<D1Result<T>>;+ all<T = Record<string, unknown>>(): Promise<D1Result<T>>;+ raw<T = unknown[]>(options: {+ columnNames: true;+ }): Promise<[+ string[],+ ...T[]+ ]>;+ raw<T = unknown[]>(options?: {+ columnNames?: false;+ }): Promise<T[]>;+}+// `Disposable` was added to TypeScript's standard lib types in version 5.2.+// To support older TypeScript versions, define an empty `Disposable` interface.+// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2,+// but this will ensure type checking on older versions still passes.+// TypeScript's interface merging will ensure our empty interface is effectively+// ignored when `Disposable` is included in the standard lib.+interface Disposable {+}+/**+ * The returned data after sending an email+ */+interface EmailSendResult {+ /**+ * The Email Message ID+ */+ messageId: string;+}+/**+ * An email message that can be sent from a Worker.+ */+interface EmailMessage {+ /**+ * Envelope From attribute of the email message.+ */+ readonly from: string;+ /**+ * Envelope To attribute of the email message.+ */+ readonly to: string;+}+/**+ * An email message that is sent to a consumer Worker and can be rejected/forwarded.+ */+interface ForwardableEmailMessage extends EmailMessage {+ /**+ * Stream of the email message content.+ */+ readonly raw: ReadableStream<Uint8Array>;+ /**+ * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).+ */+ readonly headers: Headers;+ /**+ * Size of the email message content.+ */+ readonly rawSize: number;+ /**+ * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason.+ * @param reason The reject reason.+ * @returns void+ */+ setReject(reason: string): void;+ /**+ * Forward this email message to a verified destination address of the account.+ * @param rcptTo Verified destination address.+ * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).+ * @returns A promise that resolves when the email message is forwarded.+ */+ forward(rcptTo: string, headers?: Headers): Promise<EmailSendResult>;+ /**+ * Reply to the sender of this email message with a new EmailMessage object.+ * @param message The reply message.+ * @returns A promise that resolves when the email message is replied.+ */+ reply(message: EmailMessage): Promise<EmailSendResult>;+ /**+ * Reply to the sender of this email message with a message built from the given+ * fields. Threading headers (In-Reply-To/References) are set automatically.+ * @param builder The reply message contents.+ * @returns A promise that resolves when the email message is replied.+ */+ reply(builder: EmailReplyMessageBuilder): Promise<EmailSendResult>;+}+/** A file attachment for an email message */+type EmailAttachment = {+ disposition: 'inline';+ contentId: string;+ filename: string;+ type: string;+ content: string | ArrayBuffer | ArrayBufferView;+} | {+ disposition: 'attachment';+ contentId?: undefined;+ filename: string;+ type: string;+ content: string | ArrayBuffer | ArrayBufferView;+};+/** An Email Address */+interface EmailAddress {+ name: string;+ email: string;+}+/**+ * Recipient fields for `SendEmail.send()`. At least one of `to`, `cc`, or+ * `bcc` must be provided.+ */+type EmailDestinations = {+ to?: string | EmailAddress | (string | EmailAddress)[];+ cc?: string | EmailAddress | (string | EmailAddress)[];+ bcc?: string | EmailAddress | (string | EmailAddress)[];+} & ({+ to: string | EmailAddress | (string | EmailAddress)[];+} | {+ cc: string | EmailAddress | (string | EmailAddress)[];+} | {+ bcc: string | EmailAddress | (string | EmailAddress)[];+});+/**+ * Fields shared by all composed emails (no recipients). Used directly by+ * `ForwardableEmailMessage.reply()`, which always replies to the original+ * sender, and extended by `EmailMessageBuilder` for `SendEmail.send()`.+ */+interface EmailReplyMessageBuilder {+ from: string | EmailAddress;+ subject: string;+ replyTo?: string | EmailAddress;+ headers?: Record<string, string>;+ text?: string;+ html?: string;+ attachments?: EmailAttachment[];+}+/**+ * Fields for composing an email without constructing raw MIME, for+ * `SendEmail.send()`. Requires at least one of `to`, `cc`, or `bcc`.+ */+type EmailMessageBuilder = EmailReplyMessageBuilder & EmailDestinations;+/**+ * A binding that allows a Worker to send email messages.+ */+interface SendEmail {+ send(message: EmailMessage): Promise<EmailSendResult>;+ send(builder: EmailMessageBuilder): Promise<EmailSendResult>;+}+declare abstract class EmailEvent extends ExtendableEvent {+ readonly message: ForwardableEmailMessage;+}+declare type EmailExportedHandler<Env = unknown, Props = unknown> = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;+declare module "cloudflare:email" {+ let _EmailMessage: {+ prototype: EmailMessage;+ new (from: string, to: string, raw: ReadableStream | string): EmailMessage;+ };+ export { _EmailMessage as EmailMessage };+}+/**+ * Evaluation context for targeting rules.+ * Keys are attribute names (e.g. "userId", "country"), values are the attribute values.+ */+type FlagshipEvaluationContext = Record<string, string | number | boolean>;+interface FlagshipEvaluationDetails<T> {+ flagKey: string;+ value: T;+ variant?: string | undefined;+ reason?: string | undefined;+ errorCode?: string | undefined;+ errorMessage?: string | undefined;+}+interface FlagshipEvaluationError extends Error {+}+/**+ * Feature flags binding for evaluating feature flags from a Cloudflare Workers script.+ *+ * @example+ * ```typescript+ * // Get a boolean flag value with a default+ * const enabled = await env.FLAGS.getBooleanValue('my-feature', false);+ *+ * // Get a flag value with evaluation context for targeting+ * const variant = await env.FLAGS.getStringValue('experiment', 'control', {+ * userId: 'user-123',+ * country: 'US',+ * });+ *+ * // Get full evaluation details including variant and reason+ * const details = await env.FLAGS.getBooleanDetails('my-feature', false);+ * console.log(details.variant, details.reason);+ * ```+ */+declare abstract class Flagship {+ /**+ * Get a flag value without type checking.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Optional default value returned when evaluation fails.+ * @param context Optional evaluation context for targeting rules.+ */+ get(flagKey: string, defaultValue?: unknown, context?: FlagshipEvaluationContext): Promise<unknown>;+ /**+ * Get a boolean flag value.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getBooleanValue(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<boolean>;+ /**+ * Get a string flag value.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getStringValue(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<string>;+ /**+ * Get a number flag value.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getNumberValue(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<number>;+ /**+ * Get an object flag value.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getObjectValue<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<T>;+ /**+ * Get a boolean flag value with full evaluation details.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getBooleanDetails(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<boolean>>;+ /**+ * Get a string flag value with full evaluation details.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getStringDetails(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<string>>;+ /**+ * Get a number flag value with full evaluation details.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getNumberDetails(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<number>>;+ /**+ * Get an object flag value with full evaluation details.+ * @param flagKey The key of the flag to evaluate.+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.+ * @param context Optional evaluation context for targeting rules.+ */+ getObjectDetails<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<T>>;+}+/**+ * Hello World binding to serve as an explanatory example. DO NOT USE+ */+interface HelloWorldBinding {+ /**+ * Retrieve the current stored value+ */+ get(): Promise<{+ value: string;+ ms?: number;+ }>;+ /**+ * Set a new stored value+ */+ set(value: string): Promise<void>;+}+interface Hyperdrive {+ /**+ * Connect directly to Hyperdrive as if it's your database, returning a TCP socket.+ *+ * Calling this method returns an identical socket to if you call+ * `connect("host:port")` using the `host` and `port` fields from this object.+ * Pick whichever approach works better with your preferred DB client library.+ *+ * Note that this socket is not yet authenticated -- it's expected that your+ * code (or preferably, the client library of your choice) will authenticate+ * using the information in this class's readonly fields.+ */+ connect(): Socket;+ /**+ * A valid DB connection string that can be passed straight into the typical+ * client library/driver/ORM. This will typically be the easiest way to use+ * Hyperdrive.+ */+ readonly connectionString: string;+ /*+ * A randomly generated hostname that is only valid within the context of the+ * currently running Worker which, when passed into `connect()` function from+ * the "cloudflare:sockets" module, will connect to the Hyperdrive instance+ * for your database.+ */+ readonly host: string;+ /*+ * A synthetic IPv4 address (in the reserved 240.0.0.0/4 range) that, like the+ * host field, is only valid within the context of the currently running+ * Worker and, when passed into the `connect()` function from the+ * "cloudflare:sockets" module, will connect to the Hyperdrive instance for+ * your database. This is provided for database drivers that require the host+ * to be an IP literal rather than a hostname.+ */+ readonly ip: string;+ /*+ * The port that must be paired the the host field when connecting.+ */+ readonly port: number;+ /*+ * The username to use when authenticating to your database via Hyperdrive.+ * Unlike the host and password, this will be the same every time+ */+ readonly user: string;+ /*+ * The randomly generated password to use when authenticating to your+ * database via Hyperdrive. Like the host field, this password is only valid+ * within the context of the currently running Worker instance from which+ * it's read.+ */+ readonly password: string;+ /*+ * The name of the database to connect to.+ */+ readonly database: string;+}+/**+ * A handle to a dynamically-provisioned Hyperdrive connection, returned by+ * `HyperdriveApi.get()`.+ */+interface HyperdriveDynamic extends Disposable {+ /**+ * The database name to use when connecting through this Hyperdrive.+ */+ readonly database: Promise<string>;+ /*+ * The randomly generated user to use when authenticating to your+ * database via Hyperdrive.+ */+ readonly user: Promise<string>;+ /*+ * The randomly generated password to use when authenticating to your+ * database via Hyperdrive.+ */+ readonly password: Promise<string>;+ /**+ * Open a TCP socket to the target database through this Hyperdrive.+ *+ */+ connect(): Promise<Socket>;+}+/**+ * Binding that provisions Hyperdrive connections at request time, rather than+ * from static configuration.+ */+interface HyperdriveDynamicApi {+ /**+ * Provision a connection for the database described by `args`.+ *+ */+ get(args: HyperdriveDynamicConfig): Promise<HyperdriveDynamic>;+ /**+ * Get a pre-generated connection string used for connecting to dynamic Hyperdrive.+ */+ getHyperdriveConnectionString(connectionString: string): Promise<string>;+}+/**+ * Parameters identifying the database that a dynamically-provisioned+ * Hyperdrive connection should target.+ */+interface HyperdriveDynamicConfig {+ /**+ * Generated connection string to pass into the dynamic worker.+ *+ */+ dynamicHyperdriveConnectionString: string;+ /**+ * Connection string for the origin database Hyperdrive should connect to.+ * Contains credentials, so treat it as a secret.+ *+ * The scheme selects the database engine. PostgreSQL origins are supported.+ */+ connectionString: string;+ /**+ * Region in which to place the connection pool. See the Hyperdrive+ * documentation for the set of supported regions.+ */+ targetRegion: string;+ /**+ * Whether Hyperdrive should cache query results for this connection.+ */+ cachingEnabled?: boolean;+ /**+ * Maximum number of connections the pool may open to the origin database.+ * Defaults to 60.+ */+ maxConnections?: number;+}+// Copyright (c) 2024 Cloudflare, Inc.+// Licensed under the Apache 2.0 license found in the LICENSE file or at:+// https://opensource.org/licenses/Apache-2.0+type ImageInfoResponse = {+ format: 'image/svg+xml';+} | {+ format: string;+ fileSize: number;+ width: number;+ height: number;+};+/**+ * Parameters for rasterizing text into an image.+ */+type TextRasterize = {+ /** The text content to render */+ content: string;+ /** rasterization options for the text **/+ options: TextOptions;+};+type TextOptions = {+ /** Font configuration */+ font: {+ /** URL to a font file in TrueType (.ttf), OpenType (.otf), WOFF (.woff), or WOFF2 (.woff2) format */+ url: string;+ };+ /** Font size in points (pt) */+ size?: number;+ /** Text color in CSS format: hex (#RRGGBB or #RRGGBBAA), rgb(r,g,b), rgba(r,g,b,a), or named colors */+ color?: string;+};+type ImageSource = ReadableStream<Uint8Array> | TextRasterize;+type ImageTransform = {+ width?: number;+ height?: number;+ background?: string;+ blur?: number;+ border?: {+ color?: string;+ width?: number;+ } | {+ top?: number;+ bottom?: number;+ left?: number;+ right?: number;+ };+ brightness?: number;+ contrast?: number;+ fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop';+ flip?: 'h' | 'v' | 'hv';+ gamma?: number;+ segment?: 'foreground';+ gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | {+ x?: number;+ y?: number;+ mode: 'remainder' | 'box-center';+ };+ rotate?: 0 | 90 | 180 | 270;+ saturation?: number;+ sharpen?: number;+ trim?: 'border' | {+ top?: number;+ bottom?: number;+ left?: number;+ right?: number;+ width?: number;+ height?: number;+ border?: boolean | {+ color?: string;+ tolerance?: number;+ keep?: number;+ };+ };+};+type ImageDrawOptions = {+ opacity?: number;+ repeat?: boolean | string;+ composite?: ImageCompositeMode;+ top?: number;+ left?: number;+ bottom?: number;+ right?: number;+};+type ImageCompositeMode =+/** Foreground drawn on top of backdrop (default) */+'over'+/** Foreground shown only where backdrop is opaque */+ | 'in'+/** Foreground drawn on top, but clipped to the backdrop's shape */+ | 'atop'+/** Foreground shown only where backdrop is transparent */+ | 'out'+/** Foreground and backdrop visible only where the other is not */+ | 'xor'+/** Foreground and backdrop channels added (brightening) */+ | 'lighter';+type ImageInputOptions = {+ encoding?: 'base64';+};+type ImageOutputOptions = {+ format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba';+ quality?: number;+ background?: string;+ anim?: boolean;+};+interface ImageMetadata {+ id: string;+ filename?: string;+ uploaded?: string;+ requireSignedURLs: boolean;+ meta?: Record<string, unknown>;+ variants: string[];+ draft?: boolean;+ creator?: string;+}+interface ImageUploadOptions {+ id?: string;+ filename?: string;+ requireSignedURLs?: boolean;+ metadata?: Record<string, unknown>;+ creator?: string;+ /**+ * If 'base64', the input data will be decoded from base64 before processing+ */+ encoding?: 'base64';+}+interface ImageUpdateOptions {+ requireSignedURLs?: boolean;+ metadata?: Record<string, unknown>;+ creator?: string;+}+type ImageMetadataFilterOperators = {+ eq?: string | number | boolean;+ in?: string[] | number[];+ gt?: number;+ gte?: number;+ lt?: number;+ lte?: number;+};+type ImageMetadataFilterValue = string | number | boolean | ImageMetadataFilterOperators;+interface ImageListFilter {+ metadata?: Record<string, ImageMetadataFilterValue>;+}+interface ImageListOptions {+ limit?: number;+ cursor?: string;+ sortOrder?: 'asc' | 'desc';+ creator?: string;+ filter?: ImageListFilter;+}+interface ImageSignedUrlOptions {+ variant: string;+ expiresIn?: number;+ keyName?: string;+}+interface ImageDirectUploadOptions {+ id?: string;+ requireSignedURLs?: boolean;+ metadata?: Record<string, unknown>;+ creator?: string;+ expiresIn?: number;+}+interface ImageDirectUploadResult {+ id: string;+ uploadURL: string;+}+interface ImageList {+ images: ImageMetadata[];+ cursor?: string;+ listComplete: boolean;+}+interface ImageHandle {+ /**+ * Get metadata for a hosted image+ * @returns Image metadata, or null if not found+ */+ details(): Promise<ImageMetadata | null>;+ /**+ * Get the raw image data for a hosted image+ * @returns ReadableStream of image bytes, or null if not found+ */+ bytes(): Promise<ReadableStream<Uint8Array> | null>;+ /**+ * Generate a signed delivery URL for this hosted image.+ * @param options Signing configuration+ * @returns A signed image delivery URL+ * @throws {@link ImagesError} if signing fails+ */+ signedUrl(options: ImageSignedUrlOptions): Promise<string>;+ /**+ * Update hosted image metadata+ * @param options Properties to update+ * @returns Updated image metadata+ * @throws {@link ImagesError} if update fails+ */+ update(options: ImageUpdateOptions): Promise<ImageMetadata>;+ /**+ * Delete a hosted image+ * @returns True if deleted, false if not found+ */+ delete(): Promise<boolean>;+}+interface HostedImagesBinding {+ /**+ * Get a handle for a hosted image+ * @param imageId The ID of the image (UUID or custom ID)+ * @returns A handle for per-image operations+ */+ image(imageId: string): ImageHandle;+ /**+ * Upload a new hosted image+ * @param image The image file to upload+ * @param options Upload configuration+ * @returns Metadata for the uploaded image+ * @throws {@link ImagesError} if upload fails+ */+ upload(image: ReadableStream<Uint8Array> | ArrayBuffer, options?: ImageUploadOptions): Promise<ImageMetadata>;+ /**+ * List hosted images with pagination+ * @param options List configuration+ * @returns List of images with pagination info+ * @throws {@link ImagesError} if list fails+ */+ list(options?: ImageListOptions): Promise<ImageList>;+ /**+ * Create a Direct Creator Upload link, letting an end user upload an+ * image straight to Cloudflare without exposing an API token+ * @param options Upload link configuration+ * @returns The new image ID and the upload URL to hand to the end user+ * @throws {@link ImagesError} if creation fails+ */+ createDirectUpload(options?: ImageDirectUploadOptions): Promise<ImageDirectUploadResult>;+}+interface ImagesBinding {+ /**+ * Get image metadata (type, width and height)+ * @throws {@link ImagesError} with code 9412 if input is not an image+ * @param stream The image bytes+ */+ info(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): Promise<ImageInfoResponse>;+ /**+ * Begin applying a series of transformations to an image+ * @param stream The image bytes+ * @returns A transform handle+ */+ input(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): ImageTransformer;+ /**+ * Begin applying a series of transformations to text+ * @param content string to be rendered+ * @param options font, optional color and size to use in rendering text+ * @returns A transform handle+ */+ text(content: string, options: TextOptions): ImageTransformer;+ /**+ * Access hosted images CRUD operations+ */+ readonly hosted: HostedImagesBinding;+}+interface ImageTransformer {+ /**+ * Apply transform next, returning a transform handle.+ * You can then apply more transformations, draw, or retrieve the output.+ * @param transform+ */+ transform(transform: ImageTransform): ImageTransformer;+ /**+ * Draw an image on this transformer, returning a transform handle.+ * You can then apply more transformations, draw, or retrieve the output.+ * @param image The image (or transformer that will give the image) to draw+ * @param options The options configuring how to draw the image+ */+ draw(image: ReadableStream<Uint8Array> | ImageTransformer, options?: ImageDrawOptions): ImageTransformer;+ /**+ * Retrieve the image that results from applying the transforms to the+ * provided input+ * @param options Options that apply to the output e.g. output format+ */+ output(options: ImageOutputOptions): Promise<ImageTransformationResult>;+}+type ImageTransformationOutputOptions = {+ encoding?: 'base64';+};+type ImageTransformationResponseOptions = {+ headers?: HeadersInit;+};+interface ImageTransformationResult {+ /**+ * The image as a response, ready to store in cache or return to users+ * @param options Options that apply to the returned response, e.g. additional headers+ */+ response(options?: ImageTransformationResponseOptions): Response;+ /**+ * The content type of the returned image+ */+ contentType(): string;+ /**+ * The bytes of the response+ */+ image(options?: ImageTransformationOutputOptions): ReadableStream<Uint8Array>;+}+interface ImagesError extends Error {+ readonly code: number;+ readonly message: string;+ readonly stack?: string;+}+/**+ * Media binding for transforming media streams.+ * Provides the entry point for media transformation operations.+ */+interface MediaBinding {+ /**+ * Creates a media transformer from an input stream.+ * @param media - The input media bytes+ * @returns A MediaTransformer instance for applying transformations+ */+ input(media: ReadableStream<Uint8Array>): MediaTransformer;+}+/**+ * Media transformer for applying transformation operations to media content.+ * Handles sizing, fitting, and other input transformation parameters.+ */+interface MediaTransformer {+ /**+ * Applies transformation options to the media content.+ * @param transform - Configuration for how the media should be transformed+ * @returns A generator for producing the transformed media output+ */+ transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator;+ /**+ * Generates the final media output with specified options.+ * @param output - Configuration for the output format and parameters+ * @returns The final transformation result containing the transformed media+ */+ output(output?: MediaTransformationOutputOptions): MediaTransformationResult;+}+/**+ * Generator for producing media transformation results.+ * Configures the output format and parameters for the transformed media.+ */+interface MediaTransformationGenerator {+ /**+ * Generates the final media output with specified options.+ * @param output - Configuration for the output format and parameters+ * @returns The final transformation result containing the transformed media+ */+ output(output?: MediaTransformationOutputOptions): MediaTransformationResult;+}+/**+ * Result of a media transformation operation.+ * Provides multiple ways to access the transformed media content.+ */+interface MediaTransformationResult {+ /**+ * Returns the transformed media as a readable stream of bytes.+ * @returns A promise containing a readable stream with the transformed media+ */+ media(): Promise<ReadableStream<Uint8Array>>;+ /**+ * Returns the transformed media as an HTTP response object.+ * @returns The transformed media as a Promise<Response>, ready to store in cache or return to users+ */+ response(): Promise<Response>;+ /**+ * Returns the MIME type of the transformed media.+ * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4')+ */+ contentType(): Promise<string>;+}+/**+ * Configuration options for transforming media input.+ * Controls how the media should be resized and fitted.+ */+type MediaTransformationInputOptions = {+ /** How the media should be resized to fit the specified dimensions */+ fit?: 'contain' | 'cover' | 'scale-down';+ /** Target width in pixels */+ width?: number;+ /** Target height in pixels */+ height?: number;+};+/**+ * Configuration options for Media Transformations output.+ * Controls the format, timing, and type of the generated output.+ */+type MediaTransformationOutputOptions = {+ /**+ * Output mode determining the type of media to generate+ */+ mode?: 'video' | 'spritesheet' | 'frame' | 'audio';+ /** Whether to include audio in the output */+ audio?: boolean;+ /**+ * Starting timestamp for frame extraction or start time for clips. (e.g. '2s').+ */+ time?: string;+ /**+ * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s').+ */+ duration?: string;+ /**+ * Number of frames in the spritesheet.+ */+ imageCount?: number;+ /**+ * Output format for the generated media.+ */+ format?: 'jpg' | 'png' | 'm4a';+};+/**+ * Error object for media transformation operations.+ * Extends the standard Error interface with additional media-specific information.+ */+interface MediaError extends Error {+ readonly code: number;+ readonly message: string;+ readonly stack?: string;+}+declare module 'cloudflare:node' {+ interface NodeStyleServer {+ listen(...args: unknown[]): this;+ address(): {+ port?: number | null | undefined;+ };+ }+ export function httpServerHandler(port: number): ExportedHandler;+ export function httpServerHandler(options: {+ port: number;+ }): ExportedHandler;+ export function httpServerHandler(server: NodeStyleServer): ExportedHandler;+}+type Params<P extends string = any> = Record<P, string | string[]>;+type EventContext<Env, P extends string, Data> = {+ request: Request<unknown, IncomingRequestCfProperties<unknown>>;+ functionPath: string;+ waitUntil: (promise: Promise<any>) => void;+ passThroughOnException: () => void;+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;+ env: Env & {+ ASSETS: {+ fetch: typeof fetch;+ };+ };+ params: Params<P>;+ data: Data;+};+type PagesFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>;+type EventPluginContext<Env, P extends string, Data, PluginArgs> = {+ request: Request<unknown, IncomingRequestCfProperties<unknown>>;+ functionPath: string;+ waitUntil: (promise: Promise<any>) => void;+ passThroughOnException: () => void;+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;+ env: Env & {+ ASSETS: {+ fetch: typeof fetch;+ };+ };+ params: Params<P>;+ data: Data;+ pluginArgs: PluginArgs;+};+type PagesPluginFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>, PluginArgs = unknown> = (context: EventPluginContext<Env, Params, Data, PluginArgs>) => Response | Promise<Response>;+declare module "assets:*" {+ export const onRequest: PagesFunction;+}+// Copyright (c) 2022-2023 Cloudflare, Inc.+// Licensed under the Apache 2.0 license found in the LICENSE file or at:+// https://opensource.org/licenses/Apache-2.0+declare module "cloudflare:pipelines" {+ export abstract class PipelineTransformationEntrypoint<Env = unknown, I extends PipelineRecord = PipelineRecord, O extends PipelineRecord = PipelineRecord> {+ protected env: Env;+ protected ctx: ExecutionContext;+ constructor(ctx: ExecutionContext, env: Env);+ /**+ * run receives an array of PipelineRecord which can be+ * transformed and returned to the pipeline+ * @param records Incoming records from the pipeline to be transformed+ * @param metadata Information about the specific pipeline calling the transformation entrypoint+ * @returns A promise containing the transformed PipelineRecord array+ */+ public run(records: I[], metadata: PipelineBatchMetadata): Promise<O[]>;+ }+ export type PipelineRecord = Record<string, unknown>;+ export type PipelineBatchMetadata = {+ pipelineId: string;+ pipelineName: string;+ };+ export interface Pipeline<T extends PipelineRecord = PipelineRecord> {+ /**+ * The Pipeline interface represents the type of a binding to a Pipeline+ *+ * @param records The records to send to the pipeline+ */+ send(records: T[]): Promise<void>;+ }+}+// PubSubMessage represents an incoming PubSub message.+// The message includes metadata about the broker, the client, and the payload+// itself.+// https://developers.cloudflare.com/pub-sub/+interface PubSubMessage {+ // Message ID+ readonly mid: number;+ // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT+ readonly broker: string;+ // The MQTT topic the message was sent on.+ readonly topic: string;+ // The client ID of the client that published this message.+ readonly clientId: string;+ // The unique identifier (JWT ID) used by the client to authenticate, if token+ // auth was used.+ readonly jti?: string;+ // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker+ // received the message from the client.+ readonly receivedAt: number;+ // An (optional) string with the MIME type of the payload, if set by the+ // client.+ readonly contentType: string;+ // Set to 1 when the payload is a UTF-8 string+ // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063+ readonly payloadFormatIndicator: number;+ // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays.+ // You can use payloadFormatIndicator to inspect this before decoding.+ payload: string | Uint8Array;+}+// JsonWebKey extended by kid parameter+interface JsonWebKeyWithKid extends JsonWebKey {+ // Key Identifier of the JWK+ readonly kid: string;+}+interface RateLimitOptions {+ key: string;+}+interface RateLimitOutcome {+ success: boolean;+}+interface RateLimit {+ /**+ * Rate limit a request based on the provided options.+ * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/+ * @returns A promise that resolves with the outcome of the rate limit.+ */+ limit(options: RateLimitOptions): Promise<RateLimitOutcome>;+}+// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need+// to referenced by `Fetcher`. This is included in the "importable" version of the types which+// strips all `module` blocks.+declare namespace Rpc {+ // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.+ // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.+ // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to+ // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)+ export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';+ export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';+ export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND';+ export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND';+ export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND';+ export interface RpcTargetBranded {+ [__RPC_TARGET_BRAND]: never;+ }+ export interface WorkerEntrypointBranded {+ [__WORKER_ENTRYPOINT_BRAND]: never;+ }+ export interface DurableObjectBranded {+ [__DURABLE_OBJECT_BRAND]: never;+ }+ export interface WorkflowEntrypointBranded {+ [__WORKFLOW_ENTRYPOINT_BRAND]: never;+ }+ export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded;+ // Types that can be used through `Stub`s+ export type Stubable = RpcTargetBranded | ((...args: any[]) => any);+ // Types that can be passed over RPC+ // The reason for using a generic type here is to build a serializable subset of structured+ // cloneable composite types. This allows types defined with the "interface" keyword to pass the+ // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.+ type Serializable<T> =+ // Structured cloneables+ BaseType+ // Structured cloneable composites+ | Map<T extends Map<infer U, unknown> ? Serializable<U> : never, T extends Map<unknown, infer U> ? Serializable<U> : never> | Set<T extends Set<infer U> ? Serializable<U> : never> | ReadonlyArray<T extends ReadonlyArray<infer U> ? Serializable<U> : never> | {+ [K in keyof T]: K extends number | string ? Serializable<T[K]> : never;+ }+ // Special types+ | Stub<Stubable>+ // Serialized as stubs, see `Stubify`+ | Stubable;+ // Base type for all RPC stubs, including common memory management methods.+ // `T` is used as a marker type for unwrapping `Stub`s later.+ interface StubBase<T extends Stubable> extends Disposable {+ [__RPC_STUB_BRAND]: T;+ dup(): this;+ }+ export type Stub<T extends Stubable> = Provider<T> & StubBase<T>;+ // This represents all the types that can be sent as-is over an RPC boundary+ type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream<Uint8Array> | WritableStream<Uint8Array> | Request | Response | Headers;+ // Recursively rewrite all `Stubable` types with `Stub`s+ // prettier-ignore+ type Stubify<T> = T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T : T extends {+ [key: string | number]: any;+ } ? {+ [K in keyof T]: Stubify<T[K]>;+ } : T;+ // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.+ // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:+ // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.+ // prettier-ignore+ type Unstubify<T> = T extends StubBase<infer V> ? V : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>> : T extends Set<infer V> ? Set<Unstubify<V>> : T extends Array<infer V> ? Array<Unstubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>> : T extends BaseType ? T : T extends {+ [key: string | number]: unknown;+ } ? {+ [K in keyof T]: Unstubify<T[K]>;+ } : T;+ type UnstubifyAll<A extends any[]> = {+ [I in keyof A]: Unstubify<A[I]>;+ };+ // Utility type for adding `Provider`/`Disposable`s to `object` types only.+ // Note `unknown & T` is equivalent to `T`.+ type MaybeProvider<T> = T extends object ? Provider<T> : unknown;+ type MaybeDisposable<T> = T extends object ? Disposable : unknown;+ // Type for method return or property on an RPC interface.+ // - Stubable types are replaced by stubs.+ // - Serializable types are passed by value, with stubable types replaced by stubs+ // and a top-level `Disposer`.+ // Everything else can't be passed over PRC.+ // Technically, we use custom thenables here, but they quack like `Promise`s.+ // Intersecting with `(Maybe)Provider` allows pipelining.+ // prettier-ignore+ type Result<R> = R extends Stubable ? Promise<Stub<R>> & Provider<R> : R extends Serializable<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & MaybeProvider<R> : never;+ // Type for method or property on an RPC interface.+ // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.+ // Unwrapping `Stub`s allows calling with `Stubable` arguments.+ // For properties, rewrite types to be `Result`s.+ // In each case, unwrap `Promise`s.+ type MethodOrProperty<V> = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;+ // Type for the callable part of an `Provider` if `T` is callable.+ // This is intersected with methods/properties.+ type MaybeCallableProvider<T> = T extends (...args: any[]) => any ? MethodOrProperty<T> : unknown;+ // Base type for all other types providing RPC-like interfaces.+ // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.+ // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC.+ export type Provider<T extends object, Reserved extends string = never> = MaybeCallableProvider<T> & Pick<{+ [K in keyof T]: MethodOrProperty<T[K]>;+ }, Exclude<keyof T, Reserved | symbol | keyof StubBase<never>>>;+}+declare namespace Cloudflare {+ // Type of `env`.+ //+ // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript+ // will merge all declarations.+ //+ // You can use `wrangler types` to generate the `Env` type automatically.+ interface Env {+ }+ // Project-specific parameters used to inform types.+ //+ // This interface is, again, intended to be declared in project-specific files, and then that+ // declaration will be merged with this one.+ //+ // A project should have a declaration like this:+ //+ // interface GlobalProps {+ // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type+ // // of `ctx.exports`.+ // mainModule: typeof import("my-main-module");+ //+ // // Declares which of the main module's exports are configured with durable storage, and+ // // thus should behave as Durable Object namsepace bindings.+ // durableNamespaces: "MyDurableObject" | "AnotherDurableObject";+ // }+ //+ // You can use `wrangler types` to generate `GlobalProps` automatically.+ interface GlobalProps {+ }+ // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not+ // present.+ type GlobalProp<K extends string, Default> = K extends keyof GlobalProps ? GlobalProps[K] : Default;+ // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the+ // `mainModule` property.+ type MainModule = GlobalProp<"mainModule", {}>;+ // The type of ctx.exports, which contains loopback bindings for all top-level exports.+ type Exports = {+ [K in keyof MainModule]: LoopbackForExport<MainModule[K]>+ // If the export is listed in `durableNamespaces`, then it is also a+ // DurableObjectNamespace.+ & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace<DoInstance> : DurableObjectNamespace<undefined> : DurableObjectNamespace<undefined> : {});+ };+}+declare namespace CloudflareWorkersModule {+ export type RpcStub<T extends Rpc.Stubable> = Rpc.Stub<T>;+ export const RpcStub: {+ new <T extends Rpc.Stubable>(value: T): Rpc.Stub<T>;+ };+ export abstract class RpcTarget implements Rpc.RpcTargetBranded {+ [Rpc.__RPC_TARGET_BRAND]: never;+ }+ // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC+ export abstract class WorkerEntrypoint<Env = Cloudflare.Env, Props = {}> implements Rpc.WorkerEntrypointBranded {+ [Rpc.__WORKER_ENTRYPOINT_BRAND]: never;+ protected ctx: ExecutionContext<Props>;+ protected env: Env;+ constructor(ctx: ExecutionContext, env: Env);+ email?(message: ForwardableEmailMessage): void | Promise<void>;+ fetch?(request: Request): Response | Promise<Response>;+ connect?(socket: Socket): void | Promise<void>;+ queue?(batch: MessageBatch): void | Promise<void>;+ scheduled?(controller: ScheduledController): void | Promise<void>;+ tail?(events: TraceItem[]): void | Promise<void>;+ tailStream?(event: TailStream.TailEvent<TailStream.Onset>): TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;+ test?(controller: TestController): void | Promise<void>;+ trace?(traces: TraceItem[]): void | Promise<void>;+ }+ export abstract class DurableObject<Env = Cloudflare.Env, Props = {}> implements Rpc.DurableObjectBranded {+ [Rpc.__DURABLE_OBJECT_BRAND]: never;+ protected ctx: DurableObjectState<Props>;+ protected env: Env;+ constructor(ctx: DurableObjectState, env: Env);+ alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;+ fetch?(request: Request): Response | Promise<Response>;+ connect?(socket: Socket): void | Promise<void>;+ webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;+ webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;+ webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;+ }+ export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';+ export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;+ export type WorkflowDelayDuration = WorkflowSleepDuration;+ export type WorkflowDynamicDelayContext = {+ ctx: WorkflowStepContext<WorkflowDelayFunction>;+ error: Error;+ };+ export type WorkflowDelayFunction = (input: WorkflowDynamicDelayContext) => WorkflowDelayDuration | Promise<WorkflowDelayDuration>;+ export type WorkflowTimeoutDuration = WorkflowSleepDuration;+ export type WorkflowRetentionDuration = WorkflowSleepDuration;+ export type WorkflowBackoff = 'constant' | 'linear' | 'exponential';+ export type WorkflowStepSensitivity = 'output';+ export type WorkflowStepConfig = {+ retries?: {+ limit: number;+ delay: WorkflowDelayDuration | number | WorkflowDelayFunction;+ backoff?: WorkflowBackoff;+ };+ timeout?: WorkflowTimeoutDuration | number;+ sensitive?: WorkflowStepSensitivity;+ };+ // Internal discriminators used only for `WorkflowStep.do` overload+ // resolution. They mirror `WorkflowStepConfig` but pin `retries.delay` to a+ // single kind so the callback context can be narrowed based on the shape of+ // the config argument (rather than on an inferred type parameter, which is+ // lost when the caller supplies an explicit return-type argument). Not+ // exported: they must not widen the public type surface.+ type WorkflowStepConfigWithStaticDelay = Omit<WorkflowStepConfig, 'retries'> & {+ retries?: {+ limit: number;+ delay: WorkflowDelayDuration | number;+ backoff?: WorkflowBackoff;+ };+ };+ type WorkflowStepConfigWithDelayFunction = Omit<WorkflowStepConfig, 'retries'> & {+ retries: {+ limit: number;+ delay: WorkflowDelayFunction;+ backoff?: WorkflowBackoff;+ };+ };+ export type WorkflowStepRollbackConfig = Pick<WorkflowStepConfig, 'retries' | 'timeout'>;+ export type WorkflowCronSchedule = {+ /** Cron expression that triggered this event. */+ cron: string;+ /** Timestamp of the scheduled trigger, in milliseconds since the Unix epoch. */+ scheduledTime: number;+ };+ export type WorkflowEvent<T> = {+ payload: Readonly<T>;+ timestamp: Date;+ instanceId: string;+ workflowName: string;+ schedule?: WorkflowCronSchedule;+ };+ export type WorkflowStepEvent<T> = {+ payload: Readonly<T>;+ timestamp: Date;+ type: string;+ sensitive?: WorkflowStepSensitivity;+ };+ export type WorkflowStepContext<Delay = WorkflowDelayDuration | number> = {+ step: {+ name: string;+ count: number;+ };+ attempt: number;+ config: {+ retries?: {+ limit: number;+ backoff?: WorkflowBackoff;+ } & (Delay extends WorkflowDelayFunction ? {} : {+ delay: WorkflowDelayDuration | number;+ });+ timeout?: WorkflowTimeoutDuration | number;+ sensitive?: WorkflowStepSensitivity;+ };+ };+ // The rollback handler receives the step context, so it mirrors the same+ // delay discriminant as the step callback: when the step was configured with+ // a dynamic delay function the resolved `config.retries.delay` is omitted,+ // otherwise it is present. `Delay` is threaded from the `WorkflowStep.do`+ // overload that matched the step config.+ export type WorkflowRollbackContext<T = unknown, Delay = WorkflowDelayDuration | number> = {+ ctx: WorkflowStepContext<Delay>;+ error: Error;+ output: T | undefined;+ /** @deprecated Use `ctx.step.name` and `ctx.step.count` instead. */+ stepName: string;+ };+ export type WorkflowRollbackHandler<T = unknown, Delay = WorkflowDelayDuration | number> = (ctx: WorkflowRollbackContext<T, Delay>) => Promise<void>;+ export type WorkflowStepRollbackOptions<T = unknown, Delay = WorkflowDelayDuration | number> = {+ rollback: WorkflowRollbackHandler<T, Delay>;+ rollbackConfig?: WorkflowStepRollbackConfig;+ };+ export abstract class WorkflowStep {+ do<T extends Rpc.Serializable<T>>(name: string, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;+ // The config overloads discriminate on the shape of `config.retries.delay`+ // so the callback context reflects whether the resolved delay is present+ // (static delay) or omitted (dynamic delay function). Each has a single+ // type parameter, so an explicit return-type argument (`do<T>(...)`) still+ // resolves here. ORDERING IS LOAD-BEARING: the broad `WorkflowStepConfig`+ // fallback MUST remain last, otherwise it shadows the discriminating+ // overloads and narrowing is silently lost.+ do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithDelayFunction, callback: (ctx: WorkflowStepContext<WorkflowDelayFunction>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayFunction>): Promise<T>;+ do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithStaticDelay, callback: (ctx: WorkflowStepContext<WorkflowDelayDuration | number>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayDuration | number>): Promise<T>;+ do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;+ sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;+ sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;+ waitForEvent<T extends Rpc.Serializable<T>>(name: string, options: {+ type: string;+ timeout?: WorkflowTimeoutDuration | number;+ }): Promise<WorkflowStepEvent<T>>;+ }+ export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown';+ export abstract class WorkflowEntrypoint<Env = unknown, T extends Rpc.Serializable<T> | unknown = unknown> implements Rpc.WorkflowEntrypointBranded {+ [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never;+ protected ctx: ExecutionContext;+ protected env: Env;+ constructor(ctx: ExecutionContext, env: Env);+ run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown>;+ }+ export function waitUntil(promise: Promise<unknown>): void;+ export function withEnv(newEnv: unknown, fn: () => unknown): unknown;+ export function withExports(newExports: unknown, fn: () => unknown): unknown;+ export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown;+ export const env: Cloudflare.Env;+ export const exports: Cloudflare.Exports;+ export const cache: CacheContext;+ export const tracing: Tracing;+}+declare module 'cloudflare:workers' {+ export = CloudflareWorkersModule;+}+interface SecretsStoreSecret {+ /**+ * Get a secret from the Secrets Store, returning a string of the secret value+ * if it exists, or throws an error if it does not exist+ */+ get(): Promise<string>;+}+declare module "cloudflare:sockets" {+ function _connect(address: string | SocketAddress, options?: SocketOptions): Socket;+ export { _connect as connect };+}+/**+ * Binding entrypoint for Cloudflare Stream.+ *+ * Usage:+ * - Binding-level operations:+ * `await env.STREAM.videos.upload`+ * `await env.STREAM.videos.createDirectUpload`+ * `await env.STREAM.videos.*`+ * `await env.STREAM.watermarks.*`+ * - Per-video operations:+ * `await env.STREAM.video(id).downloads.*`+ * `await env.STREAM.video(id).captions.*`+ *+ * Example usage:+ * ```ts+ * await env.STREAM.video(id).downloads.generate();+ *+ * const video = env.STREAM.video(id)+ * const captions = video.captions.list();+ * const videoDetails = video.details()+ * ```+ */+interface StreamBinding {+ /**+ * Returns a handle scoped to a single video for per-video operations.+ * @param id The unique identifier for the video.+ * @returns A handle for per-video operations.+ */+ video(id: string): StreamVideoHandle;+ /**+ * Uploads a new video from a provided URL.+ * @param url The URL to upload from.+ * @param params Optional upload parameters.+ * @returns The uploaded video details.+ * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid+ * @throws {QuotaReachedError} if the account storage capacity is exceeded+ * @throws {MaxFileSizeError} if the file size is too large+ * @throws {RateLimitedError} if the server received too many requests+ * @throws {AlreadyUploadedError} if a video was already uploaded to this URL+ * @throws {InternalError} if an unexpected error occurs+ */+ upload(url: string, params?: StreamUrlUploadParams): Promise<StreamVideo>;+ /**+ * Creates a direct upload that allows video uploads without an API key.+ * @param params Parameters for the direct upload+ * @returns The direct upload details.+ * @throws {BadRequestError} if the parameters are invalid+ * @throws {RateLimitedError} if the server received too many requests+ * @throws {InternalError} if an unexpected error occurs+ */+ createDirectUpload(params: StreamDirectUploadCreateParams): Promise<StreamDirectUpload>;+ videos: StreamVideos;+ watermarks: StreamWatermarks;+}+/**+ * Handle for operations scoped to a single Stream video.+ */+interface StreamVideoHandle {+ /**+ * The unique identifier for the video.+ */+ id: string;+ /**+ * Get a full videos details+ * @returns The full video details.+ * @throws {NotFoundError} if the video is not found+ * @throws {InternalError} if an unexpected error occurs+ */+ details(): Promise<StreamVideo>;+ /**+ * Update details for a single video.+ * @param params The fields to update for the video.+ * @returns The updated video details.+ * @throws {NotFoundError} if the video is not found+ * @throws {BadRequestError} if the parameters are invalid+ * @throws {InternalError} if an unexpected error occurs+ */+ update(params: StreamUpdateVideoParams): Promise<StreamVideo>;+ /**+ * Deletes a video and its copies from Cloudflare Stream.+ * @returns A promise that resolves when deletion completes.+ * @throws {NotFoundError} if the video is not found+ * @throws {InternalError} if an unexpected error occurs+ */+ delete(): Promise<void>;+ /**+ * Creates a signed URL token for a video.+ * @returns The signed token that was created.+ * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed+ */+ generateToken(): Promise<string>;+ downloads: StreamScopedDownloads;+ captions: StreamScopedCaptions;+}+interface StreamVideo {+ /**+ * The unique identifier for the video.+ */+ id: string;+ /**+ * A user-defined identifier for the media creator.+ */+ creator: string | null;+ /**+ * The thumbnail URL for the video.+ */+ thumbnail: string;+ /**+ * The thumbnail timestamp percentage.+ */+ thumbnailTimestampPct: number;+ /**+ * Indicates whether the video is ready to stream.+ */+ readyToStream: boolean;+ /**+ * The date and time the video became ready to stream.+ */+ readyToStreamAt: string | null;+ /**+ * Processing status information.+ */+ status: StreamVideoStatus;+ /**+ * A user modifiable key-value store.+ */+ meta: Record<string, string>;+ /**+ * The date and time the video was created.+ */+ created: string;+ /**+ * The date and time the video was last modified.+ */+ modified: string;+ /**+ * The date and time at which the video will be deleted.+ */+ scheduledDeletion: string | null;+ /**+ * The size of the video in bytes.+ */+ size: number;+ /**+ * The preview URL for the video.+ */+ preview?: string;+ /**+ * Origins allowed to display the video.+ */+ allowedOrigins: Array<string>;+ /**+ * Indicates whether signed URLs are required.+ */+ requireSignedURLs: boolean | null;+ /**+ * The date and time the video was uploaded.+ */+ uploaded: string | null;+ /**+ * The date and time when the upload URL expires.+ */+ uploadExpiry: string | null;+ /**+ * The maximum size in bytes for direct uploads.+ */+ maxSizeBytes: number | null;+ /**+ * The maximum duration in seconds for direct uploads.+ */+ maxDurationSeconds: number | null;+ /**+ * The video duration in seconds. -1 indicates unknown.+ */+ duration: number;+ /**+ * Input metadata for the original upload.+ */+ input: StreamVideoInput;+ /**+ * Playback URLs for the video.+ */+ hlsPlaybackUrl: string;+ dashPlaybackUrl: string;+ /**+ * The watermark applied to the video, if any.+ */+ watermark: StreamWatermark | null;+ /**+ * The live input id associated with the video, if any.+ */+ liveInputId?: string | null;+ /**+ * The source video id if this is a clip.+ */+ clippedFromId: string | null;+ /**+ * Public details associated with the video.+ */+ publicDetails: StreamPublicDetails | null;+}+type StreamVideoStatus = {+ /**+ * The current processing state.+ */+ state: string;+ /**+ * The current processing step.+ */+ step?: string;+ /**+ * The percent complete as a string.+ */+ pctComplete?: string;+ /**+ * An error reason code, if applicable.+ */+ errorReasonCode: string;+ /**+ * An error reason text, if applicable.+ */+ errorReasonText: string;+};+type StreamVideoInput = {+ /**+ * The input width in pixels.+ */+ width: number;+ /**+ * The input height in pixels.+ */+ height: number;+};+type StreamPublicDetails = {+ /**+ * The public title for the video.+ */+ title: string | null;+ /**+ * The public share link.+ */+ share_link: string | null;+ /**+ * The public channel link.+ */+ channel_link: string | null;+ /**+ * The public logo URL.+ */+ logo: string | null;+};+type StreamDirectUpload = {+ /**+ * The URL an unauthenticated upload can use for a single multipart request.+ */+ uploadURL: string;+ /**+ * A Cloudflare-generated unique identifier for a media item.+ */+ id: string;+ /**+ * The watermark profile applied to the upload.+ */+ watermark: StreamWatermark | null;+ /**+ * The scheduled deletion time, if any.+ */+ scheduledDeletion: string | null;+};+type StreamDirectUploadCreateParams = {+ /**+ * The maximum duration in seconds for a video upload.+ */+ maxDurationSeconds: number;+ /**+ * The date and time after upload when videos will not be accepted.+ */+ expiry?: string;+ /**+ * A user-defined identifier for the media creator.+ */+ creator?: string;+ /**+ * A user modifiable key-value store used to reference other systems of record for+ * managing videos.+ */+ meta?: Record<string, string>;+ /**+ * Lists the origins allowed to display the video.+ */+ allowedOrigins?: Array<string>;+ /**+ * Indicates whether the video can be accessed using the id. When set to `true`,+ * a signed token must be generated with a signing key to view the video.+ */+ requireSignedURLs?: boolean;+ /**+ * The thumbnail timestamp percentage.+ */+ thumbnailTimestampPct?: number;+ /**+ * The date and time at which the video will be deleted. Include `null` to remove+ * a scheduled deletion.+ */+ scheduledDeletion?: string | null;+ /**+ * The watermark profile to apply.+ */+ watermark?: StreamDirectUploadWatermark;+};+type StreamDirectUploadWatermark = {+ /**+ * The unique identifier for the watermark profile.+ */+ id: string;+};+type StreamUrlUploadParams = {+ /**+ * Lists the origins allowed to display the video. Enter allowed origin+ * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the+ * video to be viewed on any origin.+ */+ allowedOrigins?: Array<string>;+ /**+ * A user-defined identifier for the media creator.+ */+ creator?: string;+ /**+ * A user modifiable key-value store used to reference other systems of+ * record for managing videos.+ */+ meta?: Record<string, string>;+ /**+ * Indicates whether the video can be a accessed using the id. When+ * set to `true`, a signed token must be generated with a signing key to view the+ * video.+ */+ requireSignedURLs?: boolean;+ /**+ * Indicates the date and time at which the video will be deleted. Omit+ * the field to indicate no change, or include with a `null` value to remove an+ * existing scheduled deletion. If specified, must be at least 30 days from upload+ * time.+ */+ scheduledDeletion?: string | null;+ /**+ * The timestamp for a thumbnail image calculated as a percentage value+ * of the video's duration. To convert from a second-wise timestamp to a+ * percentage, divide the desired timestamp by the total duration of the video. If+ * this value is not set, the default thumbnail image is taken from 0s of the+ * video.+ */+ thumbnailTimestampPct?: number;+ /**+ * The identifier for the watermark profile+ */+ watermarkId?: string;+};+interface StreamScopedCaptions {+ /**+ * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language.+ * One caption or subtitle file per language is allowed.+ * @param language The BCP 47 language tag for the caption or subtitle.+ * @param input The caption or subtitle stream to upload.+ * @returns The created caption entry.+ * @throws {NotFoundError} if the video is not found+ * @throws {BadRequestError} if the language or file is invalid+ * @throws {InternalError} if an unexpected error occurs+ */+ upload(language: string, input: ReadableStream): Promise<StreamCaption>;+ /**+ * Generate captions or subtitles for the provided language via AI.+ * @param language The BCP 47 language tag to generate.+ * @returns The generated caption entry.+ * @throws {NotFoundError} if the video is not found+ * @throws {BadRequestError} if the language is invalid+ * @throws {StreamError} if a generated caption already exists+ * @throws {StreamError} if the video duration is too long+ * @throws {StreamError} if the video is missing audio+ * @throws {StreamError} if the requested language is not supported+ * @throws {InternalError} if an unexpected error occurs+ */+ generate(language: string): Promise<StreamCaption>;+ /**+ * Lists the captions or subtitles.+ * Use the language parameter to filter by a specific language.+ * @param language The optional BCP 47 language tag to filter by.+ * @returns The list of captions or subtitles.+ * @throws {NotFoundError} if the video or caption is not found+ * @throws {InternalError} if an unexpected error occurs+ */+ list(language?: string): Promise<StreamCaption[]>;+ /**+ * Removes the captions or subtitles from a video.+ * @param language The BCP 47 language tag to remove.+ * @returns A promise that resolves when deletion completes.+ * @throws {NotFoundError} if the video or caption is not found+ * @throws {InternalError} if an unexpected error occurs+ */+ delete(language: string): Promise<void>;+}+interface StreamScopedDownloads {+ /**+ * Generates a download for a video when a video is ready to view. Available+ * types are `default` and `audio`. Defaults to `default` when omitted.+ * @param downloadType The download type to create.+ * @returns The current downloads for the video.+ * @throws {NotFoundError} if the video is not found+ * @throws {BadRequestError} if the download type is invalid+ * @throws {StreamError} if the video duration is too long to generate a download+ * @throws {StreamError} if the video is not ready to stream+ * @throws {InternalError} if an unexpected error occurs+ */+ generate(downloadType?: StreamDownloadType): Promise<StreamDownloadGetResponse>;+ /**+ * Lists the downloads created for a video.+ * @returns The current downloads for the video.+ * @throws {NotFoundError} if the video or downloads are not found+ * @throws {InternalError} if an unexpected error occurs+ */+ get(): Promise<StreamDownloadGetResponse>;+ /**+ * Delete the downloads for a video. Available types are `default` and `audio`.+ * Defaults to `default` when omitted.+ * @param downloadType The download type to delete.+ * @returns A promise that resolves when deletion completes.+ * @throws {NotFoundError} if the video or downloads are not found+ * @throws {InternalError} if an unexpected error occurs+ */+ delete(downloadType?: StreamDownloadType): Promise<void>;+}+interface StreamVideos {+ /**+ * Lists all videos in a users account.+ * @returns The list of videos.+ * @throws {BadRequestError} if the parameters are invalid+ * @throws {InternalError} if an unexpected error occurs+ */+ list(params?: StreamVideosListParams): Promise<StreamVideo[]>;+}+interface StreamWatermarks {+ /**+ * Generate a new watermark profile+ * @param input The image stream to upload+ * @param params The watermark creation parameters.+ * @returns The created watermark profile.+ * @throws {BadRequestError} if the parameters are invalid+ * @throws {InvalidURLError} if the URL is invalid+ * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached+ * @throws {InternalError} if an unexpected error occurs+ */+ generate(input: ReadableStream, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;+ /**+ * Generate a new watermark profile+ * @param url The image url to upload+ * @param params The watermark creation parameters.+ * @returns The created watermark profile.+ * @throws {BadRequestError} if the parameters are invalid+ * @throws {InvalidURLError} if the URL is invalid+ * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached+ * @throws {InternalError} if an unexpected error occurs+ */+ generate(url: string, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;+ /**+ * Lists all watermark profiles for an account.+ * @returns The list of watermark profiles.+ * @throws {InternalError} if an unexpected error occurs+ */+ list(): Promise<StreamWatermark[]>;+ /**+ * Retrieves details for a single watermark profile.+ * @param watermarkId The watermark profile identifier.+ * @returns The watermark profile details.+ * @throws {NotFoundError} if the watermark is not found+ * @throws {InternalError} if an unexpected error occurs+ */+ get(watermarkId: string): Promise<StreamWatermark>;+ /**+ * Deletes a watermark profile.+ * @param watermarkId The watermark profile identifier.+ * @returns A promise that resolves when deletion completes.+ * @throws {NotFoundError} if the watermark is not found+ * @throws {InternalError} if an unexpected error occurs+ */+ delete(watermarkId: string): Promise<void>;+}+type StreamUpdateVideoParams = {+ /**+ * Lists the origins allowed to display the video. Enter allowed origin+ * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the+ * video to be viewed on any origin.+ */+ allowedOrigins?: Array<string>;+ /**+ * A user-defined identifier for the media creator.+ */+ creator?: string;+ /**+ * The maximum duration in seconds for a video upload. Can be set for a+ * video that is not yet uploaded to limit its duration. Uploads that exceed the+ * specified duration will fail during processing. A value of `-1` means the value+ * is unknown.+ */+ maxDurationSeconds?: number;+ /**+ * A user modifiable key-value store used to reference other systems of+ * record for managing videos.+ */+ meta?: Record<string, string>;+ /**+ * Indicates whether the video can be a accessed using the id. When+ * set to `true`, a signed token must be generated with a signing key to view the+ * video.+ */+ requireSignedURLs?: boolean;+ /**+ * Indicates the date and time at which the video will be deleted. Omit+ * the field to indicate no change, or include with a `null` value to remove an+ * existing scheduled deletion. If specified, must be at least 30 days from upload+ * time.+ */+ scheduledDeletion?: string | null;+ /**+ * The timestamp for a thumbnail image calculated as a percentage value+ * of the video's duration. To convert from a second-wise timestamp to a+ * percentage, divide the desired timestamp by the total duration of the video. If+ * this value is not set, the default thumbnail image is taken from 0s of the+ * video.+ */+ thumbnailTimestampPct?: number;+};+type StreamCaption = {+ /**+ * Whether the caption was generated via AI.+ */+ generated?: boolean;+ /**+ * The language label displayed in the native language to users.+ */+ label: string;+ /**+ * The language tag in BCP 47 format.+ */+ language: string;+ /**+ * The status of a generated caption.+ */+ status?: 'ready' | 'inprogress' | 'error';+};+type StreamDownloadStatus = 'ready' | 'inprogress' | 'error';+type StreamDownloadType = 'default' | 'audio';+type StreamDownload = {+ /**+ * Indicates the progress as a percentage between 0 and 100.+ */+ percentComplete: number;+ /**+ * The status of a generated download.+ */+ status: StreamDownloadStatus;+ /**+ * The URL to access the generated download.+ */+ url?: string;+};+/**+ * An object with download type keys. Each key is optional and only present if that+ * download type has been created.+ */+type StreamDownloadGetResponse = {+ /**+ * The audio-only download. Only present if this download type has been created.+ */+ audio?: StreamDownload;+ /**+ * The default video download. Only present if this download type has been created.+ */+ default?: StreamDownload;+};+type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center';+type StreamWatermark = {+ /**+ * The unique identifier for a watermark profile.+ */+ id: string;+ /**+ * The size of the image in bytes.+ */+ size: number;+ /**+ * The height of the image in pixels.+ */+ height: number;+ /**+ * The width of the image in pixels.+ */+ width: number;+ /**+ * The date and a time a watermark profile was created.+ */+ created: string;+ /**+ * The source URL for a downloaded image. If the watermark profile was created via+ * direct upload, this field is null.+ */+ downloadedFrom: string | null;+ /**+ * A short description of the watermark profile.+ */+ name: string;+ /**+ * The translucency of the image. A value of `0.0` makes the image completely+ * transparent, and `1.0` makes the image completely opaque. Note that if the image+ * is already semi-transparent, setting this to `1.0` will not make the image+ * completely opaque.+ */+ opacity: number;+ /**+ * The whitespace between the adjacent edges (determined by position) of the video+ * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded+ * video width or length, as determined by the algorithm.+ */+ padding: number;+ /**+ * The size of the image relative to the overall size of the video. This parameter+ * will adapt to horizontal and vertical videos automatically. `0.0` indicates no+ * scaling (use the size of the image as-is), and `1.0 `fills the entire video.+ */+ scale: number;+ /**+ * The location of the image. Valid positions are: `upperRight`, `upperLeft`,+ * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the+ * `padding` parameter.+ */+ position: StreamWatermarkPosition;+};+type StreamWatermarkCreateParams = {+ /**+ * A short description of the watermark profile.+ */+ name?: string;+ /**+ * The translucency of the image. A value of `0.0` makes the image completely+ * transparent, and `1.0` makes the image completely opaque. Note that if the+ * image is already semi-transparent, setting this to `1.0` will not make the+ * image completely opaque.+ */+ opacity?: number;+ /**+ * The whitespace between the adjacent edges (determined by position) of the+ * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully+ * padded video width or length, as determined by the algorithm.+ */+ padding?: number;+ /**+ * The size of the image relative to the overall size of the video. This+ * parameter will adapt to horizontal and vertical videos automatically. `0.0`+ * indicates no scaling (use the size of the image as-is), and `1.0 `fills the+ * entire video.+ */+ scale?: number;+ /**+ * The location of the image.+ */+ position?: StreamWatermarkPosition;+};+type StreamVideosListParams = {+ /**+ * The maximum number of videos to return.+ */+ limit?: number;+ /**+ * Return videos created before this timestamp.+ * (RFC3339/RFC3339Nano)+ */+ before?: string;+ /**+ * Comparison operator for the `before` field.+ * @default 'lt'+ */+ beforeComp?: StreamPaginationComparison;+ /**+ * Return videos created after this timestamp.+ * (RFC3339/RFC3339Nano)+ */+ after?: string;+ /**+ * Comparison operator for the `after` field.+ * @default 'gte'+ */+ afterComp?: StreamPaginationComparison;+};+type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte';+/**+ * Error object for Stream binding operations.+ */+interface StreamError extends Error {+ readonly code: number;+ readonly statusCode: number;+ readonly message: string;+ readonly stack?: string;+}+interface InternalError extends StreamError {+ name: 'InternalError';+}+interface BadRequestError extends StreamError {+ name: 'BadRequestError';+}+interface NotFoundError extends StreamError {+ name: 'NotFoundError';+}+interface ForbiddenError extends StreamError {+ name: 'ForbiddenError';+}+interface RateLimitedError extends StreamError {+ name: 'RateLimitedError';+}+interface QuotaReachedError extends StreamError {+ name: 'QuotaReachedError';+}+interface MaxFileSizeError extends StreamError {+ name: 'MaxFileSizeError';+}+interface InvalidURLError extends StreamError {+ name: 'InvalidURLError';+}+interface AlreadyUploadedError extends StreamError {+ name: 'AlreadyUploadedError';+}+interface TooManyWatermarksError extends StreamError {+ name: 'TooManyWatermarksError';+}+type MarkdownDocument = {+ name: string;+ blob: Blob;+};+type OutputFormat = 'markdown' | 'text';+type ConversionResponse = {+ id: string;+ name: string;+ mimeType: string;+ format: OutputFormat;+ tokens: number;+ data: string;+} | {+ id: string;+ name: string;+ mimeType: string;+ format: 'error';+ error: string;+};+type ImageConversionOptions = {+ descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de';+};+type EmbeddedImageConversionOptions = ImageConversionOptions & {+ convert?: boolean;+ maxConvertedImages?: number;+};+type ConversionOutputOptions = {+ format?: OutputFormat;+};+type ConversionOptions = {+ output?: ConversionOutputOptions;+ html?: {+ images?: EmbeddedImageConversionOptions & {+ convertOGImage?: boolean;+ };+ hostname?: string;+ cssSelector?: string;+ };+ docx?: {+ images?: EmbeddedImageConversionOptions;+ };+ image?: ImageConversionOptions;+ pdf?: {+ images?: EmbeddedImageConversionOptions;+ metadata?: boolean;+ };+};+type ConversionRequestOptions = {+ gateway?: GatewayOptions;+ extraHeaders?: object;+ conversionOptions?: ConversionOptions;+};+type SupportedFileFormat = {+ mimeType: string;+ extension: string;+};+declare abstract class ToMarkdownService {+ transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;+ transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;+ supported(): Promise<SupportedFileFormat[]>;+}+declare namespace TailStream {+ interface Header {+ readonly name: string;+ readonly value: string;+ }+ interface FetchEventInfo {+ readonly type: "fetch";+ readonly method: string;+ readonly url: string;+ readonly cfJson?: object;+ readonly headers: Header[];+ }+ interface JsRpcEventInfo {+ readonly type: "jsrpc";+ }+ interface ScheduledEventInfo {+ readonly type: "scheduled";+ readonly scheduledTime: Date;+ readonly cron: string;+ }+ interface AlarmEventInfo {+ readonly type: "alarm";+ readonly scheduledTime: Date;+ }+ interface QueueEventInfo {+ readonly type: "queue";+ readonly queueName: string;+ readonly batchSize: number;+ }+ interface EmailEventInfo {+ readonly type: "email";+ readonly mailFrom: string;+ readonly rcptTo: string;+ readonly rawSize: number;+ }+ interface TraceEventInfo {+ readonly type: "trace";+ readonly traces: (string | null)[];+ }+ interface HibernatableWebSocketEventInfoMessage {+ readonly type: "message";+ }+ interface HibernatableWebSocketEventInfoError {+ readonly type: "error";+ }+ interface HibernatableWebSocketEventInfoClose {+ readonly type: "close";+ readonly code: number;+ readonly wasClean: boolean;+ }+ interface HibernatableWebSocketEventInfo {+ readonly type: "hibernatableWebSocket";+ readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage;+ }+ interface CustomEventInfo {+ readonly type: "custom";+ }+ interface FetchResponseInfo {+ readonly type: "fetch";+ readonly statusCode: number;+ }+ interface ConnectEventInfo {+ readonly type: "connect";+ }+ type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound" | "internalError" | "exceededWallTime" | "aborted";+ interface ScriptVersion {+ readonly id: string;+ readonly tag?: string;+ readonly message?: string;+ }+ interface TracePreviewInfo {+ readonly id: string;+ readonly slug: string;+ readonly name: string;+ }+ interface Onset {+ readonly type: "onset";+ readonly attributes: Attribute[];+ // id for the span being opened by this Onset event.+ readonly spanId: string;+ readonly dispatchNamespace?: string;+ readonly entrypoint?: string;+ readonly executionModel: string;+ readonly durableObjectId?: string;+ readonly scriptName?: string;+ readonly scriptTags?: string[];+ readonly scriptVersion?: ScriptVersion;+ readonly preview?: TracePreviewInfo;+ readonly info: FetchEventInfo | ConnectEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo;+ }+ interface Outcome {+ readonly type: "outcome";+ readonly outcome: EventOutcome;+ readonly cpuTime: number;+ readonly wallTime: number;+ }+ interface SpanOpen {+ readonly type: "spanOpen";+ readonly name: string;+ // id for the span being opened by this SpanOpen event.+ readonly spanId: string;+ readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes;+ }+ interface SpanClose {+ readonly type: "spanClose";+ readonly outcome: EventOutcome;+ }+ interface DiagnosticChannelEvent {+ readonly type: "diagnosticChannel";+ readonly channel: string;+ readonly message: any;+ }+ interface Exception {+ readonly type: "exception";+ readonly code?: string | number;+ readonly name: string;+ readonly message: string;+ readonly stack?: string;+ }+ interface TailStreamErrorInfo {+ readonly name: string;+ readonly message: string;+ readonly stack?: string;+ }+ type Log = {+ readonly type: "log";+ readonly level: "debug" | "error" | "info" | "log" | "warn";+ readonly errorInfo?: readonly (TailStreamErrorInfo | null)[];+ } & ({+ readonly message: object;+ readonly truncated?: false;+ } | {+ readonly message: string;+ readonly truncated: true;+ });+ interface DroppedEventsDiagnostic {+ readonly diagnosticsType: "droppedEvents";+ readonly count: number;+ }+ interface StreamDiagnostic {+ readonly type: 'streamDiagnostic';+ // To add new diagnostic types, define a new interface and add it to this union type.+ readonly diagnostic: DroppedEventsDiagnostic;+ }+ // This marks the worker handler return information.+ // This is separate from Outcome because the worker invocation can live for a long time after+ // returning. For example - Websockets that return an http upgrade response but then continue+ // streaming information or SSE http connections.+ interface Return {+ readonly type: "return";+ readonly info?: FetchResponseInfo;+ }+ interface Attribute {+ readonly name: string;+ readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[];+ }+ interface Attributes {+ readonly type: "attributes";+ readonly info: Attribute[];+ }+ type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes;+ // Context in which this trace event lives.+ interface SpanContext {+ // Single id for the entire top-level invocation+ // This should be a new traceId for the first worker stage invoked in the eyeball request and then+ // same-account service-bindings should reuse the same traceId but cross-account service-bindings+ // should use a new traceId.+ readonly traceId: string;+ // spanId in which this event is handled+ // for Onset and SpanOpen events this would be the parent span id+ // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events+ // For Hibernate and Mark this would be the span under which they were emitted.+ // spanId is not set ONLY if:+ // 1. This is an Onset event+ // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation)+ readonly spanId?: string;+ // W3C trace flags from an upstream traceparent. Absent when no upstream+ // sampling decision was made.+ readonly traceFlags?: number;+ }+ interface TailEvent<Event extends EventType> {+ // invocation id of the currently invoked worker stage.+ // invocation id will always be unique to every Onset event and will be the same until the Outcome event.+ readonly invocationId: string;+ // Inherited spanContext for this event.+ readonly spanContext: SpanContext;+ readonly timestamp: Date;+ readonly sequence: number;+ readonly event: Event;+ }+ type TailEventHandler<Event extends EventType = EventType> = (event: TailEvent<Event>) => void | Promise<void>;+ type TailEventHandlerObject = {+ outcome?: TailEventHandler<Outcome>;+ spanOpen?: TailEventHandler<SpanOpen>;+ spanClose?: TailEventHandler<SpanClose>;+ diagnosticChannel?: TailEventHandler<DiagnosticChannelEvent>;+ exception?: TailEventHandler<Exception>;+ log?: TailEventHandler<Log>;+ return?: TailEventHandler<Return>;+ attributes?: TailEventHandler<Attributes>;+ };+ type TailEventHandlerType = TailEventHandler | TailEventHandlerObject;+}+// Copyright (c) 2022-2023 Cloudflare, Inc.+// Licensed under the Apache 2.0 license found in the LICENSE file or at:+// https://opensource.org/licenses/Apache-2.0+/**+ * Data types supported for holding vector metadata.+ */+type VectorizeVectorMetadataValue = string | number | boolean | string[];+/**+ * Additional information to associate with a vector.+ */+type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record<string, VectorizeVectorMetadataValue>;+type VectorFloatArray = Float32Array | Float64Array;+interface VectorizeError {+ code?: number;+ error: string;+}+/**+ * Comparison logic/operation to use for metadata filtering.+ *+ * This list is expected to grow as support for more operations are released.+ */+type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte';+type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin';+/**+ * Filter criteria for vector metadata used to limit the retrieved query result set.+ */+type VectorizeVectorMetadataFilter = {+ [field: string]: Exclude<VectorizeVectorMetadataValue, string[]> | null | {+ [Op in VectorizeVectorMetadataFilterOp]?: Exclude<VectorizeVectorMetadataValue, string[]> | null;+ } | {+ [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude<VectorizeVectorMetadataValue, string[]>[];+ };+};+/**+ * Supported distance metrics for an index.+ * Distance metrics determine how other "similar" vectors are determined.+ */+type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product";+/**+ * Metadata return levels for a Vectorize query.+ *+ * Default to "none".+ *+ * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data.+ * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings).+ * @property none No indexed metadata will be returned.+ */+type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none";+interface VectorizeQueryOptions {+ topK?: number;+ namespace?: string;+ returnValues?: boolean;+ returnMetadata?: boolean | VectorizeMetadataRetrievalLevel;+ filter?: VectorizeVectorMetadataFilter;+}+/**+ * Information about the configuration of an index.+ */+type VectorizeIndexConfig = {+ dimensions: number;+ metric: VectorizeDistanceMetric;+} | {+ preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity+};+/**+ * Metadata about an existing index.+ *+ * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.+ * See {@link VectorizeIndexInfo} for its post-beta equivalent.+ */+interface VectorizeIndexDetails {+ /** The unique ID of the index */+ readonly id: string;+ /** The name of the index. */+ name: string;+ /** (optional) A human readable description for the index. */+ description?: string;+ /** The index configuration, including the dimension size and distance metric. */+ config: VectorizeIndexConfig;+ /** The number of records containing vectors within the index. */+ vectorsCount: number;+}+/**+ * Metadata about an existing index.+ */+interface VectorizeIndexInfo {+ /** The number of records containing vectors within the index. */+ vectorCount: number;+ /** Number of dimensions the index has been configured for. */+ dimensions: number;+ /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */+ processedUpToDatetime: number;+ /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */+ processedUpToMutation: number;+}+/**+ * Represents a single vector value set along with its associated metadata.+ */+interface VectorizeVector {+ /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */+ id: string;+ /** The vector values */+ values: VectorFloatArray | number[];+ /** The namespace this vector belongs to. */+ namespace?: string;+ /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */+ metadata?: Record<string, VectorizeVectorMetadata>;+}+/**+ * Represents a matched vector for a query along with its score and (if specified) the matching vector information.+ */+type VectorizeMatch = Pick<Partial<VectorizeVector>, "values"> & Omit<VectorizeVector, "values"> & {+ /** The score or rank for similarity, when returned as a result */+ score: number;+};+/**+ * A set of matching {@link VectorizeMatch} for a particular query.+ */+interface VectorizeMatches {+ matches: VectorizeMatch[];+ count: number;+}+/**+ * Results of an operation that performed a mutation on a set of vectors.+ * Here, `ids` is a list of vectors that were successfully processed.+ *+ * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.+ * See {@link VectorizeAsyncMutation} for its post-beta equivalent.+ */+interface VectorizeVectorMutation {+ /* List of ids of vectors that were successfully processed. */+ ids: string[];+ /* Total count of the number of processed vectors. */+ count: number;+}+/**+ * Result type indicating a mutation on the Vectorize Index.+ * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation.+ */+interface VectorizeAsyncMutation {+ /** The unique identifier for the async mutation operation containing the changeset. */+ mutationId: string;+}+/**+ * A Vectorize Vector Search Index for querying vectors/embeddings.+ *+ * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.+ * See {@link Vectorize} for its new implementation.+ */+declare abstract class VectorizeIndex {+ /**+ * Get information about the currently bound index.+ * @returns A promise that resolves with information about the current index.+ */+ public describe(): Promise<VectorizeIndexDetails>;+ /**+ * Use the provided vector to perform a similarity search across the index.+ * @param vector Input vector that will be used to drive the similarity search.+ * @param options Configuration options to massage the returned data.+ * @returns A promise that resolves with matched and scored vectors.+ */+ public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;+ /**+ * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.+ * @param vectors List of vectors that will be inserted.+ * @returns A promise that resolves with the ids & count of records that were successfully processed.+ */+ public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;+ /**+ * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.+ * @param vectors List of vectors that will be upserted.+ * @returns A promise that resolves with the ids & count of records that were successfully processed.+ */+ public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;+ /**+ * Delete a list of vectors with a matching id.+ * @param ids List of vector ids that should be deleted.+ * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted).+ */+ public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>;+ /**+ * Get a list of vectors with a matching id.+ * @param ids List of vector ids that should be returned.+ * @returns A promise that resolves with the raw unscored vectors matching the id set.+ */+ public getByIds(ids: string[]): Promise<VectorizeVector[]>;+}+/**+ * A Vectorize Vector Search Index for querying vectors/embeddings.+ *+ * Mutations in this version are async, returning a mutation id.+ */+declare abstract class Vectorize {+ /**+ * Get information about the currently bound index.+ * @returns A promise that resolves with information about the current index.+ */+ public describe(): Promise<VectorizeIndexInfo>;+ /**+ * Use the provided vector to perform a similarity search across the index.+ * @param vector Input vector that will be used to drive the similarity search.+ * @param options Configuration options to massage the returned data.+ * @returns A promise that resolves with matched and scored vectors.+ */+ public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;+ /**+ * Use the provided vector-id to perform a similarity search across the index.+ * @param vectorId Id for a vector in the index against which the index should be queried.+ * @param options Configuration options to massage the returned data.+ * @returns A promise that resolves with matched and scored vectors.+ */+ public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise<VectorizeMatches>;+ /**+ * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.+ * @param vectors List of vectors that will be inserted.+ * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset.+ */+ public insert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;+ /**+ * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.+ * @param vectors List of vectors that will be upserted.+ * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset.+ */+ public upsert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;+ /**+ * Delete a list of vectors with a matching id.+ * @param ids List of vector ids that should be deleted.+ * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset.+ */+ public deleteByIds(ids: string[]): Promise<VectorizeAsyncMutation>;+ /**+ * Get a list of vectors with a matching id.+ * @param ids List of vector ids that should be returned.+ * @returns A promise that resolves with the raw unscored vectors matching the id set.+ */+ public getByIds(ids: string[]): Promise<VectorizeVector[]>;+}+/**+ * The interface for "version_metadata" binding+ * providing metadata about the Worker Version using this binding.+ */+type WorkerVersionMetadata = {+ /** The ID of the Worker Version using this binding */+ id: string;+ /** The tag of the Worker Version using this binding */+ tag: string;+ /** The timestamp of when the Worker Version was uploaded */+ timestamp: string;+};+// ============ Web Search Request Types ============+/**+ * Options for a Web Search query.+ */+type WebSearchSearchOptions = {+ /** The search query. */+ query: string;+ /**+ * Maximum number of results to return. Defaults to 10, capped at 20.+ * The actual count may be lower if fewer matches exist.+ */+ limit?: number;+};+// ============ Web Search Response Types ============+/**+ * A single Web Search result.+ *+ * Web Search is discovery-only -- results carry catalog metadata about a page+ * but never the page body. To read a result's content the caller invokes the+ * global `fetch()` API against the result's `url`, at which point the+ * destination's own access controls apply (including Cloudflare Pay-per-Crawl).+ */+type WebSearchResult = {+ /** Canonical URL. */+ url: string;+ /** Page title. */+ title: string;+ /** Page-level description. May be absent. */+ description?: string;+ /**+ * Last-modified date for the page, when known. Naive (no timezone)+ * ISO-8601 datetime, e.g. `"2025-11-30T04:39:48"`.+ */+ lastModifiedDate?: string;+ /**+ * Page meta image URL (typically the `og:image`). May be absent.+ */+ imageUrl?: string;+ /** Optional favicon URL for UI hints. */+ faviconUrl?: string;+};+/**+ * Per-response metadata for a Web Search query. Carries operational+ * fields useful for support and debugging.+ */+type WebSearchResponseMetadata = {+ /** The query that was executed. */+ query: string;+ /** Opaque request identifier used for support and debugging. */+ requestId: string;+ /** End-to-end latency for this search request, in milliseconds. */+ latencyMs: number;+};+/**+ * Response from a Web Search query.+ */+type WebSearchSearchResponse = {+ items: WebSearchResult[];+ metadata: WebSearchResponseMetadata;+};+// ============ Web Search Binding Class ============+/**+ * Cloudflare Web Search binding.+ *+ * Discovery-only primitive for agents and Workers. Returns URLs and catalog+ * metadata for a query; never returns page content or excerpts. To read a+ * result's body, fetch the URL with the global `fetch()` API.+ *+ * Declared in wrangler with a single object (there is exactly one corpus, the+ * public web, so there is no name, namespace, or instance to specify):+ *+ * ```jsonc+ * { "web_search": { "binding": "WEBSEARCH" } }+ * ```+ *+ * @example+ * ```ts+ * const { items, metadata } = await env.WEBSEARCH.search({+ * query: "Cloudflare Workers",+ * });+ *+ * const top = items[0];+ * console.log(top.url, top.title, metadata.latencyMs);+ *+ * // Read content yourself; pay-per-crawl and other publisher+ * // controls apply at the fetch site, not at search time.+ * const page = await fetch(top.url);+ * ```+ */+declare abstract class WebSearch {+ /**+ * Run a Web Search query.+ * @param options Search options. Only `query` is required.+ * @returns The matching results plus per-response metadata.+ */+ search(options: WebSearchSearchOptions): Promise<WebSearchSearchResponse>;+}+interface DynamicDispatchLimits {+ /**+ * Limit CPU time in milliseconds.+ */+ cpuMs?: number;+ /**+ * Limit number of subrequests.+ */+ subRequests?: number;+}+interface DynamicDispatchOptions {+ /**+ * Limit resources of invoked Worker script.+ */+ limits?: DynamicDispatchLimits;+ /**+ * Arguments for outbound Worker script, if configured.+ */+ outbound?: {+ [key: string]: any;+ };+}+interface DispatchNamespace {+ /**+ * @param name Name of the Worker script.+ * @param args Arguments to Worker script.+ * @param options Options for Dynamic Dispatch invocation.+ * @returns A Fetcher object that allows you to send requests to the Worker script.+ * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown.+ */+ get(name: string, args?: {+ [key: string]: any;+ }, options?: DynamicDispatchOptions): Fetcher;+}+declare module 'cloudflare:workflows' {+ /**+ * NonRetryableError allows for a user to throw a fatal error+ * that makes a Workflow instance fail immediately without triggering a retry+ */+ export class NonRetryableError extends Error {+ public constructor(message: string, name?: string);+ }+}+declare abstract class Workflow<PARAMS = unknown> {+ /**+ * Get a handle to an existing instance of the Workflow.+ * @param id Id for the instance of this Workflow+ * @returns A promise that resolves with a handle for the Instance+ */+ public get(id: string): Promise<WorkflowInstance>;+ /**+ * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown.+ * @param options Options when creating an instance including id and params+ * @returns A promise that resolves with a handle for the Instance+ */+ public create(options?: WorkflowInstanceCreateOptions<PARAMS>): Promise<WorkflowInstance>;+ /**+ * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown.+ * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached.+ * @param batch List of Options when creating an instance including name and params+ * @returns A promise that resolves with a list of handles for the created instances.+ */+ public createBatch(batch: WorkflowInstanceCreateOptions<PARAMS>[]): Promise<WorkflowInstance[]>;+ /**+ * Delete a batch of Workflow instances and their stored state.+ * `deleteBatch` is limited to 100 instances at a time. Duplicate IDs are deleted once.+ * The result contains one entry for each input position; IDs that do not exist are returned as per-instance errors.+ * @param instanceIds IDs of the Workflow instances to delete+ * @returns A promise that resolves with the successfully deleted instances and any per-instance errors.+ */+ public deleteBatch(instanceIds: string[]): Promise<WorkflowBatchDeleteResult>;+}+type WorkflowBatchDeleteResult = {+ deleted: {+ id: string;+ }[];+ errors: {+ id: string;+ code: number;+ message: string;+ }[];+};+type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';+type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;+type WorkflowRetentionDuration = WorkflowSleepDuration;+/** Geographic regions supported when creating a Workflow instance.+ * Location hints are best-effort placement preferences. */+type WorkflowInstanceLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'apac-ne' | 'apac-se' | 'oc' | 'afr' | 'me';+interface WorkflowInstanceCreateOptions<PARAMS = unknown> {+ /**+ * An id for your Workflow instance. Must be unique within the Workflow.+ */+ id?: string;+ /**+ * The event payload the Workflow instance is triggered with+ */+ params?: PARAMS;+ /**+ * The retention policy for Workflow instance.+ * Defaults to the maximum retention period available for the owner's account.+ */+ retention?: {+ successRetention?: WorkflowRetentionDuration;+ errorRetention?: WorkflowRetentionDuration;+ };+ /** A best-effort geographic placement preference for the Workflow instance.+ * See `WorkflowInstanceLocationHint` for supported regions. */+ locationHint?: WorkflowInstanceLocationHint;+}+type InstanceStatus = {+ status: 'queued' // means that instance is waiting to be started (see concurrency limits)+ | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running+ | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish+ | 'waitingForPause' // instance is finishing the current work to pause+ | 'unknown';+ error?: {+ name: string;+ message: string;+ };+ output?: unknown;+};+interface WorkflowError {+ code?: number;+ message: string;+}+interface WorkflowInstanceTerminateOptions {+ /**+ * If true, run registered rollback handlers before terminating the instance.+ * Only steps that registered rollback handlers are rolled back.+ */+ rollback?: boolean;+}+interface WorkflowInstanceRestartOptions {+ /**+ * Restart from a specific step. If omitted, the instance restarts from the beginning.+ * The step must exist in the instance's execution history.+ */+ from?: {+ /**+ * The step name as defined in your workflow code.+ */+ name: string;+ /**+ * 1-indexed occurrence of this step name. Use when the same step name appears multiple times (e.g. in a loop).+ * @default 1+ */+ count?: number;+ /**+ * Step type filter. Use when different step types share the same name.+ */+ type?: 'do' | 'sleep' | 'waitForEvent';+ };+}+declare abstract class WorkflowInstance {+ public id: string;+ /**+ * Pause the instance.+ */+ public pause(): Promise<void>;+ /**+ * Resume the instance. If it is already running, an error will be thrown.+ */+ public resume(): Promise<void>;+ /**+ * Terminate the instance. If it is errored, terminated or complete, an error will be thrown.+ * @param options Options for termination, including whether registered rollback handlers should run.+ */+ public terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>;+ /**+ * Restart the instance. Optionally restart from a specific step, preserving+ * cached results for all steps before it.+ * @param options Options for the restart, including an optional step to restart from.+ */+ public restart(options?: WorkflowInstanceRestartOptions): Promise<void>;+ /**+ * Delete the instance and its stored state.+ */+ public delete(): Promise<void>;+ /**+ * Returns the current status of the instance.+ */+ public status(): Promise<InstanceStatus>;+ /**+ * Send an event to this instance.+ */+ public sendEvent({ type, payload, }: {+ type: string;+ payload: unknown;+ }): Promise<void>;+}diff --git a/src/queue-worker/src/index.test.ts b/src/queue-worker/src/index.test.tsnew file mode 100644index 000000000..8800e0e4d--- /dev/null+++ b/src/queue-worker/src/index.test.ts@@ -0,0 +1,232 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"++const mockCreateDb = vi.fn((..._args: unknown[]) => ({ database: true }))+const { mockLogWarn } = vi.hoisted(() => ({ mockLogWarn: vi.fn() }))+vi.mock("@alook/shared", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@alook/shared")>()+ return {+ ...actual,+ createLogger: () => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: mockLogWarn,+ error: vi.fn(),+ child() { return this },+ }),+ createDb: (...args: unknown[]) => mockCreateDb(...args),+ }+})++const mockExecuteQueueTask = vi.fn()+vi.mock("./task-handler", () => ({+ executeQueueTask: (...args: unknown[]) => mockExecuteQueueTask(...args),+}))++import handler from "./index"++const legacyWake = { messageId: "message-1", botUserId: "bot-1" }+const botWake = {+ version: 1 as const,+ kind: "bot-wake" as const,+ messageId: "message-1",+ botUserId: "bot-1",+}+const mobilePush = {+ version: 1 as const,+ kind: "mobile-push" as const,+ messageId: "message-1",+ userId: "user-1",+}++function makeMessage(body: unknown) {+ return { body, ack: vi.fn(), retry: vi.fn() }+}++function request(method: string, body?: unknown) {+ return new Request("http://internal/", {+ method,+ body: body === undefined ? undefined : JSON.stringify(body),+ })+}++describe("queue-worker queue consumer", () => {+ const env = { DB: {} } as Env++ beforeEach(() => {+ vi.clearAllMocks()+ mockExecuteQueueTask.mockResolvedValue(undefined)+ })++ it.each([+ ["legacy bot wake", legacyWake, botWake],+ ["v1 bot wake", botWake, botWake],+ ["v1 mobile push", mobilePush, mobilePush],+ ])("normalizes and ACKs a completed %s", async (_name, body, expected) => {+ const message = makeMessage(body)++ await handler.queue({ messages: [message] } as never, env)++ expect(mockCreateDb).toHaveBeenCalledWith(env.DB)+ expect(mockExecuteQueueTask).toHaveBeenCalledWith(+ { database: true },+ env,+ expected,+ )+ expect(message.ack).toHaveBeenCalledTimes(1)+ expect(message.retry).not.toHaveBeenCalled()+ })++ it.each([+ ["malformed", { messageId: "message-1" }, "malformed"],+ ["unknown", { version: 1, kind: "email", messageId: "message-1", userId: "user-1" }, "unknown_kind"],+ ["unsupported", { version: 2, kind: "bot-wake", messageId: "message-1", botUserId: "bot-1" }, "unsupported_version"],+ ])("ACKs a %s poison task without opening D1", async (_name, body, reason) => {+ const message = makeMessage(body)++ await handler.queue({ messages: [message] } as never, env)++ expect(message.ack).toHaveBeenCalledTimes(1)+ expect(message.retry).not.toHaveBeenCalled()+ expect(mockCreateDb).not.toHaveBeenCalled()+ expect(mockExecuteQueueTask).not.toHaveBeenCalled()+ expect(mockLogWarn).toHaveBeenCalledWith("queue_task_ignored", { reason })+ })++ it("retries a thrown bot-wake failure by five seconds", async () => {+ mockExecuteQueueTask.mockRejectedValueOnce(new Error("D1 unavailable"))+ const message = makeMessage(botWake)++ await handler.queue({ messages: [message] } as never, env)++ expect(message.retry).toHaveBeenCalledWith({ delaySeconds: 5 })+ expect(message.ack).not.toHaveBeenCalled()+ })++ it("keeps per-message ACK/retry isolated within one batch", async () => {+ mockExecuteQueueTask+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("transient"))+ .mockResolvedValueOnce(undefined)+ const messages = [+ makeMessage(botWake),+ makeMessage({ ...botWake, botUserId: "bot-2" }),+ makeMessage(mobilePush),+ ]++ await handler.queue({ messages } as never, env)++ expect(messages[0]!.ack).toHaveBeenCalledTimes(1)+ expect(messages[1]!.retry).toHaveBeenCalledWith({ delaySeconds: 5 })+ expect(messages[2]!.ack).toHaveBeenCalledTimes(1)+ })+})++describe("queue-worker development HTTP entrypoint", () => {+ const env = { DB: {} } as Env++ beforeEach(() => {+ vi.clearAllMocks()+ mockExecuteQueueTask.mockResolvedValue(undefined)+ })++ afterEach(() => vi.useRealTimers())++ it("accepts mixed versioned tasks and normalizes legacy wakes", async () => {+ const response = await handler.fetch!(request("POST", [legacyWake, mobilePush]), env)++ expect(response.status).toBe(202)+ expect(mockExecuteQueueTask.mock.calls.map((call) => call[2])).toEqual([+ botWake,+ mobilePush,+ ])+ })++ it("deduplicates only the same kind/message/recipient tuple", async () => {+ const response = await handler.fetch!(request("POST", [+ legacyWake,+ botWake,+ mobilePush,+ { ...mobilePush, userId: "user-2" },+ ]), env)++ expect(response.status).toBe(202)+ expect(mockExecuteQueueTask).toHaveBeenCalledTimes(3)+ })++ it.each([+ ["non-array", legacyWake],+ ["malformed item", [legacyWake, { messageId: "message-2" }]],+ ["unknown item", [legacyWake, { version: 1, kind: "email", messageId: "message-2", userId: "user-2" }]],+ ])("rejects a %s body before D1", async (_name, body) => {+ const response = await handler.fetch!(request("POST", body), env)+ expect(response.status).toBe(400)+ expect(mockCreateDb).not.toHaveBeenCalled()+ expect(mockExecuteQueueTask).not.toHaveBeenCalled()+ })++ it("retries only a failing task and returns its normalized stable key after exhaustion", async () => {+ vi.useFakeTimers()+ mockExecuteQueueTask.mockImplementation(async (_db, _env, task) => {+ if (task.kind === "bot-wake" && task.botUserId === "bot-1") {+ throw new Error("transient")+ }+ })++ const responsePromise = handler.fetch!(request("POST", [legacyWake, mobilePush]), env)+ await vi.runAllTimersAsync()+ const response = await responsePromise++ expect(response.status).toBe(207)+ await expect(response.json()).resolves.toEqual({ failed: [botWake] })+ expect(mockExecuteQueueTask.mock.calls.filter((call) => call[2].kind === "bot-wake")).toHaveLength(3)+ expect(mockExecuteQueueTask.mock.calls.filter((call) => call[2].kind === "mobile-push")).toHaveLength(1)+ expect(mockLogWarn).toHaveBeenCalledWith("dev_http_queue_task_retrying", expect.objectContaining({+ attempt: 1,+ delayMs: 25,+ }))+ expect(mockLogWarn).toHaveBeenCalledWith("dev_http_queue_task_retrying", expect.objectContaining({+ attempt: 2,+ delayMs: 100,+ }))+ expect(mockLogWarn).toHaveBeenCalledWith("dev_http_queue_task_exhausted", expect.objectContaining({+ attempts: 3,+ }))+ })++ it.each([+ [1, []],+ [2, [25]],+ [3, [25, 100]],+ ])("succeeds on attempt %i after only the expected waits", async (successAttempt, delays) => {+ vi.useFakeTimers()+ let attempt = 0+ mockExecuteQueueTask.mockImplementation(async () => {+ attempt += 1+ if (attempt < successAttempt) throw new Error("transient")+ })++ const responsePromise = handler.fetch!(request("POST", [botWake]), env)+ await vi.runAllTimersAsync()+ const response = await responsePromise++ expect(response.status).toBe(202)+ expect(mockExecuteQueueTask).toHaveBeenCalledTimes(successAttempt)+ expect(mockLogWarn.mock.calls+ .filter(([event]) => event === "dev_http_queue_task_retrying")+ .map(([, details]) => details.delayMs)).toEqual(delays)+ expect(mockLogWarn).not.toHaveBeenCalledWith(+ "dev_http_queue_task_exhausted",+ expect.anything(),+ )+ })++ it("serves health and rejects invalid methods or JSON", async () => {+ await expect((await handler.fetch!(new Request("http://internal/health"), env)).json())+ .resolves.toEqual({ status: "ok" })+ expect((await handler.fetch!(request("GET"), env)).status).toBe(405)+ expect((await handler.fetch!(new Request("http://internal/", {+ method: "POST",+ body: "not-json",+ }), env)).status).toBe(400)+ })+})diff --git a/src/queue-worker/src/index.ts b/src/queue-worker/src/index.tsnew file mode 100644index 000000000..eb0ef6365--- /dev/null+++ b/src/queue-worker/src/index.ts@@ -0,0 +1,152 @@+import {+ createLogger,+ createDb,+ parseQueueTask,+ parseQueueTaskBatch,+} from "@alook/shared"+import type { AlookQueueTask, Database } from "@alook/shared"+import { executeQueueTask } from "./task-handler"++const log = createLogger({ service: "queue-worker" })+const DEV_HTTP_MAX_ATTEMPTS = 3+const DEV_HTTP_RETRY_DELAYS_MS = [25, 100] as const++/**+ * Deduplicate one batch by its stable task tuple. Both production Queue and+ * the dev-only HTTP shim execute the same normalized task handler.+ */+function dedupeQueueTasks(tasks: AlookQueueTask[]): AlookQueueTask[] {+ const seen = new Set<string>()+ return tasks.filter((task) => {+ const recipientId = task.kind === "bot-wake" ? task.botUserId : task.userId+ const key = JSON.stringify([task.kind, task.messageId, recipientId])+ if (seen.has(key)) return false+ seen.add(key)+ return true+ })+}++async function waitForDevHttpRetry(delayMs: number): Promise<void> {+ await new Promise<void>((resolve) => setTimeout(resolve, delayMs))+}++async function resolveDevHttpTask(db: Database, env: Env, task: AlookQueueTask): Promise<boolean> {+ for (let retryIndex = 0; retryIndex < DEV_HTTP_RETRY_DELAYS_MS.length; retryIndex++) {+ try {+ await executeQueueTask(db, env, task)+ return true+ } catch (err) {+ const attempt = retryIndex + 1+ const delayMs = DEV_HTTP_RETRY_DELAYS_MS[retryIndex]!+ log.warn("dev_http_queue_task_retrying", {+ kind: task.kind,+ messageId: task.messageId,+ attempt,+ delayMs,+ errorName: err instanceof Error ? err.name : "unknown",+ })+ await waitForDevHttpRetry(delayMs)+ }+ }++ try {+ await executeQueueTask(db, env, task)+ return true+ } catch (err) {+ log.warn("dev_http_queue_task_exhausted", {+ kind: task.kind,+ messageId: task.messageId,+ attempts: DEV_HTTP_MAX_ATTEMPTS,+ errorName: err instanceof Error ? err.name : "unknown",+ })+ return false+ }+}++export default {+ /**+ * `alook-queue-worker` — Cloudflare Queue consumer for `alook-queue`+ * (minimal-wake-queue-unread-notice plan §3). Owns a `DB` binding to the+ * same `alook-app` database `src/web` writes to: for every minimal+ * accepted legacy or v1 `bot-wake` queue item, `dispatchOneUnreadWake`+ * re-reads CURRENT D1 state and only then forwards a freshly built+ * `agent:wake` `HostCommand`. This is what keeps a stale queue item from+ * waking an old machine, an already-caught-up bot, or a bot that lost+ * access to the scope since it was enqueued.+ */+ async queue(batch: MessageBatch<unknown>, env: Env): Promise<void> {+ let db: Database | undefined+ for (const msg of batch.messages) {+ const parsed = parseQueueTask(msg.body)+ if (!parsed.ok) {+ log.warn("queue_task_ignored", { reason: parsed.reason })+ msg.ack()+ continue+ }++ if (!db) db = createDb(env.DB)+ try {+ await executeQueueTask(db, env, parsed.task)+ msg.ack()+ } catch (err) {+ // Transient failure (D1 exception, 5xx / network) — retry with+ // backoff. After `max_retries` (wrangler.toml: 3), the message lands+ // in the DLQ.+ log.warn("bot_wake_failed_retrying", {+ kind: parsed.task.kind,+ messageId: parsed.task.messageId,+ errorName: err instanceof Error ? err.name : "unknown",+ })+ msg.retry({ delaySeconds: 5 })+ }+ }+ },++ /**+ * Dev-only HTTP stand-in for the local Cloudflare Queue. Local Queues+ * simulation cannot bridge separate `wrangler dev`/`next dev` processes+ * (plans/minimal-wake-queue-unread-notice.md), so `src/web`'s+ * `queue-transport.ts` calls this route (via the `QUEUE_WORKER` service+ * binding, `NODE_ENV === "development"` only) instead of+ * `TASK_QUEUE.sendBatch(...)`. Body is a JSON array of accepted legacy or+ * v1 queue tasks. Runs the same handler as `queue()`, including current-D1+ * revalidation and, for bot wakes, the real forward to `alook-ws-do`.+ * There is no durable queue behind this dev path:+ * candidates get bounded in-process retries and exhausted stable keys are+ * returned visibly as a 207 partial result. A partial result is deliberately+ * not a 5xx because the caller's binding/HTTP fallback would otherwise+ * replay the full batch and duplicate already-successful siblings.+ */+ async fetch(request: Request, env: Env): Promise<Response> {+ const url = new URL(request.url)+ if (url.pathname === "/health" && request.method === "GET") {+ return Response.json({ status: "ok" })+ }++ if (request.method !== "POST") return new Response("method not allowed", { status: 405 })++ let body: unknown+ try {+ body = await request.json()+ } catch {+ return new Response("invalid json body", { status: 400 })+ }++ const parsed = parseQueueTaskBatch(body)+ if (!parsed.ok) return new Response("invalid queue payload", { status: 400 })+ if (parsed.tasks.length === 0) return new Response(null, { status: 202 })++ const db = createDb(env.DB)+ const uniqueTasks = dedupeQueueTasks(parsed.tasks)+ const results = await Promise.all(+ uniqueTasks.map(async (task) => ({+ task,+ resolved: await resolveDevHttpTask(db, env, task),+ })),+ )+ const failed = results.filter((result) => !result.resolved).map((result) => result.task)+ if (failed.length > 0) return Response.json({ failed }, { status: 207 })++ return new Response(null, { status: 202 })+ },+} satisfies ExportedHandler<Env>diff --git a/src/queue-worker/src/mobile-push.test.ts b/src/queue-worker/src/mobile-push.test.tsnew file mode 100644index 000000000..5883bb162--- /dev/null+++ b/src/queue-worker/src/mobile-push.test.ts@@ -0,0 +1,183 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const { mockLogInfo, mockLogWarn } = vi.hoisted(() => ({+ mockLogInfo: vi.fn(),+ mockLogWarn: vi.fn(),+}))+vi.mock("@alook/shared", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@alook/shared")>()+ return {+ ...actual,+ createLogger: () => ({+ debug: vi.fn(),+ info: mockLogInfo,+ warn: mockLogWarn,+ error: vi.fn(),+ child() { return this },+ }),+ }+})++import { processMobilePush } from "./mobile-push"++const task = {+ version: 1 as const,+ kind: "mobile-push" as const,+ messageId: "message-1",+ userId: "user-1",+}++type Eligibility = {+ currentLevel: "all" | "mentions" | "nothing"+ hasAttention: boolean+ isUnread: boolean+ isReadable: boolean+}++const eligible: Eligibility = {+ currentLevel: "all" as const,+ hasAttention: false,+ isUnread: true,+ isReadable: true,+}++const target = {+ messageId: "message-1",+ channelId: "channel-1",+ authorName: "Alice",+ content: "private message body",+ attachmentContentTypes: [],+}++function dependencies() {+ return {+ resolveEligibility: vi.fn(async (): Promise<Map<string, Eligibility>> => (+ new Map([[task.userId, eligible]])+ )),+ getTarget: vi.fn(async () => target),+ listDevices: vi.fn(async () => [+ {+ id: "device-ios",+ installationId: "installation-ios",+ platform: "ios" as const,+ providerEnvironment: "sandbox" as const,+ providerTokenEncrypted: "ciphertext-ios",+ },+ {+ id: "device-android",+ installationId: "installation-android",+ platform: "android" as const,+ providerEnvironment: "production" as const,+ providerTokenEncrypted: "ciphertext-android",+ },+ ]),+ disableDevice: vi.fn(async () => true),+ decrypt: vi.fn((value: string) => `plain-${value}`),+ buildPayload: vi.fn(async () => ({+ notificationId: "notification-1",+ title: "Alice",+ body: "private message body",+ route: {+ notificationId: "notification-1",+ messageId: "message-1",+ targetId: "channel-1",+ },+ })),+ createFcmAccessToken: vi.fn(async () => "access-token"),+ sendApns: vi.fn(async () => ({ outcome: "sent" as const })),+ sendFcm: vi.fn(async () => ({ outcome: "invalid-token" as const })),+ }+}++const env = {+ ENCRYPTION_KEY: "encryption-key",+ APNS_TEAM_ID: "apns-team",+ APNS_KEY_ID: "apns-key",+ APNS_PRIVATE_KEY: "apns-private-key",+ APNS_TOPIC: "app.test",+ FCM_PROJECT_ID: "fcm-project",+ FCM_CLIENT_EMAIL: "[email protected]",+ FCM_PRIVATE_KEY: "fcm-private-key",+} as Env++describe("mobile-push processing", () => {+ beforeEach(() => vi.clearAllMocks())++ it.each([+ ["message missing", undefined, "message_missing"],+ ["forbidden", { ...eligible, isReadable: false }, "forbidden"],+ ["already read", { ...eligible, isUnread: false }, "already_read"],+ ["muted", { ...eligible, currentLevel: "nothing" }, "muted"],+ ["mention-only without attention", { ...eligible, currentLevel: "mentions" }, "mention_only"],+ ])("skips %s before loading content or devices", async (_name, state, reason) => {+ const deps = dependencies()+ deps.resolveEligibility.mockResolvedValue(new Map<string, Eligibility>(+ state ? [[task.userId, state as Eligibility]] : [],+ ))++ await expect(processMobilePush({} as never, env, task, deps)).resolves.toEqual({+ outcome: "skip",+ reason,+ })+ expect(deps.getTarget).not.toHaveBeenCalled()+ expect(deps.listDevices).not.toHaveBeenCalled()+ })++ it("attempts every active device independently and soft-disables an invalid token", async () => {+ const deps = dependencies()++ await expect(processMobilePush({} as never, env, task, deps)).resolves.toEqual({+ outcome: "processed",+ attempted: 2,+ sent: 1,+ invalidated: 1,+ failed: 0,+ })+ expect(deps.decrypt).toHaveBeenCalledTimes(2)+ expect(deps.sendApns).toHaveBeenCalledWith(expect.objectContaining({+ providerToken: "plain-ciphertext-ios",+ providerEnvironment: "sandbox",+ }))+ expect(deps.sendFcm).toHaveBeenCalledWith(expect.objectContaining({+ providerToken: "plain-ciphertext-android",+ accessToken: "access-token",+ }))+ expect(deps.disableDevice).toHaveBeenCalledWith({}, {+ userId: "user-1",+ installationId: "installation-android",+ now: expect.any(String),+ })+ })++ it("continues siblings and returns a caught failure without logging content or tokens", async () => {+ const deps = dependencies()+ deps.sendApns.mockRejectedValue(new Error("provider unavailable"))++ await expect(processMobilePush({} as never, env, task, deps)).resolves.toMatchObject({+ outcome: "processed",+ attempted: 2,+ sent: 0,+ invalidated: 1,+ failed: 1,+ })+ expect(deps.sendFcm).toHaveBeenCalledTimes(1)+ const logged = JSON.stringify([+ ...mockLogInfo.mock.calls,+ ...mockLogWarn.mock.calls,+ ])+ expect(logged).not.toContain("private message body")+ expect(logged).not.toContain("plain-ciphertext")+ expect(logged).not.toContain("encryption-key")+ })++ it("skips when no active devices remain", async () => {+ const deps = dependencies()+ deps.listDevices.mockResolvedValue([])++ await expect(processMobilePush({} as never, env, task, deps)).resolves.toEqual({+ outcome: "skip",+ reason: "no_active_devices",+ })+ expect(deps.buildPayload).not.toHaveBeenCalled()+ })+})diff --git a/src/queue-worker/src/mobile-push.ts b/src/queue-worker/src/mobile-push.tsnew file mode 100644index 000000000..129ec1997--- /dev/null+++ b/src/queue-worker/src/mobile-push.ts@@ -0,0 +1,164 @@+import { createLogger, queries, type Database, type MobilePushQueueTaskV1 } from "@alook/shared"+import { decrypt } from "@alook/shared/crypto"+import { buildPushNotificationPayload } from "./notification-payload"+import { sendApnsNotification } from "./providers/apns"+import {+ createFcmAccessToken,+ sendFcmNotification,+} from "./providers/fcm"++const log = createLogger({ service: "queue-worker-mobile-push" })++type MobilePushSkipReason =+ | "message_missing"+ | "forbidden"+ | "already_read"+ | "muted"+ | "mention_only"+ | "no_active_devices"++export type MobilePushResult =+ | { outcome: "skip"; reason: MobilePushSkipReason }+ | {+ outcome: "processed"+ attempted: number+ sent: number+ invalidated: number+ failed: number+ }++type MobilePushDependencies = {+ resolveEligibility: typeof queries.communityNotificationEligibility.resolveNotificationEligibilityForUsers+ getTarget: typeof queries.communityNotificationTarget.getPushNotificationTarget+ listDevices: typeof queries.communityPushDevice.listActivePushDevices+ disableDevice: typeof queries.communityPushDevice.disablePushDevice+ decrypt: typeof decrypt+ buildPayload: typeof buildPushNotificationPayload+ createFcmAccessToken: typeof createFcmAccessToken+ sendApns: typeof sendApnsNotification+ sendFcm: typeof sendFcmNotification+}++const defaultDependencies: MobilePushDependencies = {+ resolveEligibility:+ queries.communityNotificationEligibility.resolveNotificationEligibilityForUsers,+ getTarget: queries.communityNotificationTarget.getPushNotificationTarget,+ listDevices: queries.communityPushDevice.listActivePushDevices,+ disableDevice: queries.communityPushDevice.disablePushDevice,+ decrypt,+ buildPayload: buildPushNotificationPayload,+ createFcmAccessToken,+ sendApns: sendApnsNotification,+ sendFcm: sendFcmNotification,+}++function required(value: string | undefined, name: string): string {+ if (!value) throw new Error(`${name} is not configured`)+ return value+}++export async function processMobilePush(+ db: Database,+ env: Env,+ task: MobilePushQueueTaskV1,+ dependencies: MobilePushDependencies = defaultDependencies,+): Promise<MobilePushResult> {+ const eligibility = await dependencies.resolveEligibility(+ db,+ [task.userId],+ task.messageId,+ )+ const state = eligibility.get(task.userId)+ if (!state) return { outcome: "skip", reason: "message_missing" }+ if (!state.isReadable) return { outcome: "skip", reason: "forbidden" }+ if (!state.isUnread) return { outcome: "skip", reason: "already_read" }+ if (!queries.communityNotificationSetting.policyAllows(+ state.currentLevel,+ state.hasAttention,+ )) {+ return {+ outcome: "skip",+ reason: state.currentLevel === "nothing" ? "muted" : "mention_only",+ }+ }++ const [target, devices] = await Promise.all([+ dependencies.getTarget(db, task.messageId),+ dependencies.listDevices(db, task.userId),+ ])+ if (!target) return { outcome: "skip", reason: "message_missing" }+ if (devices.length === 0) return { outcome: "skip", reason: "no_active_devices" }++ const payload = await dependencies.buildPayload(target, task.userId)+ let fcmAccessToken: Promise<string> | undefined+ const results = await Promise.all(devices.map(async (device) => {+ const startedAt = Date.now()+ try {+ const providerToken = dependencies.decrypt(+ device.providerTokenEncrypted,+ required(env.ENCRYPTION_KEY, "ENCRYPTION_KEY"),+ )+ const providerResult = device.platform === "ios"+ ? await dependencies.sendApns({+ providerToken,+ providerEnvironment: device.providerEnvironment,+ payload,+ config: {+ teamId: required(env.APNS_TEAM_ID, "APNS_TEAM_ID"),+ keyId: required(env.APNS_KEY_ID, "APNS_KEY_ID"),+ privateKey: required(env.APNS_PRIVATE_KEY, "APNS_PRIVATE_KEY"),+ topic: required(env.APNS_TOPIC, "APNS_TOPIC"),+ },+ })+ : await dependencies.sendFcm({+ providerToken,+ accessToken: await (fcmAccessToken ??= dependencies.createFcmAccessToken({+ projectId: required(env.FCM_PROJECT_ID, "FCM_PROJECT_ID"),+ clientEmail: required(env.FCM_CLIENT_EMAIL, "FCM_CLIENT_EMAIL"),+ privateKey: required(env.FCM_PRIVATE_KEY, "FCM_PRIVATE_KEY"),+ })),+ payload,+ config: {+ projectId: required(env.FCM_PROJECT_ID, "FCM_PROJECT_ID"),+ },+ })++ if (providerResult.outcome === "invalid-token") {+ await dependencies.disableDevice(db, {+ userId: task.userId,+ installationId: device.installationId,+ now: new Date().toISOString(),+ })+ }+ log.info("mobile_push_device_complete", {+ kind: task.kind,+ messageId: task.messageId,+ userId: task.userId,+ deviceId: device.id,+ platform: device.platform,+ outcome: providerResult.outcome,+ durationMs: Date.now() - startedAt,+ })+ return providerResult.outcome+ } catch (error) {+ log.warn("mobile_push_device_failed", {+ kind: task.kind,+ messageId: task.messageId,+ userId: task.userId,+ deviceId: device.id,+ platform: device.platform,+ errorName: error instanceof Error ? error.name : "unknown",+ durationMs: Date.now() - startedAt,+ })+ return "failed" as const+ }+ }))++ return {+ outcome: "processed",+ attempted: devices.length,+ sent: results.filter((outcome) => outcome === "sent").length,+ invalidated: results.filter((outcome) => outcome === "invalid-token").length,+ failed: results.filter((outcome) => outcome === "failed").length,+ }+}diff --git a/src/queue-worker/src/notification-payload.test.ts b/src/queue-worker/src/notification-payload.test.tsnew file mode 100644index 000000000..f3da980d1--- /dev/null+++ b/src/queue-worker/src/notification-payload.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from "vitest"+import {+ buildPushNotificationPayload,+ deriveNotificationId,+} from "./notification-payload"++function target(overrides: Partial<{+ messageId: string+ channelId: string+ authorName: string+ content: string+ attachmentContentTypes: Array<string | null>+}> = {}) {+ return {+ messageId: "message-1",+ channelId: "channel-1",+ authorName: "Alice",+ content: "**Hello** [there](https://example.test)\nnext line",+ attachmentContentTypes: [],+ ...overrides,+ }+}++describe("mobile notification payload", () => {+ it("derives a stable UUID-shaped ID from the user and message", async () => {+ const first = await deriveNotificationId({ messageId: "message-1", userId: "user-1" })+ const duplicate = await deriveNotificationId({ messageId: "message-1", userId: "user-1" })+ const otherUser = await deriveNotificationId({ messageId: "message-1", userId: "user-2" })++ expect(first).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)+ expect(duplicate).toBe(first)+ expect(otherUser).not.toBe(first)+ })++ it("emits a minimal plain-text preview and opaque route", async () => {+ const payload = await buildPushNotificationPayload(target(), "user-1")++ expect(payload).toEqual({+ notificationId: payload.notificationId,+ title: "Alice",+ body: "Hello there next line",+ route: {+ notificationId: payload.notificationId,+ messageId: "message-1",+ targetId: "channel-1",+ },+ })+ expect(JSON.stringify(payload)).not.toContain("https://example.test")+ })++ it.each([+ [["image/png"], "Photo"],+ [["video/mp4"], "Video"],+ [["audio/mpeg"], "Audio"],+ [["application/pdf"], "Attachment"],+ [[], "New message"],+ ])("uses an attachment-type fallback for %j", async (attachmentContentTypes, expected) => {+ const payload = await buildPushNotificationPayload(target({+ content: " ",+ attachmentContentTypes,+ }), "user-1")+ expect(payload.body).toBe(expected)+ })++ it("caps the body without splitting surrogate pairs", async () => {+ const payload = await buildPushNotificationPayload(target({+ content: `${"x".repeat(118)}😀tail`,+ }), "user-1")+ expect(payload.body).not.toContain("�")+ expect(payload.body.endsWith("…")).toBe(true)+ })+})diff --git a/src/queue-worker/src/notification-payload.ts b/src/queue-worker/src/notification-payload.tsnew file mode 100644index 000000000..2e7fe2fba--- /dev/null+++ b/src/queue-worker/src/notification-payload.ts@@ -0,0 +1,77 @@+import {+ stripInlineMarkup,+ truncateMessagePreview,+ type queries,+} from "@alook/shared"++export interface PushNotificationPayload {+ notificationId: string+ title: string+ body: string+ route: {+ notificationId: string+ messageId: string+ targetId: string+ }+}++function bytesToUuid(bytes: Uint8Array): string {+ const value = new Uint8Array(bytes.slice(0, 16))+ value[6] = (value[6]! & 0x0f) | 0x50+ value[8] = (value[8]! & 0x3f) | 0x80+ const hex = Array.from(value, (byte) => byte.toString(16).padStart(2, "0"))+ return [+ hex.slice(0, 4).join(""),+ hex.slice(4, 6).join(""),+ hex.slice(6, 8).join(""),+ hex.slice(8, 10).join(""),+ hex.slice(10, 16).join(""),+ ].join("-")+}++export async function deriveNotificationId(input: {+ messageId: string+ userId: string+}): Promise<string> {+ const encoded = new TextEncoder().encode(JSON.stringify([+ "alook:mobile-push:v1",+ input.userId,+ input.messageId,+ ]))+ const digest = await crypto.subtle.digest("SHA-256", encoded)+ return bytesToUuid(new Uint8Array(digest))+}++function attachmentFallback(contentTypes: Array<string | null>): string {+ if (contentTypes.some((value) => value?.startsWith("image/"))) return "Photo"+ if (contentTypes.some((value) => value?.startsWith("video/"))) return "Video"+ if (contentTypes.some((value) => value?.startsWith("audio/"))) return "Audio"+ if (contentTypes.length > 0) return "Attachment"+ return "New message"+}++export async function buildPushNotificationPayload(+ target: queries.communityNotificationTarget.PushNotificationTarget,+ userId: string,+): Promise<PushNotificationPayload> {+ const notificationId = await deriveNotificationId({+ messageId: target.messageId,+ userId,+ })+ const plainText = stripInlineMarkup(target.content)+ .replace(/\s+/gu, " ")+ .trim()++ return {+ notificationId,+ title: target.authorName.trim() || "Alook",+ body: plainText+ ? truncateMessagePreview(plainText)+ : attachmentFallback(target.attachmentContentTypes),+ route: {+ notificationId,+ messageId: target.messageId,+ targetId: target.channelId,+ },+ }+}diff --git a/src/queue-worker/src/providers/apns.test.ts b/src/queue-worker/src/providers/apns.test.tsnew file mode 100644index 000000000..cc7a5905d--- /dev/null+++ b/src/queue-worker/src/providers/apns.test.ts@@ -0,0 +1,593 @@+import { describe, expect, it, vi } from "vitest"+import {+ createApnsProviderTokenProvider,+ PushProviderError,+ sendApnsNotification,+} from "./apns"++const payload = {+ notificationId: "4cb8126e-4842-5c26-8d3f-02031c3d014b",+ title: "Alice",+ body: "Hello",+ route: {+ notificationId: "4cb8126e-4842-5c26-8d3f-02031c3d014b",+ messageId: "message-1",+ targetId: "channel-1",+ },+}++function input(environment: "sandbox" | "production" = "production") {+ return {+ providerToken: "provider-token",+ providerEnvironment: environment,+ payload,+ config: {+ teamId: "test-team",+ keyId: "test-key",+ privateKey: "-----BEGIN PRIVATE KEY-----\ndGVzdC1wcml2YXRlLWtleQ==\n-----END PRIVATE KEY-----",+ topic: "app.test",+ },+ }+}++function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (error: Error) => void+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise+ reject = rejectPromise+ })+ return { promise, reject, resolve }+}++async function createEcPrivateKeyPem(): Promise<string> {+ const keyPair = await crypto.subtle.generateKey({+ name: "ECDSA",+ namedCurve: "P-256",+ }, true, ["sign", "verify"]) as CryptoKeyPair+ const privateKey = await crypto.subtle.exportKey("pkcs8", keyPair.privateKey)+ const encoded = Buffer.from(privateKey).toString("base64")+ const lines = encoded.match(/.{1,64}/gu) ?? []+ return `-----BEGIN PRIVATE KEY-----\n${lines.join("\n")}\n-----END PRIVATE KEY-----`+}++describe("APNs adapter", () => {+ it("signs a real provider JWT and uses the default send dependencies", async () => {+ const originalFetch = globalThis.fetch+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ new Response(null, { status: 200 })+ ))+ globalThis.fetch = fetchMock as typeof fetch+ vi.resetModules()++ try {+ const { sendApnsNotification: sendWithFreshDefaults } = await import("./apns")+ await expect(sendWithFreshDefaults({+ ...input(),+ config: { ...input().config, privateKey: await createEcPrivateKeyPem() },+ })).resolves.toEqual({ outcome: "sent" })++ const [, init] = fetchMock.mock.calls[0]!+ const authorization = (init?.headers as Record<string, string>).authorization+ const [headerPart, claimsPart, signaturePart] = authorization.slice("bearer ".length).split(".")+ expect(JSON.parse(Buffer.from(headerPart!, "base64url").toString())).toEqual({+ alg: "ES256",+ kid: "test-key",+ })+ expect(JSON.parse(Buffer.from(claimsPart!, "base64url").toString())).toMatchObject({+ iss: "test-team",+ iat: expect.any(Number),+ })+ expect(signaturePart).not.toBe("")+ } finally {+ globalThis.fetch = originalFetch+ vi.resetModules()+ }+ })++ it("sends the minimal alert with deterministic replace/group identifiers", async () => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ new Response(null, { status: 200 })+ ))++ await expect(sendApnsNotification(input("sandbox"), {+ fetch: fetchMock as typeof fetch,+ getProviderToken: vi.fn(async () => "signed-token"),+ })).resolves.toEqual({ outcome: "sent" })++ const [url, init] = fetchMock.mock.calls[0]!+ expect(url).toBe("https://api.sandbox.push.apple.com/3/device/provider-token")+ expect(init?.headers).toMatchObject({+ authorization: "bearer signed-token",+ "apns-topic": "app.test",+ "apns-push-type": "alert",+ "apns-id": payload.notificationId,+ "apns-collapse-id": payload.notificationId,+ })+ expect(JSON.parse(init?.body as string)).toEqual({+ aps: {+ alert: { title: "Alice", body: "Hello" },+ sound: "default",+ "thread-id": "channel-1",+ },+ ...payload.route,+ })+ })++ it.each(["BadDeviceToken", "DeviceTokenNotForTopic", "Unregistered"])(+ "classifies %s as an invalid device token",+ async (reason) => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ Response.json({ reason }, { status: 400 })+ ))+ await expect(sendApnsNotification(input(), {+ fetch: fetchMock as typeof fetch,+ getProviderToken: vi.fn(async () => "signed-token"),+ })).resolves.toEqual({ outcome: "invalid-token" })+ },+ )++ it("throws a token-free provider error for other failures", async () => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ Response.json({ reason: "TooManyRequests" }, { status: 429 })+ ))+ const result = sendApnsNotification(input(), {+ fetch: fetchMock as typeof fetch,+ getProviderToken: vi.fn(async () => "signed-token"),+ })+ await expect(result).rejects.toEqual(expect.objectContaining<Partial<PushProviderError>>({+ provider: "apns",+ status: 429,+ reason: "TooManyRequests",+ }))+ await expect(result).rejects.not.toThrow(/provider-token|Hello/)+ })++ it("reuses one provider token across device/topic/environment sends until refresh", async () => {+ let now = 1_700_000_000_000+ const createProviderToken = vi.fn(async (_config, issuedAt = 0) => (+ `signed-${issuedAt}`+ ))+ const getProviderToken = createApnsProviderTokenProvider({+ createProviderToken,+ now: () => now,+ })+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ new Response(null, { status: 200 })+ ))+ const dependencies = { fetch: fetchMock as typeof fetch, getProviderToken }++ await sendApnsNotification(input(), dependencies)+ now += 20 * 60 * 1000+ await sendApnsNotification({+ ...input("sandbox"),+ providerToken: "provider-token-2",+ config: { ...input().config, topic: "app.other" },+ }, dependencies)+ now += 29 * 60 * 1000+ await sendApnsNotification({ ...input(), providerToken: "provider-token-3" }, dependencies)+ expect(createProviderToken).toHaveBeenCalledTimes(1)+ expect(fetchMock.mock.calls.map(([, init]) => (+ (init?.headers as Record<string, string>).authorization+ ))).toEqual([+ "bearer signed-1700000000000",+ "bearer signed-1700000000000",+ "bearer signed-1700000000000",+ ])++ now += 60 * 1000+ await sendApnsNotification(input(), dependencies)+ expect(createProviderToken).toHaveBeenCalledTimes(2)+ expect((fetchMock.mock.calls[3]![1]?.headers as Record<string, string>).authorization)+ .toBe("bearer signed-1700003000000")+ })++ it("single-flights concurrent device sends through one provider-token signature", async () => {+ let releaseSignature: ((token: string) => void) | undefined+ const createProviderToken = vi.fn(() => new Promise<string>((resolve) => {+ releaseSignature = resolve+ }))+ const getProviderToken = createApnsProviderTokenProvider({+ createProviderToken,+ now: () => 1_700_000_000_000,+ })+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ new Response(null, { status: 200 })+ ))+ const dependencies = { fetch: fetchMock as typeof fetch, getProviderToken }++ const sends = Promise.all([+ sendApnsNotification(input(), dependencies),+ sendApnsNotification({ ...input(), providerToken: "provider-token-2" }, dependencies),+ sendApnsNotification({ ...input(), providerToken: "provider-token-3" }, dependencies),+ ])+ await vi.waitFor(() => expect(createProviderToken).toHaveBeenCalledTimes(1))+ expect(fetchMock).not.toHaveBeenCalled()+ releaseSignature?.("shared-token")+ await expect(sends).resolves.toEqual([+ { outcome: "sent" },+ { outcome: "sent" },+ { outcome: "sent" },+ ])+ expect(createProviderToken).toHaveBeenCalledTimes(1)+ expect(fetchMock.mock.calls.map(([, init]) => (+ (init?.headers as Record<string, string>).authorization+ ))).toEqual([+ "bearer shared-token",+ "bearer shared-token",+ "bearer shared-token",+ ])+ })++ it("keeps A and B cached independently across sequential A-B-A sends", async () => {+ const createProviderToken = vi.fn(async (config) => `signed-${config.keyId}`)+ const getProviderToken = createApnsProviderTokenProvider({ createProviderToken })+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ new Response(null, { status: 200 })+ ))+ const dependencies = { fetch: fetchMock as typeof fetch, getProviderToken }+ const credentialA = input()+ const credentialB = {+ ...input(),+ config: { ...input().config, keyId: "test-key-b" },+ }++ await sendApnsNotification(credentialA, dependencies)+ await sendApnsNotification(credentialB, dependencies)+ await sendApnsNotification({ ...credentialA, providerToken: "provider-token-2" }, dependencies)++ expect(createProviderToken).toHaveBeenCalledTimes(2)+ expect(fetchMock.mock.calls.map(([, init]) => (+ (init?.headers as Record<string, string>).authorization+ ))).toEqual([+ "bearer signed-test-key",+ "bearer signed-test-key-b",+ "bearer signed-test-key",+ ])+ })++ it("keeps per-credential single-flights across concurrent A-B-A sends", async () => {+ const releaseByKey = new Map<string, (token: string) => void>()+ const createProviderToken = vi.fn((config) => new Promise<string>((resolve) => {+ releaseByKey.set(config.keyId, resolve)+ }))+ const getProviderToken = createApnsProviderTokenProvider({ createProviderToken })+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ new Response(null, { status: 200 })+ ))+ const dependencies = { fetch: fetchMock as typeof fetch, getProviderToken }+ const credentialA = input()+ const credentialB = {+ ...input(),+ providerToken: "provider-token-b",+ config: { ...input().config, keyId: "test-key-b" },+ }++ const sends = [+ sendApnsNotification(credentialA, dependencies),+ sendApnsNotification(credentialB, dependencies),+ sendApnsNotification({ ...credentialA, providerToken: "provider-token-a2" }, dependencies),+ ]+ await vi.waitFor(() => expect(createProviderToken).toHaveBeenCalledTimes(2))+ expect(fetchMock).not.toHaveBeenCalled()+ releaseByKey.get("test-key")?.("signed-a")+ releaseByKey.get("test-key-b")?.("signed-b")+ await expect(Promise.all(sends)).resolves.toEqual([+ { outcome: "sent" },+ { outcome: "sent" },+ { outcome: "sent" },+ ])+ expect(createProviderToken.mock.calls.map(([config]) => config.keyId).sort())+ .toEqual(["test-key", "test-key-b"])+ const authorizationByDevice = new Map(fetchMock.mock.calls.map(([url, init]) => [+ String(url).split("/").at(-1),+ (init?.headers as Record<string, string>).authorization,+ ]))+ expect(authorizationByDevice).toEqual(new Map([+ ["provider-token", "bearer signed-a"],+ ["provider-token-a2", "bearer signed-a"],+ ["provider-token-b", "bearer signed-b"],+ ]))+ })++ it("clears a failed signing flight so the next send can recover", async () => {+ let rejectSignature: ((error: Error) => void) | undefined+ const createProviderToken = vi.fn()+ .mockImplementationOnce(() => new Promise<string>((_resolve, reject) => {+ rejectSignature = reject+ }))+ .mockResolvedValueOnce("recovered-token")+ const getProviderToken = createApnsProviderTokenProvider({ createProviderToken })+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ new Response(null, { status: 200 })+ ))+ const dependencies = { fetch: fetchMock as typeof fetch, getProviderToken }++ const failedSends = [+ sendApnsNotification(input(), dependencies),+ sendApnsNotification({ ...input(), providerToken: "provider-token-2" }, dependencies),+ ]+ await vi.waitFor(() => expect(createProviderToken).toHaveBeenCalledTimes(1))+ rejectSignature?.(new Error("signing failed"))+ const failedResults = await Promise.allSettled(failedSends)+ expect(failedResults).toEqual([+ expect.objectContaining({ status: "rejected" }),+ expect.objectContaining({ status: "rejected" }),+ ])+ await expect(sendApnsNotification(input(), dependencies)).resolves.toEqual({ outcome: "sent" })+ expect(createProviderToken).toHaveBeenCalledTimes(2)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect((fetchMock.mock.calls[0]![1]?.headers as Record<string, string>).authorization)+ .toBe("bearer recovered-token")+ })++ it("isolates an A signing failure from a concurrent successful B authority", async () => {+ const signingA = deferred<string>()+ const signingB = deferred<string>()+ let aAttempts = 0+ const createProviderToken = vi.fn((config) => {+ if (config.keyId === "key-a") {+ aAttempts += 1+ return aAttempts === 1 ? signingA.promise : Promise.resolve("token-a-recovered")+ }+ return signingB.promise+ })+ const getProviderToken = createApnsProviderTokenProvider({+ createFingerprint: async (config) => config.keyId,+ createProviderToken,+ })+ const configA = { ...input().config, keyId: "key-a" }+ const configB = { ...input().config, keyId: "key-b" }++ const firstA = getProviderToken(configA)+ const firstB = getProviderToken(configB)+ await vi.waitFor(() => expect(createProviderToken).toHaveBeenCalledTimes(2))+ signingA.reject(new Error("A signing failed"))+ signingB.resolve("token-b")++ await expect(firstA).rejects.toThrow("A signing failed")+ await expect(firstB).resolves.toBe("token-b")+ await expect(getProviderToken(configB)).resolves.toBe("token-b")+ await expect(getProviderToken(configA)).resolves.toBe("token-a-recovered")+ expect(createProviderToken.mock.calls.map(([config]) => config.keyId))+ .toEqual(["key-a", "key-b", "key-a"])+ })++ it("refreshes at 50 minutes with one same-authority signing flight", async () => {+ const issuedAt = 1_700_000_000_000+ let now = issuedAt+ const refresh = deferred<string>()+ const createProviderToken = vi.fn()+ .mockResolvedValueOnce("initial-token")+ .mockImplementationOnce(() => refresh.promise)+ const getProviderToken = createApnsProviderTokenProvider({+ createFingerprint: async (config) => config.keyId,+ createProviderToken,+ now: () => now,+ })+ const config = input().config++ await expect(getProviderToken(config)).resolves.toBe("initial-token")+ now = issuedAt + (50 * 60 * 1000) - 1+ await expect(getProviderToken(config)).resolves.toBe("initial-token")+ expect(createProviderToken).toHaveBeenCalledTimes(1)++ now += 1+ const refreshes = [+ getProviderToken(config),+ getProviderToken(config),+ getProviderToken(config),+ ]+ await vi.waitFor(() => expect(createProviderToken).toHaveBeenCalledTimes(2))+ refresh.resolve("refreshed-token")+ await expect(Promise.all(refreshes)).resolves.toEqual([+ "refreshed-token",+ "refreshed-token",+ "refreshed-token",+ ])+ expect(createProviderToken).toHaveBeenCalledTimes(2)+ })++ it("falls back after refresh failure only while the prior token is under 60 minutes", async () => {+ const issuedAt = 1_700_000_000_000+ let now = issuedAt+ const createProviderToken = vi.fn()+ .mockResolvedValueOnce("initial-token")+ .mockRejectedValueOnce(new Error("refresh failed before expiry"))+ .mockRejectedValueOnce(new Error("refresh failed at expiry"))+ const getProviderToken = createApnsProviderTokenProvider({+ createFingerprint: async (config) => config.keyId,+ createProviderToken,+ now: () => now,+ })++ await expect(getProviderToken(input().config)).resolves.toBe("initial-token")+ now = issuedAt + (60 * 60 * 1000) - 1+ await expect(Promise.all([+ getProviderToken(input().config),+ getProviderToken(input().config),+ ])).resolves.toEqual(["initial-token", "initial-token"])++ now += 1+ await expect(getProviderToken(input().config)).rejects.toThrow("refresh failed at expiry")+ expect(createProviderToken).toHaveBeenCalledTimes(3)+ })++ it("does not fall back when a pending refresh crosses the 60-minute boundary", async () => {+ const issuedAt = 1_700_000_000_000+ let now = issuedAt+ const refresh = deferred<string>()+ const createProviderToken = vi.fn()+ .mockResolvedValueOnce("initial-token")+ .mockImplementationOnce(() => refresh.promise)+ const getProviderToken = createApnsProviderTokenProvider({+ createFingerprint: async (config) => config.keyId,+ createProviderToken,+ now: () => now,+ })++ await getProviderToken(input().config)+ now = issuedAt + (60 * 60 * 1000) - 1+ const refreshing = getProviderToken(input().config)+ await vi.waitFor(() => expect(createProviderToken).toHaveBeenCalledTimes(2))+ now += 1+ refresh.reject(new Error("late refresh failure"))++ await expect(refreshing).rejects.toThrow("late refresh failure")+ })++ it("never evicts valid authorities under cache-capacity pressure", async () => {+ const issuedAt = 1_700_000_000_000+ let now = issuedAt+ const createProviderToken = vi.fn(async (config) => `token-${config.keyId}`)+ const getProviderToken = createApnsProviderTokenProvider({+ createFingerprint: async (config) => config.keyId,+ createProviderToken,+ now: () => now,+ })+ const configs = Array.from({ length: 8 }, (_, index) => ({+ ...input().config,+ keyId: `key-${index}`,+ }))++ await Promise.all(configs.map(getProviderToken))+ now += (50 * 60 * 1000) - 1+ await expect(Promise.all(configs.map(getProviderToken))).resolves.toEqual(+ configs.map((config) => `token-${config.keyId}`),+ )+ expect(createProviderToken).toHaveBeenCalledTimes(configs.length)+ })++ it("never evicts in-flight authorities under capacity pressure", async () => {+ const signingByKey = new Map<string, ReturnType<typeof deferred<string>>>()+ const createProviderToken = vi.fn((config) => {+ const signing = deferred<string>()+ signingByKey.set(config.keyId, signing)+ return signing.promise+ })+ const getProviderToken = createApnsProviderTokenProvider({+ createFingerprint: async (config) => config.keyId,+ createProviderToken,+ })+ const configs = Array.from({ length: 8 }, (_, index) => ({+ ...input().config,+ keyId: `key-${index}`,+ }))+ const calls = [+ ...configs.map(getProviderToken),+ ...configs.map(getProviderToken),+ ]+ const settled = Promise.all(calls)+ await vi.waitFor(() => expect(createProviderToken).toHaveBeenCalledTimes(configs.length))++ for (const config of configs) {+ signingByKey.get(config.keyId)!.resolve(`token-${config.keyId}`)+ }++ await expect(settled).resolves.toEqual([+ ...configs.map((config) => `token-${config.keyId}`),+ ...configs.map((config) => `token-${config.keyId}`),+ ])+ expect(createProviderToken).toHaveBeenCalledTimes(configs.length)+ })++ it("treats clock rollback as zero age instead of signing early", async () => {+ const issuedAt = 1_700_000_000_000+ let now = issuedAt+ const createProviderToken = vi.fn(async () => "initial-token")+ const getProviderToken = createApnsProviderTokenProvider({+ createFingerprint: async (config) => config.keyId,+ createProviderToken,+ now: () => now,+ })++ await expect(getProviderToken(input().config)).resolves.toBe("initial-token")+ now -= 5 * 60 * 1000+ await expect(getProviderToken(input().config)).resolves.toBe("initial-token")+ expect(createProviderToken).toHaveBeenCalledTimes(1)+ })++ it("keys authority by credentials but not by topic", async () => {+ const createProviderToken = vi.fn(async (config) => (+ `token-${config.teamId}-${config.keyId}-${config.privateKey}`+ ))+ const getProviderToken = createApnsProviderTokenProvider({ createProviderToken })+ const base = input().config+ const differentTopic = { ...base, topic: "app.other" }+ const escapedNewlines = { ...base, privateKey: base.privateKey.replace(/\n/gu, "\\n") }+ const differentPrivateKey = {+ ...base,+ privateKey: "-----BEGIN PRIVATE KEY-----\nb3RoZXI=\n-----END PRIVATE KEY-----",+ }++ const tokens = await Promise.all([+ getProviderToken(base),+ getProviderToken(differentTopic),+ getProviderToken(escapedNewlines),+ getProviderToken({ ...base, teamId: "team-other" }),+ getProviderToken({ ...base, keyId: "key-other" }),+ getProviderToken(differentPrivateKey),+ ])++ expect(tokens[0]).toBe(tokens[1])+ expect(tokens[0]).toBe(tokens[2])+ expect(new Set(tokens).size).toBe(4)+ expect(createProviderToken).toHaveBeenCalledTimes(4)+ })++ it("preserves authority ownership across bounded A-B settlement permutations", async () => {+ const settlementOrders = [+ ["key-a", "key-b"],+ ["key-b", "key-a"],+ ] as const+ const failureSets: readonly (readonly string[])[] = [+ [],+ ["key-a"],+ ["key-b"],+ ["key-a", "key-b"],+ ]++ for (const settlementOrder of settlementOrders) {+ for (const failureKeys of failureSets) {+ const signingByKey = new Map([+ ["key-a", deferred<string>()],+ ["key-b", deferred<string>()],+ ])+ const createProviderToken = vi.fn((config) => signingByKey.get(config.keyId)!.promise)+ const getProviderToken = createApnsProviderTokenProvider({+ createFingerprint: async (config) => config.keyId,+ createProviderToken,+ })+ const configA = { ...input().config, keyId: "key-a" }+ const configB = { ...input().config, keyId: "key-b" }+ const requestedKeys = ["key-a", "key-b", "key-a", "key-b"] as const+ const calls = [+ getProviderToken(configA),+ getProviderToken(configB),+ getProviderToken(configA),+ getProviderToken(configB),+ ]+ const settled = Promise.allSettled(calls)+ await vi.waitFor(() => expect(createProviderToken).toHaveBeenCalledTimes(2))++ for (const key of settlementOrder) {+ const signing = signingByKey.get(key)!+ if (failureKeys.includes(key)) signing.reject(new Error(`${key} failed`))+ else signing.resolve(`token-${key}`)+ }++ const results = await settled+ for (const [index, result] of results.entries()) {+ const key = requestedKeys[index]!+ if (failureKeys.includes(key)) {+ expect(result.status).toBe("rejected")+ } else {+ expect(result).toEqual({ status: "fulfilled", value: `token-${key}` })+ }+ }+ expect(createProviderToken.mock.calls.map(([config]) => config.keyId).sort())+ .toEqual(["key-a", "key-b"])+ }+ }+ })+})diff --git a/src/queue-worker/src/providers/apns.ts b/src/queue-worker/src/providers/apns.tsnew file mode 100644index 000000000..c35f22a5e--- /dev/null+++ b/src/queue-worker/src/providers/apns.ts@@ -0,0 +1,262 @@+import type { PushNotificationPayload } from "../notification-payload"++interface ApnsConfig {+ teamId: string+ keyId: string+ privateKey: string+ topic: string+}++type ApnsTokenConfig = Pick<ApnsConfig, "teamId" | "keyId" | "privateKey">++const APNS_PROVIDER_TOKEN_REFRESH_INTERVAL_MS = 50 * 60 * 1000+const APNS_PROVIDER_TOKEN_EXPIRATION_INTERVAL_MS = 60 * 60 * 1000++export interface ApnsSendInput {+ providerToken: string+ providerEnvironment: "sandbox" | "production"+ payload: PushNotificationPayload+ config: ApnsConfig+}++export type PushProviderResult = { outcome: "sent" | "invalid-token" }++export class PushProviderError extends Error {+ constructor(+ readonly provider: "apns" | "fcm",+ readonly status: number,+ readonly reason: string,+ ) {+ super(`${provider} request failed (${status}:${reason})`)+ this.name = "PushProviderError"+ }+}++function base64Url(value: string | ArrayBuffer | Uint8Array): string {+ const bytes = typeof value === "string"+ ? new TextEncoder().encode(value)+ : value instanceof Uint8Array ? value : new Uint8Array(value)+ let binary = ""+ for (const byte of bytes) binary += String.fromCharCode(byte)+ return btoa(binary).replace(/=/gu, "").replace(/\+/gu, "-").replace(/\//gu, "_")+}++function pemToBytes(value: string): Uint8Array {+ const normalized = value.replace(/\\n/gu, "\n")+ const encoded = normalized+ .replace(/-----BEGIN PRIVATE KEY-----/gu, "")+ .replace(/-----END PRIVATE KEY-----/gu, "")+ .replace(/\s+/gu, "")+ const binary = atob(encoded)+ return Uint8Array.from(binary, (character) => character.charCodeAt(0))+}++async function createApnsProviderToken(+ config: ApnsTokenConfig,+ now: number,+): Promise<string> {+ const header = base64Url(JSON.stringify({ alg: "ES256", kid: config.keyId }))+ const claims = base64Url(JSON.stringify({+ iss: config.teamId,+ iat: Math.floor(now / 1000),+ }))+ const signingInput = `${header}.${claims}`+ const key = await crypto.subtle.importKey(+ "pkcs8",+ pemToBytes(config.privateKey),+ { name: "ECDSA", namedCurve: "P-256" },+ false,+ ["sign"],+ )+ const signature = await crypto.subtle.sign(+ { name: "ECDSA", hash: "SHA-256" },+ key,+ new TextEncoder().encode(signingInput),+ )+ return `${signingInput}.${base64Url(signature)}`+}++async function createCredentialFingerprint(config: ApnsTokenConfig): Promise<string> {+ const encoded = new TextEncoder().encode(JSON.stringify([+ config.teamId,+ config.keyId,+ base64Url(pemToBytes(config.privateKey)),+ ]))+ return base64Url(await crypto.subtle.digest("SHA-256", encoded))+}++type ApnsProviderTokenDependencies = {+ createProviderToken: typeof createApnsProviderToken+ createFingerprint: typeof createCredentialFingerprint+ now: () => number+}++type CachedApnsProviderToken = {+ issuedAtEpochMs: number+ token: string+}++type ApnsProviderTokenFlight = {+ promise: Promise<CachedApnsProviderToken>+ startedAtEpochMs: number+}++type ApnsProviderTokenEntry = {+ cached?: CachedApnsProviderToken+ inFlight?: ApnsProviderTokenFlight+}++function providerTokenAge(now: number, issuedAtEpochMs: number): number {+ return Math.max(0, now - issuedAtEpochMs)+}++/**+ * Keep one entry per signing authority in the isolate. Valid or in-flight+ * entries are never evicted: APNs rejects tokens updated too frequently and+ * tokens older than one hour, so capacity pressure cannot override identity+ * or time ownership. Refreshing at 50 minutes leaves margin before expiry.+ */+export function createApnsProviderTokenProvider(+ overrides: Partial<ApnsProviderTokenDependencies> = {},+): (config: ApnsTokenConfig) => Promise<string> {+ const dependencies: ApnsProviderTokenDependencies = {+ createProviderToken: createApnsProviderToken,+ createFingerprint: createCredentialFingerprint,+ now: Date.now,+ ...overrides,+ }+ const entryByCredential = new Map<string, ApnsProviderTokenEntry>()++ function pruneExpiredEntries(now: number): void {+ for (const [credentialFingerprint, entry] of entryByCredential) {+ if (entry.inFlight) continue+ if (+ !entry.cached+ || providerTokenAge(now, entry.cached.issuedAtEpochMs)+ >= APNS_PROVIDER_TOKEN_EXPIRATION_INTERVAL_MS+ ) {+ entryByCredential.delete(credentialFingerprint)+ }+ }+ }++ async function settleFlight(+ credentialFingerprint: string,+ entry: ApnsProviderTokenEntry,+ flight: ApnsProviderTokenFlight,+ ): Promise<string> {+ try {+ const signed = await flight.promise+ if (entryByCredential.get(credentialFingerprint) === entry && entry.inFlight === flight) {+ entry.cached = signed+ entry.inFlight = undefined+ }+ return signed.token+ } catch (error) {+ if (entryByCredential.get(credentialFingerprint) === entry && entry.inFlight === flight) {+ entry.inFlight = undefined+ }+ const entryIsCurrent = entryByCredential.get(credentialFingerprint) === entry+ const fallback = entryIsCurrent ? entry.cached : undefined+ if (+ fallback+ && providerTokenAge(dependencies.now(), fallback.issuedAtEpochMs)+ < APNS_PROVIDER_TOKEN_EXPIRATION_INTERVAL_MS+ ) {+ return fallback.token+ }+ if (entryIsCurrent && !entry.inFlight) {+ entry.cached = undefined+ entryByCredential.delete(credentialFingerprint)+ }+ throw error+ }+ }++ return async (config) => {+ const credentialFingerprint = await dependencies.createFingerprint(config)+ const now = dependencies.now()+ pruneExpiredEntries(now)+ let entry = entryByCredential.get(credentialFingerprint)+ if (!entry) {+ entry = {}+ entryByCredential.set(credentialFingerprint, entry)+ }+ const cached = entry.cached+ if (entry.inFlight) {+ return settleFlight(credentialFingerprint, entry, entry.inFlight)+ }+ if (cached) {+ const age = providerTokenAge(now, cached.issuedAtEpochMs)+ if (age < APNS_PROVIDER_TOKEN_REFRESH_INTERVAL_MS) {+ return cached.token+ }+ }++ const issuedAtEpochMs = Math.floor(now / 1000) * 1000+ const flight: ApnsProviderTokenFlight = {+ promise: Promise.resolve()+ .then(() => dependencies.createProviderToken(config, issuedAtEpochMs))+ .then((token) => ({ issuedAtEpochMs, token })),+ startedAtEpochMs: now,+ }+ entry.inFlight = flight+ return settleFlight(credentialFingerprint, entry, flight)+ }+}++const getApnsProviderToken = createApnsProviderTokenProvider()++type ApnsDependencies = {+ fetch: typeof fetch+ getProviderToken: typeof getApnsProviderToken+}++const defaultDependencies: ApnsDependencies = {+ fetch,+ getProviderToken: getApnsProviderToken,+}++export async function sendApnsNotification(+ input: ApnsSendInput,+ dependencies: ApnsDependencies = defaultDependencies,+): Promise<PushProviderResult> {+ const authorization = await dependencies.getProviderToken(input.config)+ const host = input.providerEnvironment === "sandbox"+ ? "https://api.sandbox.push.apple.com"+ : "https://api.push.apple.com"+ const response = await dependencies.fetch(+ `${host}/3/device/${encodeURIComponent(input.providerToken)}`,+ {+ method: "POST",+ headers: {+ authorization: `bearer ${authorization}`,+ "content-type": "application/json",+ "apns-topic": input.config.topic,+ "apns-push-type": "alert",+ "apns-priority": "10",+ "apns-id": input.payload.notificationId,+ "apns-collapse-id": input.payload.notificationId,+ },+ body: JSON.stringify({+ aps: {+ alert: {+ title: input.payload.title,+ body: input.payload.body,+ },+ sound: "default",+ "thread-id": input.payload.route.targetId,+ },+ ...input.payload.route,+ }),+ },+ )+ if (response.ok) return { outcome: "sent" }++ const body = await response.json().catch(() => null) as { reason?: unknown } | null+ const reason = typeof body?.reason === "string" ? body.reason : "unknown"+ if (["BadDeviceToken", "DeviceTokenNotForTopic", "Unregistered"].includes(reason)) {+ return { outcome: "invalid-token" }+ }+ throw new PushProviderError("apns", response.status, reason)+}diff --git a/src/queue-worker/src/providers/fcm.test.ts b/src/queue-worker/src/providers/fcm.test.tsnew file mode 100644index 000000000..543c53c5c--- /dev/null+++ b/src/queue-worker/src/providers/fcm.test.ts@@ -0,0 +1,190 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import { createFcmAccessToken, sendFcmNotification } from "./fcm"++const payload = {+ notificationId: "4cb8126e-4842-5c26-8d3f-02031c3d014b",+ title: "Alice",+ body: "Hello",+ route: {+ notificationId: "4cb8126e-4842-5c26-8d3f-02031c3d014b",+ messageId: "message-1",+ targetId: "channel-1",+ },+}++async function createRsaPrivateKeyPem(): Promise<string> {+ const keyPair = await crypto.subtle.generateKey({+ name: "RSASSA-PKCS1-v1_5",+ modulusLength: 2048,+ publicExponent: new Uint8Array([1, 0, 1]),+ hash: "SHA-256",+ }, true, ["sign", "verify"]) as CryptoKeyPair+ const privateKey = await crypto.subtle.exportKey("pkcs8", keyPair.privateKey)+ const encoded = Buffer.from(privateKey).toString("base64")+ const lines = encoded.match(/.{1,64}/gu) ?? []+ return `-----BEGIN PRIVATE KEY-----\n${lines.join("\n")}\n-----END PRIVATE KEY-----`+}++describe("FCM HTTP v1 adapter", () => {+ afterEach(() => vi.unstubAllGlobals())++ it("signs a real service-account JWT and uses the default fetch dependency", async () => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ Response.json({ access_token: "access-token" })+ ))+ vi.stubGlobal("fetch", fetchMock)+ const before = Math.floor(Date.now() / 1000)++ await expect(createFcmAccessToken({+ projectId: "test-project",+ clientEmail: "[email protected]",+ privateKey: await createRsaPrivateKeyPem(),+ })).resolves.toBe("access-token")++ const [, init] = fetchMock.mock.calls[0]!+ const assertion = new URLSearchParams(String(init?.body)).get("assertion")!+ const [headerPart, claimsPart, signaturePart] = assertion.split(".")+ expect(JSON.parse(Buffer.from(headerPart!, "base64url").toString())).toEqual({+ alg: "RS256",+ typ: "JWT",+ })+ expect(JSON.parse(Buffer.from(claimsPart!, "base64url").toString())).toMatchObject({+ iss: "[email protected]",+ scope: "https://www.googleapis.com/auth/firebase.messaging",+ aud: "https://oauth2.googleapis.com/token",+ iat: expect.any(Number),+ exp: expect.any(Number),+ })+ const claims = JSON.parse(Buffer.from(claimsPart!, "base64url").toString()) as {+ exp: number+ iat: number+ }+ expect(claims.iat).toBeGreaterThanOrEqual(before)+ expect(claims.exp).toBe(claims.iat + 3600)+ expect(signaturePart).not.toBe("")+ })++ it("exchanges a service-account assertion for a short-lived access token", async () => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ Response.json({ access_token: "access-token" })+ ))+ const token = await createFcmAccessToken({+ projectId: "test-project",+ clientEmail: "[email protected]",+ privateKey: "test-private-key",+ }, {+ fetch: fetchMock as typeof fetch,+ createAssertion: vi.fn(async () => "signed-assertion"),+ })++ expect(token).toBe("access-token")+ const [url, init] = fetchMock.mock.calls[0]!+ expect(url).toBe("https://oauth2.googleapis.com/token")+ expect(String(init?.body)).toContain("assertion=signed-assertion")+ expect(String(init?.body)).toContain("grant_type=")+ })++ it("rejects a failed OAuth exchange without an access token", async () => {+ await expect(createFcmAccessToken({+ projectId: "test-project",+ clientEmail: "[email protected]",+ privateKey: "unused",+ }, {+ fetch: vi.fn(async () => new Response("not json", { status: 503 })) as typeof fetch,+ createAssertion: vi.fn(async () => "signed-assertion"),+ })).rejects.toMatchObject({ provider: "fcm", status: 503, reason: "oauth" })+ })++ it("sends notification/data payloads with deterministic collapse semantics", async () => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ Response.json({ name: "accepted" })+ ))++ await expect(sendFcmNotification({+ providerToken: "provider-token",+ accessToken: "access-token",+ payload,+ config: { projectId: "test-project" },+ }, fetchMock as typeof fetch)).resolves.toEqual({ outcome: "sent" })++ const [url, init] = fetchMock.mock.calls[0]!+ expect(url).toBe("https://fcm.googleapis.com/v1/projects/test-project/messages:send")+ expect(init?.headers).toMatchObject({ authorization: "Bearer access-token" })+ expect(JSON.parse(init?.body as string)).toEqual({+ message: {+ token: "provider-token",+ notification: { title: "Alice", body: "Hello" },+ data: payload.route,+ android: {+ collapse_key: payload.notificationId,+ notification: { tag: payload.notificationId, sound: "default" },+ },+ },+ })+ })++ it("uses the default fetch dependency for notification sends", async () => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ Response.json({ name: "accepted" })+ ))+ vi.stubGlobal("fetch", fetchMock)++ await expect(sendFcmNotification({+ providerToken: "provider-token",+ accessToken: "access-token",+ payload,+ config: { projectId: "test-project" },+ })).resolves.toEqual({ outcome: "sent" })++ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it.each([+ [404, "NOT_FOUND", "UNREGISTERED"],+ [400, "INVALID_ARGUMENT", "INVALID_ARGUMENT"],+ ])("classifies %s/%s as an invalid registration", async (status, outerStatus, errorCode) => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ Response.json({+ error: {+ status: outerStatus,+ details: [{ "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError", errorCode }],+ },+ }, { status })+ ))+ await expect(sendFcmNotification({+ providerToken: "provider-token",+ accessToken: "access-token",+ payload,+ config: { projectId: "test-project" },+ }, fetchMock as typeof fetch)).resolves.toEqual({ outcome: "invalid-token" })+ })++ it("throws a token-free provider error for non-registration failures", async () => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (+ Response.json({ error: { status: "UNAVAILABLE" } }, { status: 503 })+ ))+ const result = sendFcmNotification({+ providerToken: "provider-token",+ accessToken: "access-token",+ payload,+ config: { projectId: "test-project" },+ }, fetchMock as typeof fetch)+ await expect(result).rejects.toMatchObject({ provider: "fcm", status: 503, reason: "UNAVAILABLE" })+ await expect(result).rejects.not.toThrow(/provider-token|Hello/)+ })++ it("uses an unknown reason for a malformed provider error", async () => {+ const fetchMock = vi.fn(async () => new Response("not json", { status: 418 }))++ await expect(sendFcmNotification({+ providerToken: "provider-token",+ accessToken: "access-token",+ payload,+ config: { projectId: "test-project" },+ }, fetchMock as typeof fetch)).rejects.toMatchObject({+ provider: "fcm",+ status: 418,+ reason: "unknown",+ })+ })+})diff --git a/src/queue-worker/src/providers/fcm.ts b/src/queue-worker/src/providers/fcm.tsnew file mode 100644index 000000000..e4387391b--- /dev/null+++ b/src/queue-worker/src/providers/fcm.ts@@ -0,0 +1,145 @@+import type { PushNotificationPayload } from "../notification-payload"+import { PushProviderError, type PushProviderResult } from "./apns"++export interface FcmConfig {+ projectId: string+ clientEmail: string+ privateKey: string+}++function base64Url(value: string | ArrayBuffer): string {+ const bytes = typeof value === "string"+ ? new TextEncoder().encode(value)+ : new Uint8Array(value)+ let binary = ""+ for (const byte of bytes) binary += String.fromCharCode(byte)+ return btoa(binary).replace(/=/gu, "").replace(/\+/gu, "-").replace(/\//gu, "_")+}++function pemToBytes(value: string): Uint8Array {+ const normalized = value.replace(/\\n/gu, "\n")+ const encoded = normalized+ .replace(/-----BEGIN PRIVATE KEY-----/gu, "")+ .replace(/-----END PRIVATE KEY-----/gu, "")+ .replace(/\s+/gu, "")+ const binary = atob(encoded)+ return Uint8Array.from(binary, (character) => character.charCodeAt(0))+}++async function createFcmServiceAccountAssertion(+ config: Pick<FcmConfig, "clientEmail" | "privateKey">,+ now = Date.now(),+): Promise<string> {+ const header = base64Url(JSON.stringify({ alg: "RS256", typ: "JWT" }))+ const issuedAt = Math.floor(now / 1000)+ const claims = base64Url(JSON.stringify({+ iss: config.clientEmail,+ scope: "https://www.googleapis.com/auth/firebase.messaging",+ aud: "https://oauth2.googleapis.com/token",+ iat: issuedAt,+ exp: issuedAt + 3600,+ }))+ const signingInput = `${header}.${claims}`+ const key = await crypto.subtle.importKey(+ "pkcs8",+ pemToBytes(config.privateKey),+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },+ false,+ ["sign"],+ )+ const signature = await crypto.subtle.sign(+ "RSASSA-PKCS1-v1_5",+ key,+ new TextEncoder().encode(signingInput),+ )+ return `${signingInput}.${base64Url(signature)}`+}++type FcmTokenDependencies = {+ fetch: typeof fetch+ createAssertion: typeof createFcmServiceAccountAssertion+}++export async function createFcmAccessToken(+ config: FcmConfig,+ dependencies: FcmTokenDependencies = {+ fetch,+ createAssertion: createFcmServiceAccountAssertion,+ },+): Promise<string> {+ const assertion = await dependencies.createAssertion(config)+ const response = await dependencies.fetch("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,+ }),+ })+ const body = await response.json().catch(() => null) as { access_token?: unknown } | null+ if (!response.ok || typeof body?.access_token !== "string" || !body.access_token) {+ throw new PushProviderError("fcm", response.status, "oauth")+ }+ return body.access_token+}++export async function sendFcmNotification(+ input: {+ providerToken: string+ accessToken: string+ payload: PushNotificationPayload+ config: Pick<FcmConfig, "projectId">+ },+ fetchImpl: typeof fetch = fetch,+): Promise<PushProviderResult> {+ const response = await fetchImpl(+ `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(input.config.projectId)}/messages:send`,+ {+ method: "POST",+ headers: {+ authorization: `Bearer ${input.accessToken}`,+ "content-type": "application/json",+ },+ body: JSON.stringify({+ message: {+ token: input.providerToken,+ notification: {+ title: input.payload.title,+ body: input.payload.body,+ },+ data: input.payload.route,+ android: {+ collapse_key: input.payload.notificationId,+ notification: {+ tag: input.payload.notificationId,+ sound: "default",+ },+ },+ },+ }),+ },+ )+ if (response.ok) return { outcome: "sent" }++ const body = await response.json().catch(() => null) as {+ error?: {+ status?: unknown+ details?: Array<{ errorCode?: unknown }>+ }+ } | null+ const fcmErrorCode = body?.error?.details?.find(+ (detail) => typeof detail?.errorCode === "string",+ )?.errorCode+ const reason = typeof fcmErrorCode === "string"+ ? fcmErrorCode+ : typeof body?.error?.status === "string"+ ? body.error.status+ : "unknown"+ if (+ (response.status === 404 && reason === "UNREGISTERED")+ || (response.status === 400 && reason === "INVALID_ARGUMENT")+ ) {+ return { outcome: "invalid-token" }+ }+ throw new PushProviderError("fcm", response.status, reason)+}diff --git a/src/queue-worker/src/task-handler.test.ts b/src/queue-worker/src/task-handler.test.tsnew file mode 100644index 000000000..009487a3f--- /dev/null+++ b/src/queue-worker/src/task-handler.test.ts@@ -0,0 +1,96 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const { mockLogInfo, mockLogWarn } = vi.hoisted(() => ({+ mockLogInfo: vi.fn(),+ mockLogWarn: vi.fn(),+}))+vi.mock("@alook/shared", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@alook/shared")>()+ return {+ ...actual,+ createLogger: () => ({+ debug: vi.fn(),+ info: mockLogInfo,+ warn: mockLogWarn,+ error: vi.fn(),+ child() { return this },+ }),+ }+})++import { executeQueueTask } from "./task-handler"++describe("queue task handler", () => {+ beforeEach(() => vi.clearAllMocks())++ it("preserves bot-wake dispatch semantics and lets transient failures throw", async () => {+ const dispatchWake = vi.fn(async () => ({ outcome: "attempted" as const }))+ const task = {+ version: 1 as const,+ kind: "bot-wake" as const,+ messageId: "message-1",+ botUserId: "bot-1",+ }+ await executeQueueTask({} as never, {} as Env, task, {+ dispatchWake,+ processMobilePush: vi.fn(),+ })+ expect(dispatchWake).toHaveBeenCalledWith({}, {}, {+ messageId: "message-1",+ botUserId: "bot-1",+ })++ dispatchWake.mockRejectedValueOnce(new Error("D1 unavailable"))+ await expect(executeQueueTask({} as never, {} as Env, task, {+ dispatchWake,+ processMobilePush: vi.fn(),+ })).rejects.toThrow("D1 unavailable")+ })++ it("logs a bot wake that reached a machine with no active session", async () => {+ const dispatchWake = vi.fn(async () => ({+ outcome: "attempted_nowhere" as const,+ machineId: "machine-1",+ }))+ const task = {+ version: 1 as const,+ kind: "bot-wake" as const,+ messageId: "message-1",+ botUserId: "bot-1",+ }++ await executeQueueTask({} as never, {} as Env, task, {+ dispatchWake,+ processMobilePush: vi.fn(),+ })++ expect(mockLogInfo).toHaveBeenCalledWith("bot_wake_attempted_nowhere", {+ kind: "bot-wake",+ botUserId: "bot-1",+ machineId: "machine-1",+ })+ })++ it("catches mobile processing failures so the consumer can ACK", async () => {+ const processPush = vi.fn(async () => {+ throw new Error("provider unavailable")+ })+ const task = {+ version: 1 as const,+ kind: "mobile-push" as const,+ messageId: "message-1",+ userId: "user-1",+ }++ await expect(executeQueueTask({} as never, {} as Env, task, {+ dispatchWake: vi.fn(),+ processMobilePush: processPush,+ })).resolves.toBeUndefined()+ expect(mockLogWarn).toHaveBeenCalledWith("mobile_push_task_failed", {+ kind: "mobile-push",+ messageId: "message-1",+ userId: "user-1",+ errorName: "Error",+ })+ })+})diff --git a/src/queue-worker/src/task-handler.ts b/src/queue-worker/src/task-handler.tsnew file mode 100644index 000000000..543c9e86e--- /dev/null+++ b/src/queue-worker/src/task-handler.ts@@ -0,0 +1,63 @@+import {+ createLogger,+ dispatchOneUnreadWake,+ type AlookQueueTask,+ type Database,+} from "@alook/shared"+import { processMobilePush } from "./mobile-push"++const log = createLogger({ service: "queue-worker-task-handler" })++type TaskHandlerDependencies = {+ dispatchWake: typeof dispatchOneUnreadWake+ processMobilePush: typeof processMobilePush+}++const defaultDependencies: TaskHandlerDependencies = {+ dispatchWake: dispatchOneUnreadWake,+ processMobilePush,+}++export async function executeQueueTask(+ db: Database,+ env: Env,+ task: AlookQueueTask,+ dependencies: TaskHandlerDependencies = defaultDependencies,+): Promise<void> {+ if (task.kind === "bot-wake") {+ const payload = { messageId: task.messageId, botUserId: task.botUserId }+ const result = await dependencies.dispatchWake(db, env, payload)+ if (result.outcome === "skip") {+ log.info("bot_wake_skipped", {+ kind: task.kind,+ botUserId: task.botUserId,+ messageId: task.messageId,+ reason: result.reason,+ })+ } else if (result.outcome === "attempted_nowhere") {+ log.info("bot_wake_attempted_nowhere", {+ kind: task.kind,+ botUserId: task.botUserId,+ machineId: result.machineId,+ })+ }+ return+ }++ try {+ const result = await dependencies.processMobilePush(db, env, task)+ log.info("mobile_push_task_complete", {+ kind: task.kind,+ messageId: task.messageId,+ userId: task.userId,+ ...result,+ })+ } catch (error) {+ log.warn("mobile_push_task_failed", {+ kind: task.kind,+ messageId: task.messageId,+ userId: task.userId,+ errorName: error instanceof Error ? error.name : "unknown",+ })+ }+}diff --git a/src/wake-worker/test-runtime/apply-migrations.ts b/src/queue-worker/test-runtime/apply-migrations.tssimilarity index 100%rename from src/wake-worker/test-runtime/apply-migrations.tsrename to src/queue-worker/test-runtime/apply-migrations.tsdiff --git a/src/queue-worker/test-runtime/worker.runtime.test.ts b/src/queue-worker/test-runtime/worker.runtime.test.tsnew file mode 100644index 000000000..8b4350a0f--- /dev/null+++ b/src/queue-worker/test-runtime/worker.runtime.test.ts@@ -0,0 +1,137 @@+/// <reference types="@cloudflare/vitest-plugin/types" />++import { env, exports } from "cloudflare:workers"+import { describe, expect, it } from "vitest"++type RuntimeQueueMessage<T> = {+ id: string+ timestamp: Date+ attempts: number+ body: T+}++type RuntimeQueueResult = {+ outcome: string+ explicitAcks: string[]+ retryMessages: Array<{ msgId: string; delaySeconds?: number }>+}++const runtimeEnv = env as unknown as { DB: D1Database }+const worker = (exports as unknown as {+ default: {+ fetch(request: Request): Promise<Response>+ queue(queueName: string, messages: RuntimeQueueMessage<unknown>[]): Promise<RuntimeQueueResult>+ }+}).default++describe("queue-worker workerd runtime", () => {+ it("loads production migrations and serves the production entrypoint", async () => {+ const schema = await runtimeEnv.DB.prepare(+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",+ ).bind("community_message").first<{ name: string }>()+ expect(schema?.name).toBe("community_message")++ const response = await worker.fetch(new Request("https://worker.test/health"))+ expect(response.status).toBe(200)+ await expect(response.json()).resolves.toEqual({ status: "ok" })+ })++ it("rejects invalid JSON and non-POST dev requests at the real entrypoint", async () => {+ const malformed = await worker.fetch(new Request("https://worker.test/", {+ method: "POST",+ body: "not json",+ }))+ expect(malformed.status).toBe(400)++ const method = await worker.fetch(new Request("https://worker.test/"))+ expect(method.status).toBe(405)+ })++ it.each([+ ["legacy", (messageId: string, botUserId: string) => ({ messageId, botUserId })],+ ["v1", (messageId: string, botUserId: string) => ({ version: 1, kind: "bot-wake", messageId, botUserId })],+ ])("acks a permanent D1 miss for a %s task through the real queue entrypoint", async (_name, makeBody) => {+ const id = `runtime-${crypto.randomUUID()}`+ const messageId = `missing-message-${crypto.randomUUID()}`+ const botUserId = `missing-bot-${crypto.randomUUID()}`+ const result = await worker.queue("alook-queue", [{+ id,+ timestamp: new Date(),+ attempts: 1,+ body: makeBody(messageId, botUserId),+ }])++ expect(result.outcome).toBe("ok")+ expect(result.explicitAcks).toContain(id)+ expect(result.retryMessages).toEqual([])+ })++ it("ACKs a mobile-push task when its message no longer exists", async () => {+ const id = `runtime-${crypto.randomUUID()}`+ const result = await worker.queue("alook-queue", [{+ id,+ timestamp: new Date(),+ attempts: 1,+ body: {+ version: 1,+ kind: "mobile-push",+ messageId: `missing-message-${crypto.randomUUID()}`,+ userId: `missing-user-${crypto.randomUUID()}`,+ },+ }])++ expect(result.outcome).toBe("ok")+ expect(result.explicitAcks).toContain(id)+ expect(result.retryMessages).toEqual([])+ })++ it("ACKs caught mobile and poison siblings while retrying only a transient bot failure", async () => {+ const mobileId = `runtime-mobile-${crypto.randomUUID()}`+ const botId = `runtime-bot-${crypto.randomUUID()}`+ const poisonId = `runtime-poison-${crypto.randomUUID()}`+ await runtimeEnv.DB.prepare(+ "ALTER TABLE community_message RENAME TO community_message_unavailable",+ ).run()+ try {+ const result = await worker.queue("alook-queue", [+ {+ id: mobileId,+ timestamp: new Date(),+ attempts: 1,+ body: {+ version: 1,+ kind: "mobile-push",+ messageId: `message-${crypto.randomUUID()}`,+ userId: `user-${crypto.randomUUID()}`,+ },+ },+ {+ id: botId,+ timestamp: new Date(),+ attempts: 1,+ body: {+ version: 1,+ kind: "bot-wake",+ messageId: `message-${crypto.randomUUID()}`,+ botUserId: `bot-${crypto.randomUUID()}`,+ },+ },+ {+ id: poisonId,+ timestamp: new Date(),+ attempts: 1,+ body: { version: 1, kind: "unknown" },+ },+ ])++ expect(result.outcome).toBe("ok")+ expect(result.explicitAcks).toEqual(expect.arrayContaining([mobileId, poisonId]))+ expect(result.explicitAcks).not.toContain(botId)+ expect(result.retryMessages).toContainEqual({ msgId: botId, delaySeconds: 5 })+ } finally {+ await runtimeEnv.DB.prepare(+ "ALTER TABLE community_message_unavailable RENAME TO community_message",+ ).run()+ }+ })+})diff --git a/src/wake-worker/tsconfig.json b/src/queue-worker/tsconfig.jsonsimilarity index 100%rename from src/wake-worker/tsconfig.jsonrename to src/queue-worker/tsconfig.jsondiff --git a/src/wake-worker/vitest.config.ts b/src/queue-worker/vitest.config.tssimilarity index 88%rename from src/wake-worker/vitest.config.tsrename to src/queue-worker/vitest.config.tsindex ba2cf9ee6..056e86db9 100644--- a/src/wake-worker/vitest.config.ts+++ b/src/queue-worker/vitest.config.ts@@ -3,7 +3,7 @@ import shared from "../../vitest.shared"export default mergeConfig(shared, defineConfig({test: {- name: "wake-worker-node",+ name: "queue-worker-node",include: ["src/**/*.test.ts"],sequence: { groupOrder: 1 },},diff --git a/src/wake-worker/vitest.runtime.config.mts b/src/queue-worker/vitest.runtime.config.mtssimilarity index 95%rename from src/wake-worker/vitest.runtime.config.mtsrename to src/queue-worker/vitest.runtime.config.mtsindex 37a5bfc17..5aebb6414 100644--- a/src/wake-worker/vitest.runtime.config.mts+++ b/src/queue-worker/vitest.runtime.config.mts@@ -18,7 +18,7 @@ export default defineProject({}),],test: {- name: "wake-worker-runtime",+ name: "queue-worker-runtime",include: ["test-runtime/**/*.runtime.test.ts"],setupFiles: ["test-runtime/apply-migrations.ts"],sequence: { groupOrder: 12 },diff --git a/src/wake-worker/vitest.workspace.config.ts b/src/queue-worker/vitest.workspace.config.tssimilarity index 100%rename from src/wake-worker/vitest.workspace.config.tsrename to src/queue-worker/vitest.workspace.config.tsdiff --git a/src/wake-worker/wrangler.toml b/src/queue-worker/wrangler.tomlsimilarity index 85%rename from src/wake-worker/wrangler.tomlrename to src/queue-worker/wrangler.tomlindex bc5534a9f..e3f692c01 100644--- a/src/wake-worker/wrangler.toml+++ b/src/queue-worker/wrangler.toml@@ -1,4 +1,4 @@-name = "alook-wake-worker"+name = "alook-queue-worker"main = "src/index.ts"compatibility_date = "2026-09-07"compatibility_flags = ["nodejs_compat"]@@ -18,7 +18,7 @@ enabled = truehead_sampling_rate = 0.05destinations = ["grafana-traces"]-# Must match DEV_PORTS.wakeWorker in src/shared/src/constants.ts+# Must match DEV_PORTS.queueWorker in src/shared/src/constants.ts[dev]port = 8790inspector_port = 9232@@ -37,7 +37,7 @@ database_id = "1593b87c-d8a8-4cdf-b6c0-c80d94442654"database_name = "alook-app"[[queues.consumers]]-queue = "alook-wake"+queue = "alook-queue"max_batch_size = 25max_retries = 3-dead_letter_queue = "alook-wake-dlq"+dead_letter_queue = "alook-queue-dlq"diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex 6bc9ea30a..c9e391245 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -7,7 +7,7 @@** Lifted from `src/daemon/src/server/contract.ts` into `@alook/shared` so the* real server routes (`src/web`) and the wake producer/consumer- * (`src/web`, `src/wake-worker`) can share the exact same types the daemon's+ * (`src/web`, `src/queue-worker`) can share the exact same types the daemon's* CLI and mock server already implement against. `src/daemon`'s* `contract.ts` re-exports everything from here — see that file.*@@ -769,7 +769,7 @@ export type AgentInterruptRequest = z.infer<typeof AgentInterruptRequestSchema>;* never fans out by channel membership.** `agent:wake` is the ONE semantic unread-wake command — "ensure this agent- * handles unread work." The server/wake-worker does not decide whether a+ * handles unread work." The server/queue-worker does not decide whether a* daemon process is already running; that is daemon-owned state. The daemon* decides whether to spawn a fresh process, notify an already-running one, or* coalesce the notice for the next turn (see `AgentProcessManager`).@@ -1145,7 +1145,7 @@ export type WebSocketFactory = (url: string, headers: Record<string, string>) =>* inject messages. `postMessage` writes* the message; real deployments separately enqueue an `agent:wake` for any* bot behind on the new message (see `src/web`'s wake producer +- * `src/wake-worker`'s consumer) — this admin surface does not itself compute+ * `src/queue-worker`'s consumer) — this admin surface does not itself compute* or dispatch control-plane commands.*/export interface AdminApi {diff --git a/src/shared/src/community/queue-task.ts b/src/shared/src/community/queue-task.tsnew file mode 100644index 000000000..c84975504--- /dev/null+++ b/src/shared/src/community/queue-task.ts@@ -0,0 +1,135 @@+export type BotWakeQueueTaskV1 = {+ version: 1+ kind: "bot-wake"+ messageId: string+ botUserId: string+}++export type MobilePushQueueTaskV1 = {+ version: 1+ kind: "mobile-push"+ messageId: string+ userId: string+}++export type AlookQueueTask = BotWakeQueueTaskV1 | MobilePushQueueTaskV1++export type QueueTaskRejectReason =+ | "malformed"+ | "unsupported_version"+ | "unknown_kind"++export type QueueTaskParseResult =+ | { ok: true; source: "legacy" | "v1"; task: AlookQueueTask }+ | { ok: false; reason: QueueTaskRejectReason }++export type QueueTaskBatchParseResult =+ | { ok: true; tasks: AlookQueueTask[] }+ | { ok: false; reason: QueueTaskRejectReason; itemIndex: number | null }++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+}++function hasOwn(value: Record<string, unknown>, key: string): boolean {+ return Object.prototype.hasOwnProperty.call(value, key)+}++function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {+ const actualKeys = Object.keys(value)+ return actualKeys.length === keys.length && keys.every((key) => hasOwn(value, key))+}++function isNonEmptyId(value: unknown): value is string {+ return typeof value === "string" && value.trim().length > 0+}++export function parseQueueTask(value: unknown): QueueTaskParseResult {+ if (!isRecord(value)) return { ok: false, reason: "malformed" }++ const hasDiscriminator = hasOwn(value, "version") || hasOwn(value, "kind")+ if (!hasDiscriminator) {+ if (+ !hasExactKeys(value, ["messageId", "botUserId"])+ || !isNonEmptyId(value.messageId)+ || !isNonEmptyId(value.botUserId)+ ) {+ return { ok: false, reason: "malformed" }+ }++ return {+ ok: true,+ source: "legacy",+ task: {+ version: 1,+ kind: "bot-wake",+ messageId: value.messageId,+ botUserId: value.botUserId,+ },+ }+ }++ if (!hasOwn(value, "version") || typeof value.version !== "number") {+ return { ok: false, reason: "malformed" }+ }+ if (value.version !== 1) return { ok: false, reason: "unsupported_version" }+ if (!hasOwn(value, "kind") || typeof value.kind !== "string") {+ return { ok: false, reason: "malformed" }+ }++ if (value.kind === "bot-wake") {+ if (+ !hasExactKeys(value, ["version", "kind", "messageId", "botUserId"])+ || !isNonEmptyId(value.messageId)+ || !isNonEmptyId(value.botUserId)+ ) {+ return { ok: false, reason: "malformed" }+ }++ return {+ ok: true,+ source: "v1",+ task: {+ version: 1,+ kind: "bot-wake",+ messageId: value.messageId,+ botUserId: value.botUserId,+ },+ }+ }++ if (value.kind === "mobile-push") {+ if (+ !hasExactKeys(value, ["version", "kind", "messageId", "userId"])+ || !isNonEmptyId(value.messageId)+ || !isNonEmptyId(value.userId)+ ) {+ return { ok: false, reason: "malformed" }+ }+ return {+ ok: true,+ source: "v1",+ task: {+ version: 1,+ kind: "mobile-push",+ messageId: value.messageId,+ userId: value.userId,+ },+ }+ }++ return { ok: false, reason: "unknown_kind" }+}++export function parseQueueTaskBatch(value: unknown): QueueTaskBatchParseResult {+ if (!Array.isArray(value)) return { ok: false, reason: "malformed", itemIndex: null }++ const tasks: AlookQueueTask[] = []+ for (let itemIndex = 0; itemIndex < value.length; itemIndex++) {+ const result = parseQueueTask(value[itemIndex])+ if (!result.ok) return { ok: false, reason: result.reason, itemIndex }+ tasks.push(result.task)+ }++ return { ok: true, tasks }+}diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.tsindex 5460cbc48..0b521fb5c 100644--- a/src/shared/src/community/wake-dispatch.ts+++ b/src/shared/src/community/wake-dispatch.ts@@ -21,7 +21,7 @@ import { parseAttemptedCountReceipt } from "../transport-receipt";* consumers too (`@alook/cli`, `@alook/daemon`), whose tsconfigs don't* include `@cloudflare/workers-types` in `types`. A real `Fetcher` service* binding satisfies this structurally at the two real call sites- * (`src/web`, `src/wake-worker`, both of which DO have workers-types).+ * (`src/web`, `src/queue-worker`, both of which DO have workers-types).*/interface FetcherLike {fetch(input: string, init?: RequestInit): Promise<Response>;@@ -57,11 +57,11 @@ async function unreadWakeLaunchId(input: {}/**- * One `WAKE_QUEUE` message — deliberately minimal (plan+ * One bot-wake queue task — deliberately minimal (plan* minimal-wake-queue-unread-notice §1): just enough to rebuild the wake* command from CURRENT D1 state at consume time. No `machineId`, `runtime`,* `launchId`, message text, sender, or preview — all of that is re-derived- * by `buildUnreadWakeCommand` in `src/wake-worker` so a stale queue item+ * by `buildUnreadWakeCommand` in `src/queue-worker` so a stale queue item* never wakes an old machine or carries stale content. `launchId` is derived* deterministically from the bot/message tuple so retry and reconnect replay* retain one semantic command identity.@@ -73,13 +73,13 @@ export interface WakePayload {/*** Thin wake-dispatch seam. Lives in `src/shared` (not `src/web`) because- * BOTH the `src/web` wake producer AND the `src/wake-worker` queue consumer+ * BOTH the `src/web` queue producer AND the `src/queue-worker` queue consumer* need it, and the consumer has no `@opennextjs/cloudflare` / Next.js* context — this module does a plain `Fetcher.fetch`, nothing* CF-Workers-Next.js-specific.** `env.WS_DO_WORKER` is a service binding to the `alook-ws-do` worker's HTTP- * surface (never a raw DO namespace — `src/web`/`src/wake-worker` cannot+ * surface (never a raw DO namespace — `src/web`/`src/queue-worker` cannot* fetch a DO stub directly). This function POSTs an already-fully-built* `HostCommand` to that worker's `/community-machine/by-id/<machineId>/forward-agent-wake`* route and normalizes the attempted socket-write count to a boolean — it never inspects,@@ -344,10 +344,10 @@ export type DispatchOneWakeResult =/*** The ONE place that decides what happens for a single `{ messageId,* botUserId }` wake candidate: rebuild from current D1 state, and forward if- * `ready`. Every caller — `src/wake-worker`'s real queue consumer AND+ * `ready`. Every caller — `src/queue-worker`'s real queue consumer AND* `src/web`'s dev-only inline stand-in (local Cloudflare Queues can't bridge* separate `wrangler dev`/`next dev` processes, so `next dev` calls this- * directly instead of going through `WAKE_QUEUE`) — calls this SAME function,+ * directly instead of going through the production queue) — calls this SAME function,* so "what a wake candidate resolves to" has exactly one implementation.* Callers own their own retry/ack-vs-log semantics on top; this never* swallows a `buildUnreadWakeCommand`/`sendWakeToMachine` throw (a transientdiff --git a/src/shared/src/constants.ts b/src/shared/src/constants.tsindex 479f34847..6eb071391 100644--- a/src/shared/src/constants.ts+++ b/src/shared/src/constants.ts@@ -202,25 +202,25 @@ export interface DevPortProfile {web: number;emailWorker: number;wsDo: number;- wakeWorker: number;+ queueWorker: number;}// Ports used by `pnpm dev:*` / `wrangler dev` in this monorepo — must match-// each worker's wrangler.toml `[dev] port` (web via Next, wake-worker via-// src/wake-worker/wrangler.toml). Single source of truth for the fallback+// each worker's wrangler.toml `[dev] port` (web via Next, queue-worker via+// src/queue-worker/wrangler.toml). Single source of truth for the fallback// URLs below and every other hardcoded dev-port default across web/cli/daemon.export const DEV_PORTS: DevPortProfile = {web: 3000,emailWorker: 8787,wsDo: 8789,- wakeWorker: 8790,+ queueWorker: 8790,};// Local dev URLs (used for service-binding fallbacks)export const DEV_WEB_URL = process.env.ALOOK_SERVER_URL || `http://localhost:${DEV_PORTS.web}`;export const DEV_WS_DO_URL = process.env.DEV_WS_DO_URL || `http://localhost:${DEV_PORTS.wsDo}`;export const DEV_EMAIL_WORKER_URL = process.env.DEV_EMAIL_WORKER_URL || `http://localhost:${DEV_PORTS.emailWorker}`;-export const DEV_WAKE_WORKER_URL = process.env.DEV_WAKE_WORKER_URL || `http://localhost:${DEV_PORTS.wakeWorker}`;+export const DEV_QUEUE_WORKER_URL = process.env.DEV_QUEUE_WORKER_URL || `http://localhost:${DEV_PORTS.queueWorker}`;/** Local ws-do port — derived from `DEV_WS_DO_URL` so env overrides stay in sync. */export function devWsDoPort(): number {diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex acb39aaec..d28f5017c 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -2,6 +2,7 @@ import {sqliteTable,text,integer,+ check,index,unique,uniqueIndex,@@ -517,6 +518,47 @@ export const communityNotificationSetting = sqliteTable((t) => [index("idx_notification_setting_user").on(t.userId)]);+// One durable row per native app installation. Tokens are encrypted before+// this table boundary; the hash is only a possession check for safe account+// transfer and must never be used as a provider credential.+export const communityPushDevice = sqliteTable(+ "community_push_device",+ {+ id: text("id").primaryKey().$defaultFn(() => "cpd_" + nanoid()),+ userId: text("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ installationId: text("installation_id").notNull(),+ platform: text("platform").notNull(),+ providerEnvironment: text("provider_environment").notNull(),+ providerTokenEncrypted: text("provider_token_encrypted").notNull(),+ providerTokenHash: text("provider_token_hash").notNull(),+ appVersion: text("app_version"),+ lastSeenAt: text("last_seen_at").notNull().$defaultFn(() => new Date().toISOString()),+ disabledAt: text("disabled_at"),+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),+ },+ (t) => [+ unique("uq_push_device_installation").on(t.installationId),+ index("idx_push_device_user_active").on(t.userId, t.disabledAt),+ index("idx_push_device_token_hash").on(t.providerTokenHash),+ check("ck_push_device_platform", sql`${t.platform} in ('ios', 'android')`),+ check(+ "ck_push_device_provider_environment",+ sql`${t.providerEnvironment} in ('sandbox', 'production')`,+ ),+ check(+ "ck_push_device_android_environment",+ sql`${t.platform} = 'ios' or ${t.providerEnvironment} = 'production'`,+ ),+ check(+ "ck_push_device_token_hash",+ sql`length(${t.providerTokenHash}) = 64 and ${t.providerTokenHash} not glob '*[^0-9a-f]*'`,+ ),+ ],+);+// 19. community_bot_approval_request// Represents pending/resolved approval workflows a bot owner sees in the// owner↔bot DM. After migration 0065 the ONLY live `kind` is:diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex 14688eaa1..9eba6e907 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -56,6 +56,8 @@ export * as communityUserProfile from "./queries/community/user-profile";export * as communitySearch from "./queries/community/search";export * as communityNotificationSetting from "./queries/community/notification-setting";export * as communityNotificationEligibility from "./queries/community/notification-eligibility";+export * as communityPushDevice from "./queries/community/push-device";+export * as communityNotificationTarget from "./queries/community/notification-target";export * as communityServerFolder from "./queries/community/server-folder";export * as communityServerRail from "./queries/community/server-rail";export * as communityInbox from "./queries/community/inbox";diff --git a/src/shared/src/db/queries/account-deletion.test.ts b/src/shared/src/db/queries/account-deletion.test.tsindex 40a332c8a..e2ae3de23 100644--- a/src/shared/src/db/queries/account-deletion.test.ts+++ b/src/shared/src/db/queries/account-deletion.test.ts@@ -168,6 +168,12 @@ describe("account deletion snapshot and delete queries", () => {bot, `${bot}@example.com`, `bots/${bot}/avatar`,reader, `${reader}@example.com`, earlyReader, `${earlyReader}@example.com`,)+ run(+ "INSERT INTO community_push_device (id, user_id, installation_id, platform, provider_environment, provider_token_encrypted, provider_token_hash, last_seen_at, created_at, updated_at) VALUES ('owner_device_1', ?, 'owner-installation-1', 'ios', 'sandbox', 'fake-owner-ciphertext-1', ?, ?, ?, ?), ('owner_device_2', ?, 'owner-installation-2', 'android', 'production', 'fake-owner-ciphertext-2', ?, ?, ?, ?), ('reader_device', ?, 'reader-installation', 'ios', 'production', 'fake-reader-ciphertext', ?, ?, ?, ?)",+ owner, "a".repeat(64), now, now, now,+ owner, "b".repeat(64), now, now, now,+ reader, "c".repeat(64), now, now, now,+ )run("UPDATE user SET isBot = 1, ownerUserId = ? WHERE id = ?", owner, bot)run("INSERT INTO account (id, userId, accountId, providerId, accessToken, refreshToken, createdAt, updatedAt) VALUES ('account_1', ?, 'provider_account', 'github', 'access', 'refresh', ?, ?)",@@ -333,6 +339,12 @@ describe("account deletion snapshot and delete queries", () => {"pending_thread_attachment",)).toBeUndefined()expect(sqlite.prepare("SELECT id FROM user WHERE id = ?").get(reader)).toEqual({ id: reader })+ expect(sqlite.prepare(+ "SELECT COUNT(*) AS count FROM community_push_device WHERE user_id = ?",+ ).get(owner)).toEqual({ count: 0 })+ expect(sqlite.prepare(+ "SELECT installation_id FROM community_push_device WHERE user_id = ?",+ ).get(reader)).toEqual({ installation_id: "reader-installation" })expect(sqlite.prepare("SELECT message_count FROM community_channel WHERE id = ?").get(dm)).toEqual({ message_count: 1 })expect(sqlite.prepare("PRAGMA foreign_key_check").all()).toEqual([])})diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.tsindex bc29ef7db..4ce354986 100644--- a/src/shared/src/db/queries/community/bot-audit-log.ts+++ b/src/shared/src/db/queries/community/bot-audit-log.ts@@ -212,10 +212,10 @@ export async function listOwnedBotActivityEvents(/*** Wake-trigger audit write — thin wrapper around- * `insertBotActivityEventAndPrune` for the wake-worker's write path+ * `insertBotActivityEventAndPrune` for the queue-worker's write path* (`buildUnreadWakeCommand`). Serializes the typed `WakeTriggerPayload` into* the existing opaque `payload` text column and runs the same rolling-500- * prune atomically. Distinct entry point so wake-worker callers can't+ * prune atomically. Distinct entry point so queue-worker callers can't* accidentally construct a shape that fails `BotAuditEventSchema` at read* time.*/diff --git a/src/shared/src/db/queries/community/notification-target.ts b/src/shared/src/db/queries/community/notification-target.tsnew file mode 100644index 000000000..89f28a1c3--- /dev/null+++ b/src/shared/src/db/queries/community/notification-target.ts@@ -0,0 +1,48 @@+import { asc, eq } from "drizzle-orm";+import {+ communityAttachment,+ communityMessage,+} from "../../community-schema";+import { user } from "../../schema";+import type { Database } from "../../index";++export interface PushNotificationTarget {+ messageId: string;+ channelId: string;+ authorName: string;+ content: string;+ attachmentContentTypes: Array<string | null>;+}++export async function getPushNotificationTarget(+ db: Database,+ messageId: string,+): Promise<PushNotificationTarget | null> {+ const rows = await db+ .select({+ messageId: communityMessage.id,+ channelId: communityMessage.channelId,+ authorName: user.name,+ content: communityMessage.content,+ })+ .from(communityMessage)+ .innerJoin(user, eq(user.id, communityMessage.authorId))+ .where(eq(communityMessage.id, messageId))+ .limit(1);+ const message = rows[0];+ if (!message) return null;++ const attachments = await db+ .select({ contentType: communityAttachment.contentType })+ .from(communityAttachment)+ .where(eq(communityAttachment.messageId, messageId))+ .orderBy(+ asc(communityAttachment.position),+ asc(communityAttachment.createdAt),+ );++ return {+ ...message,+ attachmentContentTypes: attachments.map((row) => row.contentType),+ };+}diff --git a/src/shared/src/db/queries/community/push-device.ts b/src/shared/src/db/queries/community/push-device.tsnew file mode 100644index 000000000..b6ab4201f--- /dev/null+++ b/src/shared/src/db/queries/community/push-device.ts@@ -0,0 +1,159 @@+import { and, asc, eq, isNull, or } from "drizzle-orm";+import { communityPushDevice } from "../../community-schema";+import type { Database } from "../../index";++export type PushDevicePlatform = "ios" | "android";+export type PushProviderEnvironment = "sandbox" | "production";++export interface PushDeviceMetadata {+ installationId: string;+ platform: PushDevicePlatform;+ providerEnvironment: PushProviderEnvironment;+ appVersion: string | null;+ lastSeenAt: string;+ disabledAt: string | null;+}++export interface ActivePushDevice {+ id: string;+ installationId: string;+ platform: PushDevicePlatform;+ providerEnvironment: PushProviderEnvironment;+ providerTokenEncrypted: string;+}++export interface RegisterPushDeviceInput {+ userId: string;+ installationId: string;+ platform: PushDevicePlatform;+ providerEnvironment: PushProviderEnvironment;+ providerTokenEncrypted: string;+ providerTokenHash: string;+ previousProviderTokenHash?: string;+ appVersion?: string;+ now: string;+}++export type RegisterPushDeviceResult =+ | { ok: true; device: PushDeviceMetadata }+ | { ok: false; reason: "ownership-conflict" };++const metadataProjection = {+ installationId: communityPushDevice.installationId,+ platform: communityPushDevice.platform,+ providerEnvironment: communityPushDevice.providerEnvironment,+ appVersion: communityPushDevice.appVersion,+ lastSeenAt: communityPushDevice.lastSeenAt,+ disabledAt: communityPushDevice.disabledAt,+};++export async function registerPushDevice(+ db: Database,+ input: RegisterPushDeviceInput,+): Promise<RegisterPushDeviceResult> {+ const ownershipProof = or(+ eq(communityPushDevice.userId, input.userId),+ eq(communityPushDevice.providerTokenHash, input.providerTokenHash),+ input.previousProviderTokenHash+ ? eq(+ communityPushDevice.providerTokenHash,+ input.previousProviderTokenHash,+ )+ : undefined,+ );++ const rows = await db+ .insert(communityPushDevice)+ .values({+ userId: input.userId,+ installationId: input.installationId,+ platform: input.platform,+ providerEnvironment: input.providerEnvironment,+ providerTokenEncrypted: input.providerTokenEncrypted,+ providerTokenHash: input.providerTokenHash,+ appVersion: input.appVersion ?? null,+ lastSeenAt: input.now,+ createdAt: input.now,+ updatedAt: input.now,+ })+ .onConflictDoUpdate({+ target: communityPushDevice.installationId,+ set: {+ userId: input.userId,+ platform: input.platform,+ providerEnvironment: input.providerEnvironment,+ providerTokenEncrypted: input.providerTokenEncrypted,+ providerTokenHash: input.providerTokenHash,+ appVersion: input.appVersion ?? null,+ lastSeenAt: input.now,+ disabledAt: null,+ updatedAt: input.now,+ },+ setWhere: ownershipProof,+ })+ .returning(metadataProjection);++ const device = rows[0];+ if (!device) return { ok: false, reason: "ownership-conflict" };++ return {+ ok: true,+ device: {+ ...device,+ platform: device.platform as PushDevicePlatform,+ providerEnvironment:+ device.providerEnvironment as PushProviderEnvironment,+ },+ };+}++export async function disablePushDevice(+ db: Database,+ input: { userId: string; installationId: string; now: string },+): Promise<boolean> {+ const rows = await db+ .update(communityPushDevice)+ .set({ disabledAt: input.now, updatedAt: input.now })+ .where(+ and(+ eq(communityPushDevice.userId, input.userId),+ eq(communityPushDevice.installationId, input.installationId),+ isNull(communityPushDevice.disabledAt),+ ),+ )+ .returning({ id: communityPushDevice.id });++ return rows.length > 0;+}++export async function listActivePushDevices(+ db: Database,+ userId: string,+): Promise<ActivePushDevice[]> {+ const rows = await db+ .select({+ id: communityPushDevice.id,+ installationId: communityPushDevice.installationId,+ platform: communityPushDevice.platform,+ providerEnvironment: communityPushDevice.providerEnvironment,+ providerTokenEncrypted: communityPushDevice.providerTokenEncrypted,+ })+ .from(communityPushDevice)+ .where(+ and(+ eq(communityPushDevice.userId, userId),+ isNull(communityPushDevice.disabledAt),+ ),+ )+ .orderBy(+ asc(communityPushDevice.createdAt),+ asc(communityPushDevice.id),+ );++ return rows.map((row) => ({+ ...row,+ platform: row.platform as PushDevicePlatform,+ providerEnvironment:+ row.providerEnvironment as PushProviderEnvironment,+ }));+}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 48b7ee506..1bfee1e13 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -106,7 +106,7 @@ export {DEV_WEB_URL,DEV_WS_DO_URL,DEV_EMAIL_WORKER_URL,- DEV_WAKE_WORKER_URL,+ DEV_QUEUE_WORKER_URL,devWsDoPort,MeetingStatus,TERMINAL_MEETING_STATUSES,@@ -554,6 +554,15 @@ export type {} from "./community-message-delivery";export type { DispatchOneWakeResult } from "./community/wake-dispatch";export type { WakePayload, BuildUnreadWakeResult } from "./community/wake-dispatch";+export { parseQueueTask, parseQueueTaskBatch } from "./community/queue-task";+export type {+ AlookQueueTask,+ BotWakeQueueTaskV1,+ MobilePushQueueTaskV1,+ QueueTaskRejectReason,+ QueueTaskParseResult,+ QueueTaskBatchParseResult,+} from "./community/queue-task";export {BOT_ACTIVITY_PRESETS,@@ -698,7 +707,7 @@ export type {} from "./community-server-rail";export * as schema from "./db/schema";export * as queries from "./db/queries-index";-export { communityServer, communityServerInvite, communityFriendship, communityServerMember, communityServerFolder, communityServerFolderItem, communityBotActivityEvent, communityBotDailyActivity } from "./db/community-schema";+export { communityServer, communityServerInvite, communityFriendship, communityServerMember, communityServerFolder, communityServerFolderItem, communityBotActivityEvent, communityBotDailyActivity, communityPushDevice } from "./db/community-schema";// Loggerexport { Logger, createLogger } from "./logger"diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.tsindex 97552e4e7..0570a31ec 100644--- a/src/shared/src/runtime-config.ts+++ b/src/shared/src/runtime-config.ts@@ -8,7 +8,7 @@** Lifted from `src/daemon/src/runtimeConfig.ts` into `@alook/shared` because* `HostCommand`'s `agent:wake.config` field needs this type, and the wake- * producer/consumer (`src/web` + `src/wake-worker`, both Workers) has no path+ * producer/consumer (`src/web` + `src/queue-worker`, both Workers) has no path* to import from the CLI/daemon package. `src/daemon` re-exports* `RuntimeConfig`/`makeRuntimeConfig` from here; `resolveLaunchFields`/* `ResolvedLaunchFields` stay daemon-only (host-side launch resolution, notdiff --git a/src/shared/test/community/queue-task.test.ts b/src/shared/test/community/queue-task.test.tsnew file mode 100644index 000000000..08a8690da--- /dev/null+++ b/src/shared/test/community/queue-task.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it } from "vitest"+import { parseQueueTask, parseQueueTaskBatch } from "../../src/community/queue-task"++describe("parseQueueTask", () => {+ it.each([+ {+ name: "legacy",+ value: { messageId: "message-1", botUserId: "bot-1" },+ source: "legacy",+ },+ {+ name: "v1 bot-wake",+ value: { version: 1, kind: "bot-wake", messageId: "message-1", botUserId: "bot-1" },+ source: "v1",+ },+ ])("normalizes a valid $name task", ({ value, source }) => {+ expect(parseQueueTask(value)).toEqual({+ ok: true,+ source,+ task: {+ version: 1,+ kind: "bot-wake",+ messageId: "message-1",+ botUserId: "bot-1",+ },+ })+ })++ it.each([+ { name: "null", value: null },+ { name: "array", value: [] },+ { name: "primitive", value: "wake" },+ { name: "missing legacy key", value: { messageId: "message-1" } },+ { name: "extra legacy key", value: { messageId: "message-1", botUserId: "bot-1", extra: true } },+ { name: "empty message ID", value: { messageId: "", botUserId: "bot-1" } },+ { name: "blank bot ID", value: { messageId: "message-1", botUserId: " " } },+ { name: "missing version", value: { kind: "bot-wake", messageId: "message-1", botUserId: "bot-1" } },+ { name: "non-number version", value: { version: "1", kind: "bot-wake", messageId: "message-1", botUserId: "bot-1" } },+ { name: "missing kind", value: { version: 1, messageId: "message-1", botUserId: "bot-1" } },+ { name: "extra v1 key", value: { version: 1, kind: "bot-wake", messageId: "message-1", botUserId: "bot-1", extra: true } },+ { name: "wrong v1 recipient key", value: { version: 1, kind: "bot-wake", messageId: "message-1", userId: "bot-1" } },+ { name: "malformed mobile-push", value: { version: 1, kind: "mobile-push", messageId: "message-1", userId: "" } },+ ])("rejects malformed input: $name", ({ value }) => {+ expect(parseQueueTask(value)).toEqual({ ok: false, reason: "malformed" })+ })++ it("classifies unsupported versions", () => {+ expect(parseQueueTask({+ version: 2,+ kind: "bot-wake",+ messageId: "message-1",+ botUserId: "bot-1",+ })).toEqual({ ok: false, reason: "unsupported_version" })+ })++ it("classifies unknown v1 task kinds", () => {+ expect(parseQueueTask({+ version: 1,+ kind: "email",+ messageId: "message-1",+ userId: "user-1",+ })).toEqual({ ok: false, reason: "unknown_kind" })+ })++ it("accepts an exact mobile-push task", () => {+ expect(parseQueueTask({+ version: 1,+ kind: "mobile-push",+ messageId: "message-1",+ userId: "user-1",+ })).toEqual({+ ok: true,+ source: "v1",+ task: {+ version: 1,+ kind: "mobile-push",+ messageId: "message-1",+ userId: "user-1",+ },+ })+ })+})++describe("parseQueueTaskBatch", () => {+ it("normalizes the complete legacy/v1 batch", () => {+ expect(parseQueueTaskBatch([+ { messageId: "message-1", botUserId: "bot-1" },+ { version: 1, kind: "bot-wake", messageId: "message-2", botUserId: "bot-2" },+ { version: 1, kind: "mobile-push", messageId: "message-3", userId: "user-3" },+ ])).toEqual({+ ok: true,+ tasks: [+ { version: 1, kind: "bot-wake", messageId: "message-1", botUserId: "bot-1" },+ { version: 1, kind: "bot-wake", messageId: "message-2", botUserId: "bot-2" },+ { version: 1, kind: "mobile-push", messageId: "message-3", userId: "user-3" },+ ],+ })+ })++ it("reports the first rejected item without returning partial payloads", () => {+ expect(parseQueueTaskBatch([+ { messageId: "message-1", botUserId: "bot-1" },+ { version: 1, kind: "email", messageId: "message-2", userId: "user-2" },+ { messageId: "message-3", botUserId: "bot-3" },+ ])).toEqual({ ok: false, reason: "unknown_kind", itemIndex: 1 })+ })++ it("rejects a non-array body", () => {+ expect(parseQueueTaskBatch({ messageId: "message-1", botUserId: "bot-1" }))+ .toEqual({ ok: false, reason: "malformed", itemIndex: null })+ })+})diff --git a/src/shared/test/community/wake-dispatch-one.test.ts b/src/shared/test/community/wake-dispatch-one.test.tsindex ac49ae44b..272f56b13 100644--- a/src/shared/test/community/wake-dispatch-one.test.ts+++ b/src/shared/test/community/wake-dispatch-one.test.ts@@ -83,7 +83,7 @@ function makeEnv(fetchImpl: (url: string, init?: RequestInit) => Promise<Respons/*** `dispatchOneUnreadWake` is the ONE per-candidate function both- * `src/wake-worker`'s real queue consumer and `src/web`'s dev-only inline+ * `src/queue-worker`'s real queue consumer and `src/web`'s dev-only inline* stand-in call — these tests exercise it through its real* `buildUnreadWakeCommand`/`sendWakeToMachine` wiring end-to-end (query* modules mocked, `fetch` mocked), so neither caller needs its owndiff --git a/src/shared/test/migrations/community-push-device.test.ts b/src/shared/test/migrations/community-push-device.test.tsnew file mode 100644index 000000000..bbf143f76--- /dev/null+++ b/src/shared/test/migrations/community-push-device.test.ts@@ -0,0 +1,124 @@+import { readFileSync } from "node:fs";+import Sqlite from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++const migration = readFileSync(+ new URL(+ "../../../web/migrations/0102_community_push_device.sql",+ import.meta.url,+ ),+ "utf8",+);++describe("community push device migration", () => {+ let sqlite: Sqlite.Database;++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.pragma("foreign_keys = ON");+ sqlite.exec("CREATE TABLE user (id TEXT PRIMARY KEY NOT NULL)");+ sqlite.exec(migration);+ });++ afterEach(() => sqlite.close());++ function insertDevice(+ overrides: Partial<Record<string, string | null>> = {},+ ): void {+ const row = {+ id: "device-row-1",+ user_id: "user-1",+ installation_id: "installation-1",+ platform: "ios",+ provider_environment: "sandbox",+ provider_token_encrypted: "fake-ciphertext",+ provider_token_hash: "a".repeat(64),+ app_version: null,+ last_seen_at: "2026-09-12T00:00:00.000Z",+ disabled_at: null,+ created_at: "2026-09-12T00:00:00.000Z",+ updated_at: "2026-09-12T00:00:00.000Z",+ ...overrides,+ };++ sqlite+ .prepare(+ `INSERT INTO community_push_device (+ id, user_id, installation_id, platform, provider_environment,+ provider_token_encrypted, provider_token_hash, app_version,+ last_seen_at, disabled_at, created_at, updated_at+ ) VALUES (+ @id, @user_id, @installation_id, @platform, @provider_environment,+ @provider_token_encrypted, @provider_token_hash, @app_version,+ @last_seen_at, @disabled_at, @created_at, @updated_at+ )`,+ )+ .run(row);+ }++ it("creates the exact one-table, zero-trigger contract", () => {+ const columns = sqlite+ .prepare("PRAGMA table_info(community_push_device)")+ .all() as Array<{ name: string; notnull: number; dflt_value: string | null }>;++ expect(columns.map(({ name, notnull, dflt_value }) => ({+ name,+ notnull,+ default: dflt_value,+ }))).toEqual([+ { name: "id", notnull: 1, default: null },+ { name: "user_id", notnull: 1, default: null },+ { name: "installation_id", notnull: 1, default: null },+ { name: "platform", notnull: 1, default: null },+ { name: "provider_environment", notnull: 1, default: null },+ { name: "provider_token_encrypted", notnull: 1, default: null },+ { name: "provider_token_hash", notnull: 1, default: null },+ { name: "app_version", notnull: 0, default: null },+ { name: "last_seen_at", notnull: 1, default: null },+ { name: "disabled_at", notnull: 0, default: null },+ { name: "created_at", notnull: 1, default: null },+ { name: "updated_at", notnull: 1, default: null },+ ]);++ const indexes = sqlite+ .prepare("PRAGMA index_list(community_push_device)")+ .all() as Array<{ name: string; unique: number }>;+ expect(indexes).toEqual(expect.arrayContaining([+ expect.objectContaining({ name: "uq_push_device_installation", unique: 1 }),+ expect.objectContaining({ name: "idx_push_device_user_active", unique: 0 }),+ expect.objectContaining({ name: "idx_push_device_token_hash", unique: 0 }),+ ]));+ expect(sqlite.prepare(+ "SELECT name FROM sqlite_master WHERE type = 'trigger'",+ ).all()).toEqual([]);+ });++ it("enforces platform, environment, token-hash, and required fields", () => {+ sqlite.prepare("INSERT INTO user (id) VALUES (?)").run("user-1");++ expect(() => insertDevice({ platform: "web" })).toThrow();+ expect(() => insertDevice({ provider_environment: "development" })).toThrow();+ expect(() => insertDevice({ platform: "android" })).toThrow();+ expect(() => insertDevice({ provider_token_hash: "A".repeat(64) })).toThrow();+ expect(() => insertDevice({ provider_token_hash: "a".repeat(63) })).toThrow();+ expect(() => insertDevice({ provider_token_encrypted: null })).toThrow();++ expect(() => insertDevice({+ platform: "android",+ provider_environment: "production",+ })).not.toThrow();+ });++ it("keeps installation ids global and cascades account deletion", () => {+ sqlite.prepare("INSERT INTO user (id) VALUES (?)").run("user-1");+ insertDevice();++ expect(() => insertDevice({ id: "device-row-2" })).toThrow();+ sqlite.prepare("DELETE FROM user WHERE id = ?").run("user-1");++ expect(sqlite.prepare(+ "SELECT COUNT(*) AS count FROM community_push_device",+ ).get()).toEqual({ count: 0 });+ expect(sqlite.prepare("PRAGMA foreign_key_check").all()).toEqual([]);+ });+});diff --git a/src/shared/test/queries/community-notification-target.test.ts b/src/shared/test/queries/community-notification-target.test.tsnew file mode 100644index 000000000..9942bf41f--- /dev/null+++ b/src/shared/test/queries/community-notification-target.test.ts@@ -0,0 +1,59 @@+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import * as coreSchema from "../../src/db/schema";+import * as communitySchema from "../../src/db/community-schema";+import type { Database } from "../../src/db";+import { getPushNotificationTarget } from "../../src/db/queries/community/notification-target";++const schema = { ...coreSchema, ...communitySchema };++describe("community notification target query", () => {+ let sqlite: Sqlite.Database;+ let db: Database;++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE user (id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL);+ CREATE TABLE community_message (+ id TEXT PRIMARY KEY NOT NULL,+ author_id TEXT NOT NULL,+ content TEXT NOT NULL,+ channel_id TEXT NOT NULL+ );+ CREATE TABLE community_attachment (+ id TEXT PRIMARY KEY NOT NULL,+ message_id TEXT,+ content_type TEXT,+ position INTEGER,+ created_at TEXT NOT NULL+ );+ INSERT INTO user (id, name) VALUES ('author-1', 'Alice');+ INSERT INTO community_message (id, author_id, content, channel_id)+ VALUES ('message-1', 'author-1', '**hello**', 'channel-1');+ INSERT INTO community_attachment+ (id, message_id, content_type, position, created_at)+ VALUES+ ('attachment-2', 'message-1', 'application/pdf', 1, '2026-09-12T00:00:01.000Z'),+ ('attachment-1', 'message-1', 'image/png', 0, '2026-09-12T00:00:00.000Z');+ `);+ db = drizzle(sqlite, { schema }) as unknown as Database;+ });++ afterEach(() => sqlite.close());++ it("loads minimal display content only after the caller has gated eligibility", async () => {+ await expect(getPushNotificationTarget(db, "message-1")).resolves.toEqual({+ messageId: "message-1",+ channelId: "channel-1",+ authorName: "Alice",+ content: "**hello**",+ attachmentContentTypes: ["image/png", "application/pdf"],+ });+ });++ it("returns null for a deleted or missing message", async () => {+ await expect(getPushNotificationTarget(db, "missing")).resolves.toBeNull();+ });+});diff --git a/src/shared/test/queries/community-push-device.test.ts b/src/shared/test/queries/community-push-device.test.tsnew file mode 100644index 000000000..862e92174--- /dev/null+++ b/src/shared/test/queries/community-push-device.test.ts@@ -0,0 +1,257 @@+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { getTableConfig } from "drizzle-orm/sqlite-core";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as coreSchema from "../../src/db/schema";+import * as communitySchema from "../../src/db/community-schema";+import type { Database } from "../../src/db";+import {+ disablePushDevice,+ listActivePushDevices,+ registerPushDevice,+ type RegisterPushDeviceInput,+} from "../../src/db/queries/community/push-device";++const schema = { ...coreSchema, ...communitySchema };++describe("community push device queries", () => {+ let sqlite: Sqlite.Database;+ let db: Database;++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.pragma("foreign_keys = ON");+ sqlite.exec("CREATE TABLE user (id TEXT PRIMARY KEY NOT NULL)");+ sqlite.exec(`+ CREATE TABLE community_push_device (+ id TEXT PRIMARY KEY NOT NULL,+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ installation_id TEXT NOT NULL UNIQUE,+ platform TEXT NOT NULL,+ provider_environment TEXT NOT NULL,+ provider_token_encrypted TEXT NOT NULL,+ provider_token_hash TEXT NOT NULL,+ app_version TEXT,+ last_seen_at TEXT NOT NULL,+ disabled_at TEXT,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL+ )+ `);+ sqlite.prepare("INSERT INTO user (id) VALUES (?), (?)").run("user-a", "user-b");+ db = drizzle(sqlite, { schema }) as unknown as Database;+ });++ afterEach(() => {+ vi.useRealTimers();+ sqlite.close();+ });++ function registration(+ overrides: Partial<RegisterPushDeviceInput> = {},+ ): RegisterPushDeviceInput {+ return {+ userId: "user-a",+ installationId: "installation-1",+ platform: "ios",+ providerEnvironment: "sandbox",+ providerTokenEncrypted: "fake-ciphertext-1",+ providerTokenHash: "a".repeat(64),+ appVersion: "1.0.0",+ now: "2026-09-12T00:00:00.000Z",+ ...overrides,+ };+ }++ function storedRow(): Record<string, unknown> {+ return sqlite.prepare(+ "SELECT * FROM community_push_device WHERE installation_id = ?",+ ).get("installation-1") as Record<string, unknown>;+ }++ it("declares the user cascade and applies timestamp defaults", async () => {+ const userForeignKey = getTableConfig(communitySchema.communityPushDevice)+ .foreignKeys[0]!;+ expect(userForeignKey.reference()).toMatchObject({+ columns: [{ name: "user_id" }],+ foreignColumns: [{ name: "id" }],+ });+ expect(userForeignKey.onDelete).toBe("cascade");++ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-09-12T04:05:06.000Z"));+ await db.insert(communitySchema.communityPushDevice).values({+ userId: "user-a",+ installationId: "installation-1",+ platform: "ios",+ providerEnvironment: "sandbox",+ providerTokenEncrypted: "fake-ciphertext-1",+ providerTokenHash: "a".repeat(64),+ });++ expect(storedRow()).toMatchObject({+ last_seen_at: "2026-09-12T04:05:06.000Z",+ created_at: "2026-09-12T04:05:06.000Z",+ updated_at: "2026-09-12T04:05:06.000Z",+ });+ });++ it("inserts, replays idempotently, and refreshes same-account metadata", async () => {+ const first = await registerPushDevice(db, registration());+ expect(first).toEqual({+ ok: true,+ device: {+ installationId: "installation-1",+ platform: "ios",+ providerEnvironment: "sandbox",+ appVersion: "1.0.0",+ lastSeenAt: "2026-09-12T00:00:00.000Z",+ disabledAt: null,+ },+ });+ expect(Object.keys(first.ok ? first.device : {})).not.toEqual(expect.arrayContaining([+ "userId",+ "providerTokenEncrypted",+ "providerTokenHash",+ ]));++ const originalId = storedRow().id;+ await registerPushDevice(db, registration({+ platform: "android",+ providerEnvironment: "production",+ providerTokenEncrypted: "fake-ciphertext-2",+ providerTokenHash: "b".repeat(64),+ appVersion: "2.0.0",+ now: "2026-09-12T01:00:00.000Z",+ }));++ expect(storedRow()).toMatchObject({+ id: originalId,+ user_id: "user-a",+ platform: "android",+ provider_environment: "production",+ provider_token_encrypted: "fake-ciphertext-2",+ provider_token_hash: "b".repeat(64),+ app_version: "2.0.0",+ last_seen_at: "2026-09-12T01:00:00.000Z",+ created_at: "2026-09-12T00:00:00.000Z",+ updated_at: "2026-09-12T01:00:00.000Z",+ });+ expect(sqlite.prepare(+ "SELECT COUNT(*) AS count FROM community_push_device",+ ).get()).toEqual({ count: 1 });+ });++ it("permits cross-account transfer only with current or previous token proof", async () => {+ await registerPushDevice(db, registration());++ await expect(registerPushDevice(db, registration({+ userId: "user-b",+ providerTokenEncrypted: "fake-current-proof-ciphertext",+ }))).resolves.toMatchObject({ ok: true });+ expect(storedRow()).toMatchObject({ user_id: "user-b" });++ await registerPushDevice(db, registration({+ userId: "user-b",+ providerTokenEncrypted: "fake-rotated-ciphertext",+ providerTokenHash: "b".repeat(64),+ }));+ await expect(registerPushDevice(db, registration({+ userId: "user-a",+ providerTokenEncrypted: "fake-new-account-ciphertext",+ providerTokenHash: "c".repeat(64),+ previousProviderTokenHash: "b".repeat(64),+ }))).resolves.toMatchObject({ ok: true });+ expect(storedRow()).toMatchObject({+ user_id: "user-a",+ provider_token_hash: "c".repeat(64),+ });+ });++ it("rejects an installation-id-only hijack without changing the row", async () => {+ await registerPushDevice(db, registration());+ const before = storedRow();++ await expect(registerPushDevice(db, registration({+ userId: "user-b",+ providerTokenEncrypted: "fake-attacker-ciphertext",+ providerTokenHash: "d".repeat(64),+ appVersion: "9.9.9",+ now: "2026-09-12T02:00:00.000Z",+ }))).resolves.toEqual({ ok: false, reason: "ownership-conflict" });++ expect(storedRow()).toEqual(before);+ });++ it("soft-disables only the owner and reactivates on registration", async () => {+ await registerPushDevice(db, registration());++ await expect(disablePushDevice(db, {+ userId: "user-b",+ installationId: "installation-1",+ now: "2026-09-12T01:00:00.000Z",+ })).resolves.toBe(false);+ await expect(disablePushDevice(db, {+ userId: "user-a",+ installationId: "missing-installation",+ now: "2026-09-12T01:00:00.000Z",+ })).resolves.toBe(false);+ await expect(disablePushDevice(db, {+ userId: "user-a",+ installationId: "installation-1",+ now: "2026-09-12T01:00:00.000Z",+ })).resolves.toBe(true);+ await expect(disablePushDevice(db, {+ userId: "user-a",+ installationId: "installation-1",+ now: "2026-09-12T02:00:00.000Z",+ })).resolves.toBe(false);+ expect(storedRow()).toMatchObject({+ disabled_at: "2026-09-12T01:00:00.000Z",+ updated_at: "2026-09-12T01:00:00.000Z",+ });++ await expect(registerPushDevice(db, registration({+ now: "2026-09-12T03:00:00.000Z",+ }))).resolves.toMatchObject({+ ok: true,+ device: { disabledAt: null },+ });+ expect(storedRow()).toMatchObject({ disabled_at: null });+ });++ it("returns every active device for one user without plaintext token fields", async () => {+ await registerPushDevice(db, registration());+ await registerPushDevice(db, registration({+ installationId: "installation-2",+ platform: "android",+ providerEnvironment: "production",+ providerTokenEncrypted: "fake-ciphertext-2",+ providerTokenHash: "b".repeat(64),+ now: "2026-09-12T01:00:00.000Z",+ }));+ await registerPushDevice(db, registration({+ userId: "user-b",+ installationId: "installation-3",+ providerTokenEncrypted: "fake-ciphertext-3",+ providerTokenHash: "c".repeat(64),+ }));+ await disablePushDevice(db, {+ userId: "user-a",+ installationId: "installation-2",+ now: "2026-09-12T02:00:00.000Z",+ });++ const devices = await listActivePushDevices(db, "user-a");++ expect(devices).toHaveLength(1);+ expect(devices[0]).toMatchObject({+ installationId: "installation-1",+ platform: "ios",+ providerEnvironment: "sandbox",+ providerTokenEncrypted: "fake-ciphertext-1",+ });+ expect(devices[0]).not.toHaveProperty("providerTokenHash");+ expect(devices[0]).not.toHaveProperty("userId");+ });+});diff --git a/src/wake-worker/src/env.d.ts b/src/wake-worker/src/env.d.tsdeleted file mode 100644index 82a35f0bc..000000000--- a/src/wake-worker/src/env.d.ts+++ /dev/null@@ -1,10 +0,0 @@-interface Env {- WS_DO_WORKER: Fetcher- /**- * `alook-app` — the same D1 database `src/web/wrangler.toml` binds as- * `DB` (minimal-wake-queue-unread-notice plan §3). The consumer reads- * current message/bot/binding/read-state rows here to rebuild the- * `agent:wake` command at consume time (`buildUnreadWakeCommand`).- */- DB: D1Database-}diff --git a/src/wake-worker/src/index.test.ts b/src/wake-worker/src/index.test.tsdeleted file mode 100644index 01d52e5b2..000000000--- a/src/wake-worker/src/index.test.ts+++ /dev/null@@ -1,296 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"--const mockDispatchOneUnreadWake = vi.fn()-const mockCreateDb = vi.fn((..._a: unknown[]) => ({ __db: true }))-const { mockLogInfo } = vi.hoisted(() => ({ mockLogInfo: vi.fn() }))-vi.mock("@alook/shared", () => {- const noopLogger = { debug: () => { }, info: mockLogInfo, warn: () => { }, error: () => { }, child() { return this } }- return {- createLogger: () => noopLogger,- createDb: (...a: unknown[]) => mockCreateDb(...a),- dispatchOneUnreadWake: (...a: unknown[]) => mockDispatchOneUnreadWake(...a),- }-})--import handler from "./index"--function makeMsg(body: { messageId: string; botUserId: string }) {- return { body, ack: vi.fn(), retry: vi.fn() }-}--describe("wake-worker queue consumer", () => {- const env = { WS_DO_WORKER: {}, DB: {} } as unknown as Env-- beforeEach(() => {- vi.clearAllMocks()- })-- it("resolves via dispatchOneUnreadWake and acks after an attempted write", async () => {- mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "attempted" })- const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })- const batch = { messages: [msg] } as unknown as MessageBatch<unknown>-- await handler.queue(batch as never, env)-- expect(mockCreateDb).toHaveBeenCalledWith(env.DB)- expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith({ __db: true }, env, { messageId: "msg1", botUserId: "bot1" })- expect(msg.ack).toHaveBeenCalledTimes(1)- expect(msg.retry).not.toHaveBeenCalled()- })-- it("acks and logs when no socket write was attempted — reconnect resync owns recovery", async () => {- mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "attempted_nowhere", machineId: "m1" })- const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })- const batch = { messages: [msg] } as unknown as MessageBatch<unknown>-- await handler.queue(batch as never, env)-- expect(msg.ack).toHaveBeenCalledTimes(1)- expect(msg.retry).not.toHaveBeenCalled()- expect(mockLogInfo).toHaveBeenCalledWith("wake_attempted_nowhere", {- botUserId: "bot1",- machineId: "m1",- })- })-- it("acks when the resolution is a skip", async () => {- mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "skip", reason: "already_read" })- const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })- const batch = { messages: [msg] } as unknown as MessageBatch<unknown>-- await handler.queue(batch as never, env)-- expect(msg.ack).toHaveBeenCalledTimes(1)- expect(msg.retry).not.toHaveBeenCalled()- })-- it.each([- "message_missing",- "invalid_message_scope",- "self_authored",- "bot_missing",- "bot_deleted",- "bot_unbound",- "forbidden",- "notice_channel_unresolvable",- "already_read",- ] as const)("acks for skip reason %s", async (reason) => {- mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "skip", reason })- const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })- const batch = { messages: [msg] } as unknown as MessageBatch<unknown>-- await handler.queue(batch as never, env)-- expect(msg.ack).toHaveBeenCalledTimes(1)- expect(msg.retry).not.toHaveBeenCalled()- })-- it("retries with backoff when dispatchOneUnreadWake throws (D1 exception or transient sendWakeToMachine failure)", async () => {- mockDispatchOneUnreadWake.mockRejectedValue(new Error("D1 query failed"))- const msg = makeMsg({ messageId: "msg1", botUserId: "bot1" })- const batch = { messages: [msg] } as unknown as MessageBatch<unknown>-- await handler.queue(batch as never, env)-- expect(msg.retry).toHaveBeenCalledWith({ delaySeconds: 5 })- expect(msg.ack).not.toHaveBeenCalled()- })-- it("processes every message in the batch independently — one failure doesn't block others", async () => {- mockDispatchOneUnreadWake- .mockResolvedValueOnce({ outcome: "attempted" })- .mockRejectedValueOnce(new Error("boom"))- .mockResolvedValueOnce({ outcome: "skip", reason: "already_read" })-- const msgs = [- makeMsg({ messageId: "msg1", botUserId: "bot1" }),- makeMsg({ messageId: "msg2", botUserId: "bot2" }),- makeMsg({ messageId: "msg3", botUserId: "bot3" }),- ]- const batch = { messages: msgs } as unknown as MessageBatch<unknown>-- await handler.queue(batch as never, env)-- expect(msgs[0]!.ack).toHaveBeenCalledTimes(1)- expect(msgs[1]!.retry).toHaveBeenCalledWith({ delaySeconds: 5 })- expect(msgs[2]!.ack).toHaveBeenCalledTimes(1)- })-})--describe("wake-worker dev-only HTTP entrypoint (fetch)", () => {- const env = { WS_DO_WORKER: {}, DB: {} } as unknown as Env-- beforeEach(() => {- vi.clearAllMocks()- })-- function makeRequest(method: string, body?: unknown) {- return new Request("http://internal/", {- method,- body: body === undefined ? undefined : JSON.stringify(body),- })- }-- it("resolves every candidate in the body via dispatchOneUnreadWake — the SAME function queue() calls", async () => {- mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "attempted" })- const payloads = [- { messageId: "msg1", botUserId: "bot1" },- { messageId: "msg1", botUserId: "bot2" },- ]-- const res = await handler.fetch!(makeRequest("POST", payloads), env)-- expect(res.status).toBe(202)- expect(mockCreateDb).toHaveBeenCalledWith(env.DB)- expect(mockDispatchOneUnreadWake).toHaveBeenCalledTimes(2)- expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith({ __db: true }, env, payloads[0])- expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith({ __db: true }, env, payloads[1])- })-- it("returns 202 even when a skip/attempted_nowhere outcome resolves (no queue infra to ack/retry against)", async () => {- mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "skip", reason: "already_read" })-- const res = await handler.fetch!(makeRequest("POST", [{ messageId: "msg1", botUserId: "bot1" }]), env)-- expect(res.status).toBe(202)- })-- it("deduplicates candidates by stable messageId + botUserId within one request", async () => {- mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "attempted" })- const first = { messageId: "msg:one", botUserId: "bot" }- const delimiterCollision = { messageId: "msg", botUserId: "one:bot" }-- const res = await handler.fetch!(makeRequest("POST", [first, delimiterCollision, first]), env)-- expect(res.status).toBe(202)- expect(mockDispatchOneUnreadWake).toHaveBeenCalledTimes(2)- expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith({ __db: true }, env, first)- expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith({ __db: true }, env, delimiterCollision)- })-- it("retries only a transiently failing candidate while a healthy sibling is dispatched once", async () => {- const attempts = new Map<string, number>()- mockDispatchOneUnreadWake.mockImplementation(async (_db: unknown, _env: unknown, item: { botUserId: string }) => {- const attempt = (attempts.get(item.botUserId) ?? 0) + 1- attempts.set(item.botUserId, attempt)- if (item.botUserId === "bot_flaky" && attempt === 1) throw new Error("D1 exploded")- return { outcome: "attempted" }- })-- const res = await handler.fetch!(- makeRequest("POST", [- { messageId: "msg1", botUserId: "bot_flaky" },- { messageId: "msg1", botUserId: "bot_healthy" },- ]),- env,- )-- expect(res.status).toBe(202)- expect(attempts).toEqual(new Map([- ["bot_flaky", 2],- ["bot_healthy", 1],- ]))- })-- it("returns 207 with failed stable keys after bounded retries are exhausted without redispatching a healthy sibling", async () => {- const attempts = new Map<string, number>()- mockDispatchOneUnreadWake.mockImplementation(async (_db: unknown, _env: unknown, item: { botUserId: string }) => {- const attempt = (attempts.get(item.botUserId) ?? 0) + 1- attempts.set(item.botUserId, attempt)- if (item.botUserId === "bot_flaky") throw new Error("D1 stayed down")- return { outcome: "attempted" }- })-- const res = await handler.fetch!(- makeRequest("POST", [- { messageId: "msg1", botUserId: "bot_flaky" },- { messageId: "msg1", botUserId: "bot_healthy" },- ]),- env,- )-- expect(res.status).toBe(207)- expect(await res.json()).toEqual({- failed: [{ messageId: "msg1", botUserId: "bot_flaky" }],- })- expect(attempts).toEqual(new Map([- ["bot_flaky", 3],- ["bot_healthy", 1],- ]))- })--})--/**- * Equivalence contract: `queue()` (real Cloudflare Queue traffic) and- * `fetch()` (dev-only stand-in `wake-transport.ts`'s dev HTTP transport- * calls) MUST resolve a given `WakePayload` identically — same- * `dispatchOneUnreadWake` call, same args — because they share the exact- * same `resolveAndLog` helper. This single table is exercised against BOTH- * entrypoints so a future change that special-cases one of them (instead of- * `resolveAndLog`) fails a test here, not just in production later.- *- * Queue infrastructure and dev HTTP use different retry mechanisms, but- * both must preserve sibling isolation and surface exhausted transient- * failures instead of silently swallowing them. Entry-point-specific retry- * details are covered by the `describe` blocks above.- */-const RESOLUTION_SCENARIOS = [- { name: "attempted", outcome: { outcome: "attempted" as const } },- { name: "attempted_nowhere", outcome: { outcome: "attempted_nowhere" as const, machineId: "m1" } },- { name: "skip: already_read", outcome: { outcome: "skip" as const, reason: "already_read" as const } },- { name: "skip: forbidden", outcome: { outcome: "skip" as const, reason: "forbidden" as const } },- { name: "skip: muted", outcome: { outcome: "skip" as const, reason: "muted" as const } },- { name: "skip: mention_only", outcome: { outcome: "skip" as const, reason: "mention_only" as const } },-]--describe("wake-worker queue() vs fetch() — same resolution for the same candidate", () => {- const env = { WS_DO_WORKER: {}, DB: {} } as unknown as Env-- beforeEach(() => {- vi.clearAllMocks()- })-- it.each(RESOLUTION_SCENARIOS)("calls dispatchOneUnreadWake with identical args for scenario: $name", async ({ outcome }) => {- const item = { messageId: "msg1", botUserId: "bot1" }-- mockDispatchOneUnreadWake.mockResolvedValue(outcome)- await handler.queue({ messages: [{ body: item, ack: vi.fn(), retry: vi.fn() }] } as never, env)- const queueCallArgs = mockDispatchOneUnreadWake.mock.calls[0]-- vi.clearAllMocks()- mockDispatchOneUnreadWake.mockResolvedValue(outcome)- await handler.fetch!(new Request("http://internal/", { method: "POST", body: JSON.stringify([item]) }), env)- const fetchCallArgs = mockDispatchOneUnreadWake.mock.calls[0]-- expect(fetchCallArgs).toEqual(queueCallArgs)- })-- it("both entrypoints let a sibling proceed when one candidate has a transient failure", async () => {- const items = [- { messageId: "msg1", botUserId: "bot1" },- { messageId: "msg2", botUserId: "bot2" },- ]-- mockDispatchOneUnreadWake.mockRejectedValueOnce(new Error("boom")).mockResolvedValueOnce({ outcome: "attempted" })- const msgs = items.map((body) => ({ body, ack: vi.fn(), retry: vi.fn() }))- await handler.queue({ messages: msgs } as never, env)- expect(msgs[0]!.retry).toHaveBeenCalledTimes(1)- expect(msgs[1]!.ack).toHaveBeenCalledTimes(1)-- vi.clearAllMocks()- const attempts = new Map<string, number>()- mockDispatchOneUnreadWake.mockImplementation(async (_db: unknown, _env: unknown, item: { botUserId: string }) => {- const attempt = (attempts.get(item.botUserId) ?? 0) + 1- attempts.set(item.botUserId, attempt)- if (item.botUserId === "bot1" && attempt === 1) throw new Error("boom")- return { outcome: "attempted" }- })- const res = await handler.fetch!(new Request("http://internal/", { method: "POST", body: JSON.stringify(items) }), env)- expect(res.status).toBe(202)- expect(attempts).toEqual(new Map([- ["bot1", 2],- ["bot2", 1],- ]))- })-})diff --git a/src/wake-worker/src/index.ts b/src/wake-worker/src/index.tsdeleted file mode 100644index 8e5c58fe0..000000000--- a/src/wake-worker/src/index.ts+++ /dev/null@@ -1,153 +0,0 @@-import { createLogger, createDb, dispatchOneUnreadWake } from "@alook/shared"-import type { WakePayload, Database } from "@alook/shared"--const log = createLogger({ service: "wake-worker" })-const DEV_HTTP_MAX_ATTEMPTS = 3-const DEV_HTTP_RETRY_DELAYS_MS = [25, 100] as const--/**- * Resolve ONE wake candidate via `dispatchOneUnreadWake` and log its- * (non-error) outcome. Shared by both entrypoints below — `queue()` (real- * traffic) and `fetch()` (dev-only stand-in for the local Cloudflare Queue,- * see its doc comment) — so the log lines and interpretation logic exist- * exactly once regardless of which entrypoint received the item. Throws- * propagate untouched; each caller applies its own retry contract (Queue- * retry/DLQ versus bounded in-process retries for the dev HTTP shim).- */-async function resolveAndLog(db: Database, env: Env, item: WakePayload) {- const result = await dispatchOneUnreadWake(db, env, item)- if (result.outcome === "skip") {- // Every skip reason is a permanent current-state miss — caller must ack, never retry.- log.info("wake_skipped", { botUserId: item.botUserId, messageId: item.messageId, reason: result.reason })- } else if (result.outcome === "attempted_nowhere") {- // ws-do resolved cleanly but the daemon is offline — a known-permanent- // state for this attempt (plan §3's error contract). Daemon reconnect- // warmup recovers; retrying would just spin, so this also acks.- log.info("wake_attempted_nowhere", { botUserId: item.botUserId, machineId: result.machineId })- }- return result-}--function dedupeWakePayloads(payloads: WakePayload[]): WakePayload[] {- const seen = new Map<string, Set<string>>()- return payloads.filter((item) => {- let botIds = seen.get(item.messageId)- if (!botIds) {- botIds = new Set<string>()- seen.set(item.messageId, botIds)- }- if (botIds.has(item.botUserId)) return false- botIds.add(item.botUserId)- return true- })-}--async function waitForDevHttpRetry(delayMs: number): Promise<void> {- await new Promise<void>((resolve) => setTimeout(resolve, delayMs))-}--async function resolveDevHttpCandidate(db: Database, env: Env, item: WakePayload): Promise<boolean> {- for (let attempt = 1; attempt <= DEV_HTTP_MAX_ATTEMPTS; attempt++) {- try {- await resolveAndLog(db, env, item)- return true- } catch (err) {- if (attempt === DEV_HTTP_MAX_ATTEMPTS) {- log.warn("dev_http_wake_dispatch_exhausted", {- botUserId: item.botUserId,- messageId: item.messageId,- attempts: attempt,- err: String(err),- })- return false- }-- const delayMs = DEV_HTTP_RETRY_DELAYS_MS[attempt - 1]!- log.warn("dev_http_wake_dispatch_retrying", {- botUserId: item.botUserId,- messageId: item.messageId,- attempt,- delayMs,- err: String(err),- })- await waitForDevHttpRetry(delayMs)- }- }-- return false-}--export default {- /**- * `alook-wake-worker` — Cloudflare Queue consumer for `alook-wake`- * (minimal-wake-queue-unread-notice plan §3). Owns a `DB` binding to the- * same `alook-app` database `src/web` writes to: for every minimal- * `{ messageId, botUserId }` queue item, `dispatchOneUnreadWake` re-reads- * CURRENT D1 state and only then forwards a freshly built `agent:wake`- * `HostCommand`. This is what keeps a stale queue item from waking an old- * machine, an already-caught-up bot, or a bot that lost access to the- * scope since it was enqueued.- */- async queue(batch: MessageBatch<WakePayload>, env: Env): Promise<void> {- const db = createDb(env.DB)- for (const msg of batch.messages) {- try {- await resolveAndLog(db, env, msg.body)- msg.ack()- } catch (err) {- // Transient failure (D1 exception, 5xx / network) — retry with- // backoff. After `max_retries` (wrangler.toml: 3), the message lands- // in the DLQ.- log.warn("wake_dispatch_failed_retrying", {- botUserId: msg.body.botUserId,- messageId: msg.body.messageId,- err: String(err),- })- msg.retry({ delaySeconds: 5 })- }- }- },-- /**- * Dev-only HTTP stand-in for the local Cloudflare Queue. Local Queues- * simulation cannot bridge separate `wrangler dev`/`next dev` processes- * (plans/minimal-wake-queue-unread-notice.md), so `src/web`'s- * `wake-transport.ts` calls this route (via the `WAKE_WORKER` service- * binding, `NODE_ENV === "development"` only) instead of- * `WAKE_QUEUE.sendBatch(...)`. Body is a JSON `WakePayload[]` — same shape- * a queue batch's message bodies would carry. Runs the SAME- * `resolveAndLog`/`dispatchOneUnreadWake` real orchestration `queue()`- * does, including the real D1 read and the real forward to `alook-ws-do`- * — this is the actual worker process handling actual wake candidates,- * not a simulation of it. There is no durable queue behind this dev path:- * candidates get bounded in-process retries and exhausted stable keys are- * returned visibly as a 207 partial result. A partial result is deliberately- * not a 5xx because the caller's binding/HTTP fallback would otherwise- * replay the full batch and duplicate already-successful siblings.- */- async fetch(request: Request, env: Env): Promise<Response> {- const url = new URL(request.url)- if (url.pathname === "/health" && request.method === "GET") {- return Response.json({ status: "ok" })- }-- if (request.method !== "POST") return new Response("method not allowed", { status: 405 })-- let payloads: WakePayload[]- try {- payloads = await request.json()- } catch {- return new Response("invalid json body", { status: 400 })- }-- const db = createDb(env.DB)- const uniquePayloads = dedupeWakePayloads(payloads)- const results = await Promise.all(- uniquePayloads.map(async (item) => ({ item, resolved: await resolveDevHttpCandidate(db, env, item) })),- )- const failed = results.filter((result) => !result.resolved).map((result) => result.item)- if (failed.length > 0) return Response.json({ failed }, { status: 207 })-- return new Response(null, { status: 202 })- },-}diff --git a/src/wake-worker/test-runtime/worker.runtime.test.ts b/src/wake-worker/test-runtime/worker.runtime.test.tsdeleted file mode 100644index 0e3fe4df8..000000000--- a/src/wake-worker/test-runtime/worker.runtime.test.ts+++ /dev/null@@ -1,67 +0,0 @@-/// <reference types="@cloudflare/vitest-plugin/types" />--import type { WakePayload } from "@alook/shared"-import { env, exports } from "cloudflare:workers"-import { describe, expect, it } from "vitest"--type RuntimeQueueMessage<T> = {- id: string- timestamp: Date- attempts: number- body: T-}--type RuntimeQueueResult = {- outcome: string- explicitAcks: string[]- retryMessages: Array<{ msgId: string }>-}--const runtimeEnv = env as unknown as { DB: D1Database }-const worker = (exports as unknown as {- default: {- fetch(request: Request): Promise<Response>- queue(queueName: string, messages: RuntimeQueueMessage<WakePayload>[]): Promise<RuntimeQueueResult>- }-}).default--describe("wake-worker workerd runtime", () => {- it("loads production migrations and serves the production entrypoint", async () => {- const schema = await runtimeEnv.DB.prepare(- "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",- ).bind("community_message").first<{ name: string }>()- expect(schema?.name).toBe("community_message")-- const response = await worker.fetch(new Request("https://worker.test/health"))- expect(response.status).toBe(200)- await expect(response.json()).resolves.toEqual({ status: "ok" })- })-- it("rejects invalid JSON and non-POST dev requests at the real entrypoint", async () => {- const malformed = await worker.fetch(new Request("https://worker.test/", {- method: "POST",- body: "not json",- }))- expect(malformed.status).toBe(400)-- const method = await worker.fetch(new Request("https://worker.test/"))- expect(method.status).toBe(405)- })-- it("acks a permanent D1 miss through the real queue entrypoint", async () => {- const id = `runtime-${crypto.randomUUID()}`- const result = await worker.queue("alook-wake", [{- id,- timestamp: new Date(),- attempts: 1,- body: {- messageId: `missing-message-${crypto.randomUUID()}`,- botUserId: `missing-bot-${crypto.randomUUID()}`,- },- }])-- expect(result.outcome).toBe("ok")- expect(result.explicitAcks).toContain(id)- expect(result.retryMessages).toEqual([])- })-})diff --git a/src/web/.dev.vars.example b/src/web/.dev.vars.exampleindex 88ca68089..5a667104b 100644--- a/src/web/.dev.vars.example+++ b/src/web/.dev.vars.example@@ -10,7 +10,7 @@BETTER_AUTH_SECRET=BETTER_AUTH_URL=http://localhost:3000-# Encryption key for IMAP/SMTP credentials (generate with: openssl rand -base64 32)+# Encryption key for credentials and device tokens (generate with: openssl rand -base64 32)ENCRYPTION_KEY=# GitHub OAuth App (https://github.com/settings/developers)diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.tsindex 19e6192c7..18d51c79f 100644--- a/src/web/cloudflare-env.d.ts+++ b/src/web/cloudflare-env.d.ts@@ -1,5 +1,5 @@/* eslint-disable */-// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example --env-interface=CloudflareEnv cloudflare-env.d.ts` (hash: 53b69659a969e5ead1c93192f0067aae)+// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example --env-interface=CloudflareEnv cloudflare-env.d.ts` (hash: c941b18ab73ccc416dc399c07bd9d67d)// Runtime types generated with [email protected] 2026-09-07 global_fetch_strictly_public,nodejs_compatinterface __BaseEnv_CloudflareEnv {CACHE_KV: KVNamespace;@@ -9,7 +9,7 @@ interface __BaseEnv_CloudflareEnv {BUG_REPORTS: R2Bucket;NEXT_TAG_CACHE_D1: D1Database;DB: D1Database;- WAKE_QUEUE: Queue;+ TASK_QUEUE: Queue;ASSETS: Fetcher;RUNTIME_MODEL_OPTIONS: "{\"claude\":[\"claude-opus-4-6\",\"claude-sonnet-4-6\",\"claude-haiku-4-5\"],\"codex\":[\"gpt-5.4\",\"gpt-5.3-codex\"]}";MIN_CLI_VERSION: "0.0.159";@@ -31,7 +31,7 @@ interface __BaseEnv_CloudflareEnv {WS_DO_WORKER: Fetcher /* alook-ws-do */;EMAIL_WORKER: Fetcher /* alook-email-worker */;BLOG_WORKER: Fetcher /* alook-blog */;- WAKE_WORKER: Fetcher /* alook-wake-worker */;+ QUEUE_WORKER: Fetcher /* alook-queue-worker */;}declare namespace Cloudflare {interface GlobalProps {diff --git a/src/web/migrations/0102_community_push_device.sql b/src/web/migrations/0102_community_push_device.sqlnew file mode 100644index 000000000..f941b1a23--- /dev/null+++ b/src/web/migrations/0102_community_push_device.sql@@ -0,0 +1,31 @@+CREATE TABLE community_push_device (+ id TEXT PRIMARY KEY NOT NULL,+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ installation_id TEXT NOT NULL,+ platform TEXT NOT NULL CONSTRAINT ck_push_device_platform+ CHECK (platform IN ('ios', 'android')),+ provider_environment TEXT NOT NULL CONSTRAINT ck_push_device_provider_environment+ CHECK (provider_environment IN ('sandbox', 'production')),+ provider_token_encrypted TEXT NOT NULL,+ provider_token_hash TEXT NOT NULL CONSTRAINT ck_push_device_token_hash+ CHECK (+ length(provider_token_hash) = 64+ AND provider_token_hash NOT GLOB '*[^0-9a-f]*'+ ),+ app_version TEXT,+ last_seen_at TEXT NOT NULL,+ disabled_at TEXT,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ CONSTRAINT ck_push_device_android_environment+ CHECK (platform = 'ios' OR provider_environment = 'production')+);++CREATE UNIQUE INDEX uq_push_device_installation+ ON community_push_device(installation_id);++CREATE INDEX idx_push_device_user_active+ ON community_push_device(user_id, disabled_at);++CREATE INDEX idx_push_device_token_hash+ ON community_push_device(provider_token_hash);diff --git a/src/web/scripts/opennext-wrangler-config.test.ts b/src/web/scripts/opennext-wrangler-config.test.tsindex cdf164181..98b6a56b5 100644--- a/src/web/scripts/opennext-wrangler-config.test.ts+++ b/src/web/scripts/opennext-wrangler-config.test.ts@@ -32,7 +32,7 @@ describe("OpenNext and Wrangler refresh", () => {"package.json","src/app/package.json","src/email-worker/package.json",- "src/wake-worker/package.json",+ "src/queue-worker/package.json","src/web/package.json","src/ws-do/package.json",]@@ -56,7 +56,7 @@ describe("OpenNext and Wrangler refresh", () => {for (const manifest of ["src/email-worker/package.json","src/shared/package.json",- "src/wake-worker/package.json",+ "src/queue-worker/package.json","src/ws-do/package.json",]) {expect(dependency(manifest, "@cloudflare/workers-types"), manifest)diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.tsindex 299745357..6a6451db1 100644--- a/src/web/src/app/api/community/daemon/resync-wakes/route.ts+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.ts@@ -7,7 +7,7 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"* POST /api/community/daemon/resync-wakes** Daemon-initiated recovery for the "message sent while the daemon was- * offline" gap: `WAKE_QUEUE`'s consumer acks (never retries) a wake whose+ * offline" gap: the queue consumer acks (never retries) a wake whose* daemon was unreachable at delivery time (`dispatchOneUnreadWake`'s* `attempted_nowhere` outcome) — that queue item is gone for good. Rather* than the server pushing a catch-up wake on its own when the daemon's WS@@ -17,7 +17,7 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"** This route decides nothing new about addressing/config — for every bot* bound to `ctx.machineId` with pending unread, it calls the SAME- * `dispatchOneUnreadWake` the real `alook-wake-worker` queue consumer uses,+ * `dispatchOneUnreadWake` the real `alook-queue-worker` queue consumer uses,* which re-reads current D1 state and forwards a freshly built `agent:wake`.* Because the daemon's WS just connected, `sendWakeToMachine` finds a live* socket this time and delivers immediately.diff --git a/src/web/src/app/api/community/notifications/devices/[installationId]/route.test.ts b/src/web/src/app/api/community/notifications/devices/[installationId]/route.test.tsnew file mode 100644index 000000000..6c52332da--- /dev/null+++ b/src/web/src/app/api/community/notifications/devices/[installationId]/route.test.ts@@ -0,0 +1,111 @@+import { NextRequest } from "next/server";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ actor: { kind: "human", userId: "session-user" } as+ | { kind: "human"; userId: string }+ | { kind: "bot"; userId: string },+ db: { primary: true },+ disablePushDevice: vi.fn(),+ params: { installationId: "installation-123" } as Record<string, string>,+ withCommunityActor: vi.fn(+ (handler: (req: NextRequest, ctx: Record<string, unknown>) => Promise<Response>) =>+ async (req: NextRequest) => handler(req, {+ env: { DB: {} },+ actor: mocks.actor,+ params: mocks.params,+ }),+ ),+}));++vi.mock("@/lib/db", () => ({+ getPrimaryDb: vi.fn(() => mocks.db),+}));++vi.mock("@alook/shared", () => ({+ queries: {+ communityPushDevice: {+ disablePushDevice: (...args: unknown[]) =>+ mocks.disablePushDevice(...args),+ },+ },+}));++vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: mocks.withCommunityActor,+}));++import { DELETE } from "./route";++function request(headers: Record<string, string> = {}) {+ return new NextRequest(+ "https://alook.ai/api/community/notifications/devices/installation-123",+ {+ method: "DELETE",+ headers: { Origin: "https://alook.ai", ...headers },+ },+ );+}++describe("DELETE /api/community/notifications/devices/:installationId", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-09-12T00:00:00.000Z"));+ mocks.actor = { kind: "human", userId: "session-user" };+ mocks.params = { installationId: "installation-123" };+ mocks.disablePushDevice.mockResolvedValue(true);+ });++ it("scopes a decoded installation id to the current session user", async () => {+ mocks.params = { installationId: "safe%3Ainstallation_123" };++ const response = await DELETE(request());++ expect(response.status).toBe(204);+ expect(await response.text()).toBe("");+ expect(mocks.disablePushDevice).toHaveBeenCalledWith(mocks.db, {+ userId: "session-user",+ installationId: "safe:installation_123",+ now: "2026-09-12T00:00:00.000Z",+ });+ });++ it.each([+ ["authorization header", { Authorization: "Bearer al_fake" }, "human"],+ ["bot actor", {}, "bot"],+ ["cross origin", { Origin: "https://evil.example" }, "human"],+ ] as const)("rejects %s before persistence", async (_name, headers, actorKind) => {+ mocks.actor = actorKind === "bot"+ ? { kind: "bot", userId: "bot-user" }+ : { kind: "human", userId: "session-user" };++ const response = await DELETE(request(headers));++ expect(response.status).toBe(+ _name === "authorization header" ? 401 : 403,+ );+ expect(mocks.disablePushDevice).not.toHaveBeenCalled();+ });++ it.each([undefined, "bad id", "%E0%A4%A"])(+ "rejects an invalid path id %s",+ async (installationId) => {+ mocks.params = installationId === undefined ? {} : { installationId };++ const response = await DELETE(request());++ expect(response.status).toBe(400);+ expect(mocks.disablePushDevice).not.toHaveBeenCalled();+ },+ );++ it("returns the same empty 204 for disabled, missing, or foreign rows", async () => {+ mocks.disablePushDevice.mockResolvedValue(false);++ const response = await DELETE(request());++ expect(response.status).toBe(204);+ expect(await response.text()).toBe("");+ });+});diff --git a/src/web/src/app/api/community/notifications/devices/[installationId]/route.ts b/src/web/src/app/api/community/notifications/devices/[installationId]/route.tsnew file mode 100644index 000000000..532969946--- /dev/null+++ b/src/web/src/app/api/community/notifications/devices/[installationId]/route.ts@@ -0,0 +1,41 @@+import { queries } from "@alook/shared";+import { getPrimaryDb } from "@/lib/db";+import {+ isCookieHumanSameOrigin,+ notificationDeviceInstallationIdSchema,+} from "@/lib/community/notification-device-schema";+import { withCommunityActor } from "@/lib/middleware/community-actor";+import { writeError } from "@/lib/middleware/helpers";++export const DELETE = withCommunityActor(async (req, ctx) => {+ if (req.headers.has("Authorization")) return writeError("unauthorized", 401);+ if (ctx.actor.kind !== "human") return writeError("forbidden", 403);+ if (!isCookieHumanSameOrigin(req)) return writeError("forbidden", 403);++ const rawInstallationId = ctx.params?.installationId;+ if (!rawInstallationId) return writeError("installation id is required", 400);++ let installationId: string;+ try {+ installationId = decodeURIComponent(rawInstallationId);+ } catch {+ return writeError("invalid installation id", 400);+ }++ const parsedInstallationId =+ notificationDeviceInstallationIdSchema.safeParse(installationId);+ if (!parsedInstallationId.success) {+ return writeError("invalid installation id", 400);+ }++ await queries.communityPushDevice.disablePushDevice(+ getPrimaryDb(ctx.env.DB),+ {+ userId: ctx.actor.userId,+ installationId: parsedInstallationId.data,+ now: new Date().toISOString(),+ },+ );++ return new Response(null, { status: 204 });+});diff --git a/src/web/src/app/api/community/notifications/devices/route.test.ts b/src/web/src/app/api/community/notifications/devices/route.test.tsnew file mode 100644index 000000000..59ce02d33--- /dev/null+++ b/src/web/src/app/api/community/notifications/devices/route.test.ts@@ -0,0 +1,188 @@+import { decrypt } from "@alook/shared/crypto";+import { NextRequest } from "next/server";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ db: { primary: true },+ registerPushDevice: vi.fn(),+ withCookieHumanAuth: vi.fn(+ (handler: (req: NextRequest, ctx: Record<string, unknown>) => Promise<Response>) =>+ async (req: NextRequest) => handler(req, {+ env: {+ DB: {},+ ENCRYPTION_KEY: "fake-encryption-key",+ },+ userId: "session-user",+ email: "[email protected]",+ }),+ ),+}));++vi.mock("@/lib/db", () => ({+ getPrimaryDb: vi.fn(() => mocks.db),+}));++vi.mock("@alook/shared", () => ({+ queries: {+ communityPushDevice: {+ registerPushDevice: (...args: unknown[]) =>+ mocks.registerPushDevice(...args),+ },+ },+}));++vi.mock("@/lib/middleware/auth", () => ({+ withCookieHumanAuth: mocks.withCookieHumanAuth,+}));++import { POST } from "./route";++const cookieHumanHandler = mocks.withCookieHumanAuth.mock.calls[0]![0] as (+ req: NextRequest,+ ctx: Record<string, unknown>,+) => Promise<Response>;++const token = "fake-provider-token-123";+const previousToken = "fake-previous-token-123";++function request(body: string, headers: Record<string, string> = {}) {+ return new NextRequest(+ "https://alook.ai/api/community/notifications/devices",+ {+ method: "POST",+ body,+ headers: {+ "Content-Type": "application/json",+ Origin: "https://alook.ai",+ ...headers,+ },+ },+ );+}++function validBody(overrides: Record<string, unknown> = {}) {+ return JSON.stringify({+ installationId: "installation-123",+ platform: "ios",+ providerEnvironment: "sandbox",+ providerToken: token,+ previousProviderToken: previousToken,+ appVersion: "1.2.3",+ ...overrides,+ });+}++describe("POST /api/community/notifications/devices", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-09-12T00:00:00.000Z"));+ mocks.registerPushDevice.mockResolvedValue({+ ok: true,+ device: {+ installationId: "installation-123",+ platform: "ios",+ providerEnvironment: "sandbox",+ appVersion: "1.2.3",+ lastSeenAt: "2026-09-12T00:00:00.000Z",+ disabledAt: null,+ },+ });+ });++ it("is defined through the cookie-human-only authentication boundary", () => {+ expect(cookieHumanHandler).toEqual(expect.any(Function));+ });++ it("derives identity, hashes, ciphertext, and timestamps on the server", async () => {+ const response = await POST(request(validBody()));++ expect(response.status).toBe(200);+ expect(mocks.registerPushDevice).toHaveBeenCalledWith(+ mocks.db,+ expect.objectContaining({+ userId: "session-user",+ installationId: "installation-123",+ platform: "ios",+ providerEnvironment: "sandbox",+ providerTokenHash:+ "04e7ad517a6cc23fa2c94e37eee8c98fefb772de5d84f73b180c0d344d7c59ac",+ previousProviderTokenHash:+ "6441899ba9e50e8a754691bcd032064634566723d6dcbb5c834fbcfabc4be0dd",+ appVersion: "1.2.3",+ now: "2026-09-12T00:00:00.000Z",+ }),+ );+ const input = mocks.registerPushDevice.mock.calls[0]![1] as {+ providerTokenEncrypted: string;+ };+ expect(input.providerTokenEncrypted).not.toContain(token);+ expect(decrypt(+ input.providerTokenEncrypted,+ "fake-encryption-key",+ )).toBe(token);++ const responseText = await response.text();+ expect(responseText).not.toContain(token);+ expect(responseText).not.toContain(previousToken);+ expect(responseText).not.toContain("fake-encryption-key");+ expect(responseText).not.toContain("04e7ad51");+ });++ it("omits the previous-token proof when the client has no previous token", async () => {+ const response = await POST(request(validBody({ previousProviderToken: undefined })));++ expect(response.status).toBe(200);+ expect(mocks.registerPushDevice).toHaveBeenCalledWith(+ mocks.db,+ expect.objectContaining({ previousProviderTokenHash: undefined }),+ );+ });++ it.each([+ ["malformed JSON", "{"],+ ["unknown user id", validBody({ userId: "other-user" })],+ ["client hash", validBody({ providerTokenHash: "a".repeat(64) })],+ ["invalid Android environment", validBody({+ platform: "android",+ providerEnvironment: "sandbox",+ })],+ ])("rejects %s before persistence", async (_name, body) => {+ const response = await POST(request(body));++ expect(response.status).toBe(400);+ expect(mocks.registerPushDevice).not.toHaveBeenCalled();+ });++ it("fails closed when encryption is not configured", async () => {+ const response = await cookieHumanHandler(request(validBody()), {+ env: { DB: {}, ENCRYPTION_KEY: "" },+ userId: "session-user",+ });++ expect(response.status).toBe(500);+ expect(await response.json()).toEqual({ error: "encryption not configured" });+ expect(mocks.registerPushDevice).not.toHaveBeenCalled();+ });++ it("returns a secret-free conflict without logging", async () => {+ mocks.registerPushDevice.mockResolvedValue({+ ok: false,+ reason: "ownership-conflict",+ });+ const log = vi.spyOn(console, "log").mockImplementation(() => {});+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const error = vi.spyOn(console, "error").mockImplementation(() => {});++ const response = await POST(request(validBody()));+ const responseText = await response.text();++ expect(response.status).toBe(409);+ expect(responseText).toBe('{"error":"device ownership conflict"}');+ expect(responseText).not.toContain(token);+ expect(responseText).not.toContain(previousToken);+ expect(log).not.toHaveBeenCalled();+ expect(warn).not.toHaveBeenCalled();+ expect(error).not.toHaveBeenCalled();+ });+});diff --git a/src/web/src/app/api/community/notifications/devices/route.ts b/src/web/src/app/api/community/notifications/devices/route.tsnew file mode 100644index 000000000..d7d97cefb--- /dev/null+++ b/src/web/src/app/api/community/notifications/devices/route.ts@@ -0,0 +1,46 @@+import { encrypt } from "@alook/shared/crypto";+import { queries } from "@alook/shared";+import { getPrimaryDb } from "@/lib/db";+import {+ hashProviderToken,+ notificationDeviceRegistrationSchema,+} from "@/lib/community/notification-device-schema";+import { withCookieHumanAuth } from "@/lib/middleware/auth";+import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers";++export const POST = withCookieHumanAuth(async (req, ctx) => {+ const [body, error] = await parseBody(+ req,+ notificationDeviceRegistrationSchema,+ );+ if (error) return error;++ const encryptionKey = ctx.env.ENCRYPTION_KEY;+ if (!encryptionKey) return writeError("encryption not configured", 500);++ const [providerTokenHash, previousProviderTokenHash] = await Promise.all([+ hashProviderToken(body.providerToken),+ body.previousProviderToken+ ? hashProviderToken(body.previousProviderToken)+ : undefined,+ ]);+ const now = new Date().toISOString();++ const result = await queries.communityPushDevice.registerPushDevice(+ getPrimaryDb(ctx.env.DB),+ {+ userId: ctx.userId,+ installationId: body.installationId,+ platform: body.platform,+ providerEnvironment: body.providerEnvironment,+ providerTokenEncrypted: encrypt(body.providerToken, encryptionKey),+ providerTokenHash,+ previousProviderTokenHash,+ appVersion: body.appVersion,+ now,+ },+ );++ if (!result.ok) return writeError("device ownership conflict", 409);+ return writeJSON({ device: result.device });+});diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex 69050f4c4..ceedb4bd0 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -10,6 +10,7 @@ import {} from "@/contexts/community/current-user"import { useCommunityWs } from "@/hooks/community/use-community-ws"import { useNotificationSettings } from "@/hooks/community/use-notification-settings"+import { useNativeSystemNotifications } from "@/hooks/community/use-native-system-notifications"import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"import { CommunityOnboardingForm } from "@/components/community/onboarding/community-onboarding-form"import { CommunityWsReconnectBoundary } from "@/components/community/shell/community-ws-reconnect-overlay"@@ -78,6 +79,7 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {const currentUser = useCurrentUser()useNotificationSettings()+ useNativeSystemNotifications(currentUser.id)// Wire the WS handler once for the whole community subtree. `viewerUserId`// powers the `me` flag on incoming reactions — passing null would leave that// flag stuck at false for the viewer's own reactions.diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex ab2700dda..732b3cfbe 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -11,7 +11,7 @@ interface RuntimeEnv {DEVICE_CLIENT_IDS?: stringNODE_ENV?: stringDEV_WS_DO_URL?: string- DEV_WAKE_WORKER_URL?: string+ DEV_QUEUE_WORKER_URL?: stringAPPLE_CLIENT_ID?: stringAPPLE_TEAM_ID?: stringAPPLE_KEY_ID?: string@@ -26,8 +26,8 @@ declare namespace Cloudflare {BUG_REPORTS: R2BucketWS_DO_WORKER: FetcherEMAIL_WORKER: Fetcher- WAKE_QUEUE: Queue<import("@alook/shared").WakePayload>- WAKE_WORKER: Fetcher+ TASK_QUEUE: Queue<import("@alook/shared").AlookQueueTask>+ QUEUE_WORKER: FetcherWORKER_SELF_REFERENCE: FetcherNEXT_INC_CACHE_R2_BUCKET: R2BucketNEXT_TAG_CACHE_D1: D1Databasediff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.tsindex f60890b97..14b4bbe12 100644--- a/src/web/src/hooks/community/community-ws/handler-context.ts+++ b/src/web/src/hooks/community/community-ws/handler-context.ts@@ -46,6 +46,7 @@ export type CommunityWsHandlerContext = CommunityWsDispatchContext & {messageId: stringseq: numbercreatedAt: string+ messageEvent: Extract<CommunityWsEvent, { type: "community:message.create" }>}>messageEvidenceByChannel?: ReadonlyMap<string, {messageId: stringdiff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.tsindex 8e3834faf..b2349c33f 100644--- a/src/web/src/hooks/community/community-ws/registry.test.ts+++ b/src/web/src/hooks/community/community-ws/registry.test.ts@@ -203,4 +203,24 @@ describe("community WebSocket registry", () => {expect(observed).toEqual([1])})++ it("exposes the complete message only to a bump in the same unambiguous bundle", () => {+ handlers.handleUnreadBump.mockClear()+ const create = communityWsEventFixtures["community:message.create"]+ const bump = communityWsEventFixtures["community:unread.bump"]++ dispatchCommunityWsEvents([create, bump], dispatchContext())+ const pairedContext = handlers.handleUnreadBump.mock.calls[0]?.[1] as CommunityWsHandlerContext+ expect(pairedContext.unreadBumpEvidence?.get(bump)).toEqual({+ messageId: create.message.id,+ seq: create.message.seq,+ createdAt: create.message.createdAt,+ messageEvent: create,+ })++ handlers.handleUnreadBump.mockClear()+ dispatchCommunityWsEvents([create, { ...create, message: { ...create.message, id: "message-2" } }, bump], dispatchContext())+ const ambiguousContext = handlers.handleUnreadBump.mock.calls[0]?.[1] as CommunityWsHandlerContext+ expect(ambiguousContext.unreadBumpEvidence?.get(bump)).toBeUndefined()+ })})diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsindex 72387d09c..d391e8eaa 100644--- a/src/web/src/hooks/community/community-ws/registry.ts+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -130,6 +130,7 @@ export function dispatchCommunityWsEvents(messageId: stringseq: numbercreatedAt: string+ messageEvent: Extract<CommunityWsEvent, { type: "community:message.create" }>}>()const messageEvidenceByChannel = new Map<string, {messageId: string@@ -154,6 +155,7 @@ export function dispatchCommunityWsEvents(messageId: message.id,seq: message.seq,createdAt: message.createdAt,+ messageEvent: creates[0]!,})}runCommunityWsProjectionTransaction(context.queryClient, (projection) => {diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.tsindex 3e44ef06a..87d41c05d 100644--- a/src/web/src/hooks/community/community-ws/social-events.test.ts+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts@@ -23,6 +23,14 @@ import {unreadBump,} from "./test-harness"+const notificationMocks = vi.hoisted(() => ({ show: vi.fn(async () => undefined) }))+vi.mock("@/lib/community/desktop-system-notification", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/desktop-system-notification")>(+ "@/lib/community/desktop-system-notification",+ )+ return { ...actual, showDesktopSystemNotification: notificationMocks.show }+})+beforeEach(resetCommunityWsHarness)afterEach(cleanupCommunityWsHarness)@@ -158,6 +166,33 @@ describe("useCommunityWs — account unread projection", () => {capturedOnMessage!(messageCreate("ch_random"))expect(getActiveAccountUnreadProjection(capturedQueryClient).projectServerUnread("s1", [])).toBe(false)+ expect(notificationMocks.show).not.toHaveBeenCalled()+ })++ it("notifies only when message.create and the viewer's unread.bump share one bundle", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const create = messageCreate("dm_1", "message_1")+ capturedOnMessage!(await batchFor("message_1", [+ create,+ unreadBump("dm_1", "u_me"),+ ]))++ await vi.waitFor(() => expect(notificationMocks.show).toHaveBeenCalledOnce())+ expect(notificationMocks.show).toHaveBeenCalledWith(expect.objectContaining({+ viewerUserId: "u_me",+ target: {+ kind: "dm",+ channelId: "dm_1",+ messageId: "message_1",+ seq: 1,+ },+ }))+ })++ it("does not notify for an orphan unread.bump", async () => {+ await mountHook({ viewerUserId: "u_me" })+ capturedOnMessage!(unreadBump("dm_1", "u_me"))+ expect(notificationMocks.show).not.toHaveBeenCalled()})it("syncs focused content without refreshing notification surfaces", async () => {diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.tsindex 6c626d617..a74fa42c8 100644--- a/src/web/src/hooks/community/community-ws/social-events.ts+++ b/src/web/src/hooks/community/community-ws/social-events.ts@@ -24,6 +24,10 @@ import { removeDmReactionDetails } from "./reaction-details-invalidation"import { reconcileNotificationSettings } from "@/hooks/community/use-notification-settings"import { getFriendRequestActionController } from "@/hooks/community/use-friend-request-action-state"import { communityKeys } from "@/lib/query-keys"+import {+ buildDesktopSystemNotificationCandidate,+ showDesktopSystemNotification,+} from "@/lib/community/desktop-system-notification"export function handleReadStateAdvanced(event: CommunityReadStateAdvanced,@@ -91,6 +95,14 @@ export function handleUnreadBump(// Use the existing coalesced owner. This is also the sole authority// refresh for legacy/orphan bumps; the ledger itself performs no I/O.scheduleInboxInvalidate({ inbox: true, dms: !event.serverId })+ if (evidence) {+ const candidate = buildDesktopSystemNotificationCandidate(+ evidence.messageEvent,+ event,+ viewerId,+ )+ if (candidate) void showDesktopSystemNotification(candidate).catch(() => undefined)+ }}}diff --git a/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts b/src/web/src/hooks/community/use-native-system-notifications.dom.test.tsnew file mode 100644index 000000000..7184969ee--- /dev/null+++ b/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts@@ -0,0 +1,483 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import {+ createDesktopSystemNotificationActivationController,+ createDesktopSystemNotificationInboxOpener,+ type DesktopSystemNotificationInboxDeps,+ useNativeSystemNotifications,+} from "./use-native-system-notifications"+import type { DesktopSystemNotificationActivation } from "@/lib/community/system-notification-route"++const hookMocks = vi.hoisted(() => ({+ desktop: true,+ mobile: false,+ listen: vi.fn(),+ take: vi.fn(),+ revalidate: vi.fn(),+ mobileListen: vi.fn(),+ mobileCheck: vi.fn(),+ mobileRequest: vi.fn(),+ mobileSnapshot: vi.fn(),+ mobilePost: vi.fn(),+ mobileAck: vi.fn(),+ mobileDelete: vi.fn(),+ mobileTake: vi.fn(),+ mobileRevalidate: vi.fn(),+}))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ isDesktop: () => hookMocks.desktop,+ isMobile: () => hookMocks.mobile,+ }+})+vi.mock("@/lib/community/desktop-system-notification", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/desktop-system-notification")>(+ "@/lib/community/desktop-system-notification",+ )+ return {+ ...actual,+ listenDesktopSystemNotificationActivations: hookMocks.listen,+ takeDesktopSystemNotificationActivation: hookMocks.take,+ }+})+vi.mock("@/lib/community/system-notification-route", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/system-notification-route")>(+ "@/lib/community/system-notification-route",+ )+ return { ...actual, revalidateDesktopSystemNotificationTarget: hookMocks.revalidate }+})+vi.mock("@/lib/community/mobile-system-notification", async () => {+ const actual = await vi.importActual<typeof import("@/lib/community/mobile-system-notification")>(+ "@/lib/community/mobile-system-notification",+ )+ return {+ ...actual,+ listenMobileSystemNotificationSignals: hookMocks.mobileListen,+ checkMobileSystemNotificationPermission: hookMocks.mobileCheck,+ requestMobileSystemNotificationPermission: hookMocks.mobileRequest,+ snapshotMobileSystemNotificationRegistration: hookMocks.mobileSnapshot,+ postMobileSystemNotificationRegistration: hookMocks.mobilePost,+ acknowledgeMobileSystemNotificationRegistration: hookMocks.mobileAck,+ deleteMobileSystemNotificationRegistration: hookMocks.mobileDelete,+ takeMobileSystemNotificationActivation: hookMocks.mobileTake,+ revalidateMobileSystemNotificationActivation: hookMocks.mobileRevalidate,+ }+})++const activation: DesktopSystemNotificationActivation = {+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ target: {+ kind: "server",+ serverId: "server_1",+ channelId: "channel_1",+ messageId: "message_1",+ seq: 4,+ },+}++afterEach(() => {+ hookMocks.desktop = true+ hookMocks.mobile = false+ window.sessionStorage.clear()+ document.body.replaceChildren()+ vi.useRealTimers()+ vi.unstubAllGlobals()+ vi.clearAllMocks()+})++describe("desktop notification activation controller", () => {+ it("drains a cold-start activation after registering the listener", async () => {+ const calls: string[] = []+ const controller = createDesktopSystemNotificationActivationController({+ listen: vi.fn(async () => { calls.push("listen"); return () => calls.push("unlisten") }),+ take: vi.fn(async () => { calls.push("take"); return activation }),+ revalidate: vi.fn(async () => { calls.push("revalidate"); return true }),+ navigate: vi.fn(() => calls.push("navigate")),+ openInbox: vi.fn(),+ })+ await controller.connect()+ expect(calls).toEqual(["listen", "take", "revalidate", "navigate"])+ controller.dispose()+ expect(calls.at(-1)).toBe("unlisten")+ })++ it("falls back to Inbox when the message is deleted or access is revoked", async () => {+ const openInbox = vi.fn()+ const navigate = vi.fn()+ const controller = createDesktopSystemNotificationActivationController({+ listen: vi.fn(async () => () => undefined),+ take: vi.fn(async () => activation),+ revalidate: vi.fn(async () => false),+ navigate,+ openInbox,+ })+ await controller.connect()+ expect(openInbox).toHaveBeenCalledOnce()+ expect(navigate).not.toHaveBeenCalled()+ })++ it("handles hot activation signals and ignores work after disposal", async () => {+ let ready: (() => void) | undefined+ const take = vi.fn()+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce(activation)+ .mockResolvedValue(null)+ const navigate = vi.fn()+ const controller = createDesktopSystemNotificationActivationController({+ listen: vi.fn(async (callback) => { ready = callback; return () => undefined }),+ take,+ revalidate: vi.fn(async () => true),+ navigate,+ openInbox: vi.fn(),+ })+ await controller.connect()+ ready?.()+ await waitFor(() => expect(navigate).toHaveBeenCalledOnce())+ controller.dispose()+ ready?.()+ await Promise.resolve()+ expect(take).toHaveBeenCalledTimes(2)+ })++ it("reruns a drain when a native signal arrives during an active take", async () => {+ let ready: (() => void) | undefined+ let releaseTake = (_value: DesktopSystemNotificationActivation | null) => undefined+ const firstTake = new Promise<DesktopSystemNotificationActivation | null>((resolve) => {+ releaseTake = resolve+ })+ const take = vi.fn()+ .mockReturnValueOnce(firstTake)+ .mockResolvedValueOnce(null)+ const controller = createDesktopSystemNotificationActivationController({+ listen: vi.fn(async (callback) => { ready = callback; return () => undefined }),+ take,+ revalidate: vi.fn(async () => true),+ navigate: vi.fn(),+ openInbox: vi.fn(),+ })++ const connecting = controller.connect()+ await waitFor(() => expect(take).toHaveBeenCalledOnce())+ ready?.()+ releaseTake(null)+ await connecting+ expect(take).toHaveBeenCalledTimes(2)+ })++ it("stops a listener that resolves after disposal", async () => {+ let releaseListen = (_stop: () => void) => undefined+ const listener = new Promise<() => void>((resolve) => { releaseListen = resolve })+ const stop = vi.fn()+ const controller = createDesktopSystemNotificationActivationController({+ listen: vi.fn(() => listener),+ take: vi.fn(),+ revalidate: vi.fn(),+ navigate: vi.fn(),+ openInbox: vi.fn(),+ })++ const connecting = controller.connect()+ controller.dispose()+ releaseListen(stop)+ await connecting+ expect(stop).toHaveBeenCalledOnce()+ })+})++function inboxDeps(+ pending: Map<string, string>,+ overrides: Partial<DesktopSystemNotificationInboxDeps> = {},+): DesktopSystemNotificationInboxDeps {+ return {+ getItem: (key) => pending.get(key) ?? null,+ setItem: (key, value) => pending.set(key, value),+ removeItem: (key) => { pending.delete(key) },+ findTrigger: () => null,+ navigateToCommunity: vi.fn(),+ wait: async () => undefined,+ now: () => 1_000,+ pollAttempts: 2,+ ...overrides,+ }+}++describe("desktop notification Inbox fallback", () => {+ it("keeps a timed-out intent for remount, navigates once, and clears only after a real click", async () => {+ const pending = new Map<string, string>()+ const firstNavigate = vi.fn()+ const first = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {+ navigateToCommunity: firstNavigate,+ }))++ await first.open()+ expect(firstNavigate).toHaveBeenCalledOnce()+ expect([...pending.values()].map((value) => JSON.parse(value))).toEqual([+ { version: 1, expiresAt: 301_000, navigationStarted: true },+ ])+ await first.open()+ expect(firstNavigate).toHaveBeenCalledOnce()+ first.dispose()++ const remountNavigate = vi.fn()+ const click = vi.fn()+ const remount = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {+ findTrigger: () => ({ click }),+ navigateToCommunity: remountNavigate,+ }))+ await remount.resume()+ expect(click).toHaveBeenCalledOnce()+ expect(remountNavigate).not.toHaveBeenCalled()+ expect(pending.size).toBe(0)+ })++ it("consumes a trigger that mounts late without navigating", async () => {+ const pending = new Map<string, string>()+ const click = vi.fn()+ const navigate = vi.fn()+ let probes = 0+ const opener = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {+ findTrigger: () => (++probes === 2 ? { click } : null),+ navigateToCommunity: navigate,+ }))++ await opener.open()+ expect(click).toHaveBeenCalledOnce()+ expect(navigate).not.toHaveBeenCalled()+ expect(pending.size).toBe(0)+ })++ it("cleans corrupt or expired state and has no side effects after disposal", async () => {+ const pending = new Map([["alook:desktop-system-notification:inbox-intent", "corrupt"]])+ const navigate = vi.fn()+ const opener = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {+ navigateToCommunity: navigate,+ }))+ await opener.resume()+ expect(pending.size).toBe(0)++ pending.set("alook:desktop-system-notification:inbox-intent", JSON.stringify({+ version: 1,+ expiresAt: 999,+ navigationStarted: false,+ }))+ await opener.resume()+ expect(pending.size).toBe(0)++ let releaseWait = () => undefined+ const wait = new Promise<void>((resolve) => { releaseWait = resolve })+ const click = vi.fn()+ let triggerReady = false+ const active = createDesktopSystemNotificationInboxOpener(inboxDeps(pending, {+ findTrigger: () => (triggerReady ? { click } : null),+ navigateToCommunity: navigate,+ wait: () => wait,+ }))+ const opening = active.open()+ await Promise.resolve()+ triggerReady = true+ active.dispose()+ releaseWait()+ await opening+ expect(click).not.toHaveBeenCalled()+ expect(navigate).not.toHaveBeenCalled()+ expect(pending.size).toBe(1)+ })++ it("treats storage failures as unavailable persistence", async () => {+ const removeFailure = createDesktopSystemNotificationInboxOpener(inboxDeps(new Map(), {+ getItem: () => "corrupt",+ removeItem: () => { throw new Error("blocked") },+ }))+ await removeFailure.resume()++ const readFailure = createDesktopSystemNotificationInboxOpener(inboxDeps(new Map(), {+ getItem: () => { throw new Error("blocked") },+ }))+ await readFailure.resume()++ const writeFailure = createDesktopSystemNotificationInboxOpener(inboxDeps(new Map(), {+ setItem: () => { throw new Error("blocked") },+ }))+ await writeFailure.open()+ })+})++describe("native system notification hook", () => {+ it("does nothing in the browser", () => {+ hookMocks.desktop = false+ const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))+ expect(hookMocks.listen).not.toHaveBeenCalled()+ rendered.unmount()+ })++ it("navigates an allowed activation and disposes the native listener", async () => {+ const assign = vi.fn()+ const stop = vi.fn()+ vi.stubGlobal("location", { href: "https://alook.test/c", assign })+ hookMocks.listen.mockResolvedValue(stop)+ hookMocks.take.mockResolvedValueOnce(activation)+ hookMocks.revalidate.mockResolvedValue(true)++ const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))+ await waitFor(() => expect(assign).toHaveBeenCalledWith(+ "/c/channels/server_1/channel_1?msg=message_1",+ ))+ expect(hookMocks.revalidate).toHaveBeenCalledWith(activation.target)++ rendered.unmount()+ expect(stop).toHaveBeenCalledOnce()+ })++ it("persists an Inbox fallback, resumes it, and clears it after a real click", async () => {+ vi.useFakeTimers()+ const assign = vi.fn()+ const stop = vi.fn()+ vi.stubGlobal("location", { href: "https://alook.test/c/channels/server_1/channel_1", assign })+ hookMocks.listen.mockResolvedValue(stop)+ hookMocks.take.mockResolvedValueOnce(activation).mockResolvedValue(null)+ hookMocks.revalidate.mockResolvedValue(false)++ const first = renderHook(() => useNativeSystemNotifications("viewer_1"))+ await act(async () => {+ await Promise.resolve()+ await vi.advanceTimersByTimeAsync(2_000)+ })+ expect(assign).toHaveBeenCalledWith("https://alook.test/c")+ first.unmount()++ const button = document.createElement("button")+ button.setAttribute("aria-label", "Inbox")+ const click = vi.spyOn(button, "click")+ document.body.append(button)+ const second = renderHook(() => useNativeSystemNotifications("viewer_1"))+ await act(async () => { await Promise.resolve() })+ expect(click).toHaveBeenCalledOnce()+ expect(window.sessionStorage.length).toBe(0)+ second.unmount()+ })++ it("disposes the controller when native listener setup rejects", async () => {+ hookMocks.listen.mockRejectedValue(new Error("native unavailable"))+ hookMocks.take.mockResolvedValue(null)+ const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))+ await act(async () => { await Promise.resolve() })+ expect(hookMocks.listen).toHaveBeenCalledOnce()+ rendered.unmount()+ })++ it("uses one mobile listener for Web-ready registration and activation signals", async () => {+ hookMocks.desktop = false+ hookMocks.mobile = true+ const calls: string[] = []+ const assign = vi.fn()+ const stop = vi.fn()+ let signal: (() => void) | undefined+ vi.stubGlobal("location", { href: "https://alook.test/c", assign })+ hookMocks.mobileListen.mockImplementation(async (callback) => {+ calls.push("listen")+ signal = callback+ return stop+ })+ hookMocks.mobileCheck.mockImplementation(async () => { calls.push("check"); return "granted" })+ hookMocks.mobileSnapshot.mockImplementation(async () => {+ calls.push("snapshot")+ return {+ installationId: "123e4567-e89b-42d3-a456-426614174000",+ platform: "ios",+ providerEnvironment: "sandbox",+ providerToken: "token-00000000000",+ }+ })+ hookMocks.mobilePost.mockImplementation(async () => { calls.push("post") })+ hookMocks.mobileAck.mockImplementation(async () => { calls.push("ack") })+ hookMocks.mobileTake+ .mockImplementationOnce(async () => {+ calls.push("take")+ return {+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ messageId: "message_1",+ targetId: "channel_1",+ }+ })+ .mockImplementationOnce(async () => {+ calls.push("take")+ return {+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ messageId: "message_2",+ targetId: "channel_1",+ }+ })+ .mockImplementation(async () => { calls.push("take"); return null })+ hookMocks.mobileRevalidate+ .mockResolvedValueOnce({ href: "/c/me/channel_1?seq=9" })+ .mockResolvedValueOnce(null)++ const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))+ await waitFor(() => expect(calls).toEqual([+ "listen",+ "check",+ "take",+ "snapshot",+ "post",+ "ack",+ ]))+ expect(hookMocks.mobileListen).toHaveBeenCalledOnce()+ expect(assign).toHaveBeenCalledWith("/c/me/channel_1?seq=9")++ const button = document.createElement("button")+ button.setAttribute("aria-label", "Inbox")+ const click = vi.spyOn(button, "click")+ document.body.append(button)+ const visibilityState = vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible")+ document.dispatchEvent(new Event("visibilitychange"))+ await waitFor(() => expect(hookMocks.mobileCheck).toHaveBeenCalledTimes(2))+ expect(hookMocks.mobileTake).toHaveBeenCalledTimes(2)+ expect(click).toHaveBeenCalledOnce()++ signal?.()+ await waitFor(() => expect(hookMocks.mobileCheck).toHaveBeenCalledTimes(3))+ expect(hookMocks.mobileTake).toHaveBeenCalledTimes(3)+ rendered.unmount()+ visibilityState.mockRestore()+ expect(stop).toHaveBeenCalledOnce()+ })++ it("schedules and cancels a mobile registration retry", async () => {+ hookMocks.desktop = false+ hookMocks.mobile = true+ const stop = vi.fn()+ const setTimeout = vi.spyOn(window, "setTimeout")+ const clearTimeout = vi.spyOn(window, "clearTimeout")+ hookMocks.mobileListen.mockResolvedValue(stop)+ hookMocks.mobileCheck.mockRejectedValue(new Error("offline"))+ hookMocks.mobileTake.mockResolvedValue(null)++ const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))+ await waitFor(() => expect(setTimeout.mock.calls.some(([, delay]) => delay === 1_000)).toBe(true))+ const clearsBeforeUnmount = clearTimeout.mock.calls.length+ rendered.unmount()++ expect(clearTimeout.mock.calls).toHaveLength(clearsBeforeUnmount + 1)+ expect(stop).toHaveBeenCalledOnce()+ })++ it("continues mobile startup when native listener setup rejects", async () => {+ hookMocks.desktop = false+ hookMocks.mobile = true+ hookMocks.mobileListen.mockRejectedValue(new Error("native unavailable"))+ hookMocks.mobileCheck.mockResolvedValue("granted")+ hookMocks.mobileSnapshot.mockResolvedValue({+ installationId: "123e4567-e89b-42d3-a456-426614174000",+ platform: "ios",+ providerEnvironment: "sandbox",+ })+ hookMocks.mobileTake.mockResolvedValue(null)++ const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))+ await waitFor(() => expect(hookMocks.mobileCheck).toHaveBeenCalledOnce())+ expect(hookMocks.mobileTake).toHaveBeenCalledOnce()+ rendered.unmount()+ })+})diff --git a/src/web/src/hooks/community/use-native-system-notifications.ts b/src/web/src/hooks/community/use-native-system-notifications.tsnew file mode 100644index 000000000..f8681db3f--- /dev/null+++ b/src/web/src/hooks/community/use-native-system-notifications.ts@@ -0,0 +1,299 @@+"use client"++import { useEffect } from "react"+import { isDesktop, isMobile } from "@alook/shared"+import {+ listenDesktopSystemNotificationActivations,+ takeDesktopSystemNotificationActivation,+} from "@/lib/community/desktop-system-notification"+import {+ desktopSystemNotificationHref,+ revalidateDesktopSystemNotificationTarget,+ type DesktopSystemNotificationActivation,+} from "@/lib/community/system-notification-route"+import {+ acknowledgeMobileSystemNotificationRegistration,+ checkMobileSystemNotificationPermission,+ createMobileSystemNotificationActivationController,+ createMobileSystemNotificationRegistrationController,+ deleteMobileSystemNotificationRegistration,+ listenMobileSystemNotificationSignals,+ postMobileSystemNotificationRegistration,+ requestMobileSystemNotificationPermission,+ resumeMobileSystemNotificationRegistration,+ revalidateMobileSystemNotificationActivation,+ snapshotMobileSystemNotificationRegistration,+ takeMobileSystemNotificationActivation,+} from "@/lib/community/mobile-system-notification"++export type DesktopSystemNotificationActivationDeps = {+ listen: (ready: () => void) => Promise<() => void>+ take: () => Promise<DesktopSystemNotificationActivation | null>+ revalidate: (activation: DesktopSystemNotificationActivation) => Promise<boolean>+ navigate: (href: string) => void+ openInbox: () => Promise<void> | void+}++type InboxIntent = {+ version: 1+ expiresAt: number+ navigationStarted: boolean+}++export type DesktopSystemNotificationInboxDeps = {+ getItem: (key: string) => string | null+ setItem: (key: string, value: string) => void+ removeItem: (key: string) => void+ findTrigger: () => { click: () => void } | null+ navigateToCommunity: () => void+ wait: () => Promise<void>+ now: () => number+ pollAttempts?: number+}++const INBOX_INTENT_KEY = "alook:desktop-system-notification:inbox-intent"+const INBOX_INTENT_VERSION = 1+const INBOX_INTENT_TTL_MS = 5 * 60 * 1000+const INBOX_POLL_ATTEMPTS = 40++export function createDesktopSystemNotificationInboxOpener(+ deps: DesktopSystemNotificationInboxDeps,+) {+ let disposed = false+ let draining: Promise<void> | null = null++ function removeIntent() {+ try {+ deps.removeItem(INBOX_INTENT_KEY)+ } catch {+ return+ }+ }++ function readIntent(): InboxIntent | null {+ let raw: string | null+ try {+ raw = deps.getItem(INBOX_INTENT_KEY)+ } catch {+ return null+ }+ if (raw === null) return null+ try {+ const value = JSON.parse(raw) as Partial<InboxIntent>+ if (+ value.version !== INBOX_INTENT_VERSION+ || typeof value.expiresAt !== "number"+ || !Number.isFinite(value.expiresAt)+ || value.expiresAt <= deps.now()+ || typeof value.navigationStarted !== "boolean"+ || Object.keys(value).some((key) => !["version", "expiresAt", "navigationStarted"].includes(key))+ ) {+ removeIntent()+ return null+ }+ return value as InboxIntent+ } catch {+ removeIntent()+ return null+ }+ }++ function writeIntent(intent: InboxIntent) {+ try {+ deps.setItem(INBOX_INTENT_KEY, JSON.stringify(intent))+ return true+ } catch {+ return false+ }+ }++ function queueIntent() {+ if (readIntent()) return true+ return writeIntent({+ version: INBOX_INTENT_VERSION,+ expiresAt: deps.now() + INBOX_INTENT_TTL_MS,+ navigationStarted: false,+ })+ }++ function consume() {+ if (draining) return draining+ draining = (async () => {+ const attempts = Math.max(1, deps.pollAttempts ?? INBOX_POLL_ATTEMPTS)+ for (let attempt = 0; attempt < attempts; attempt += 1) {+ if (disposed || !readIntent()) return+ const trigger = deps.findTrigger()+ if (trigger) {+ if (disposed) return+ trigger.click()+ removeIntent()+ return+ }+ if (attempt + 1 < attempts) await deps.wait()+ }+ if (disposed) return+ const intent = readIntent()+ if (!intent || intent.navigationStarted) return+ if (!writeIntent({ ...intent, navigationStarted: true })) return+ deps.navigateToCommunity()+ })().finally(() => {+ draining = null+ })+ return draining+ }++ return {+ async open() {+ if (disposed || !queueIntent()) return+ await consume()+ },+ async resume() {+ if (disposed || !readIntent()) return+ await consume()+ },+ dispose() {+ disposed = true+ },+ }+}++export function createDesktopSystemNotificationActivationController(+ deps: DesktopSystemNotificationActivationDeps,+) {+ let disposed = false+ let draining = false+ let rerun = false+ let unlisten: (() => void) | undefined++ async function drain() {+ if (disposed) return+ if (draining) {+ rerun = true+ return+ }+ draining = true+ try {+ do {+ rerun = false+ const activation = await deps.take().catch(() => null)+ if (!activation || disposed) continue+ const allowed = await deps.revalidate(activation).catch(() => false)+ if (disposed) continue+ if (allowed) deps.navigate(desktopSystemNotificationHref(activation.target))+ else await deps.openInbox()+ } while (rerun && !disposed)+ } finally {+ draining = false+ }+ }++ return {+ async connect() {+ const stop = await deps.listen(() => { void drain() })+ if (disposed) {+ stop()+ return+ }+ unlisten = stop+ await drain()+ },+ dispose() {+ if (disposed) return+ disposed = true+ unlisten?.()+ unlisten = undefined+ },+ }+}++export function useNativeSystemNotifications(viewerUserId: string) {+ useEffect(() => {+ const inbox = createDesktopSystemNotificationInboxOpener({+ getItem: (key) => window.sessionStorage.getItem(key),+ setItem: (key, value) => window.sessionStorage.setItem(key, value),+ removeItem: (key) => window.sessionStorage.removeItem(key),+ findTrigger: () => document.querySelector<HTMLButtonElement>(+ 'button[aria-label="Inbox"], button[aria-label="Open Inbox"]',+ ),+ navigateToCommunity: () => window.location.assign(new URL("/c", window.location.href).href),+ wait: () => new Promise<void>((resolve) => window.setTimeout(resolve, 50)),+ now: () => Date.now(),+ })++ if (isDesktop()) {+ const browserDeps: DesktopSystemNotificationActivationDeps = {+ listen: listenDesktopSystemNotificationActivations,+ take: takeDesktopSystemNotificationActivation,+ revalidate: ({ target }) => revalidateDesktopSystemNotificationTarget(target),+ navigate: (href) => window.location.assign(href),+ openInbox: () => inbox.open(),+ }+ const controller = createDesktopSystemNotificationActivationController(browserDeps)+ void inbox.resume()+ void controller.connect().catch(() => controller.dispose())+ return () => {+ controller.dispose()+ inbox.dispose()+ }+ }++ if (!isMobile()) {+ inbox.dispose()+ return+ }++ resumeMobileSystemNotificationRegistration()++ const registration = createMobileSystemNotificationRegistrationController({+ checkPermission: checkMobileSystemNotificationPermission,+ requestPermission: requestMobileSystemNotificationPermission,+ snapshot: snapshotMobileSystemNotificationRegistration,+ register: postMobileSystemNotificationRegistration,+ acknowledge: acknowledgeMobileSystemNotificationRegistration,+ unregister: deleteMobileSystemNotificationRegistration,+ schedule: (callback, delayMs) => window.setTimeout(callback, delayMs),+ cancel: (handle) => window.clearTimeout(handle as number),+ })+ const activation = createMobileSystemNotificationActivationController({+ take: takeMobileSystemNotificationActivation,+ revalidate: revalidateMobileSystemNotificationActivation,+ navigate: (href) => window.location.assign(href),+ openInbox: () => inbox.open(),+ })+ let disposed = false+ let unlisten: (() => void) | undefined++ const synchronize = () => {+ void registration.sync()+ void activation.drain()+ }+ const onVisibilityChange = () => {+ if (document.visibilityState === "visible") synchronize()+ }+ window.addEventListener("online", synchronize)+ document.addEventListener("visibilitychange", onVisibilityChange)++ void inbox.resume()+ void (async () => {+ try {+ const stop = await listenMobileSystemNotificationSignals(synchronize)+ if (disposed) stop()+ else unlisten = stop+ } catch {+ unlisten = undefined+ }+ if (disposed) return+ await Promise.all([registration.sync(true), activation.drain()])+ })()++ return () => {+ disposed = true+ window.removeEventListener("online", synchronize)+ document.removeEventListener("visibilitychange", onVisibilityChange)+ unlisten?.()+ registration.dispose()+ activation.dispose()+ inbox.dispose()+ }+ }, [viewerUserId])+}diff --git a/src/web/src/lib/auth-client.test.ts b/src/web/src/lib/auth-client.test.tsnew file mode 100644index 000000000..408cef914--- /dev/null+++ b/src/web/src/lib/auth-client.test.ts@@ -0,0 +1,75 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ underlyingSignOut: vi.fn(),+ resume: vi.fn(),+ suspend: vi.fn(),+ unregister: vi.fn(),+}))++vi.mock("better-auth/react", () => ({+ createAuthClient: () => ({+ signIn: {},+ signUp: {},+ signOut: mocks.underlyingSignOut,+ useSession: vi.fn(),+ }),+}))++vi.mock("better-auth/client/plugins", () => ({+ emailOTPClient: vi.fn(() => ({})),+ deviceAuthorizationClient: vi.fn(() => ({})),+}))++vi.mock("@/lib/community/mobile-system-notification", () => ({+ resumeMobileSystemNotificationRegistration: mocks.resume,+ suspendMobileSystemNotificationRegistration: mocks.suspend,+ unregisterCurrentMobileSystemNotification: mocks.unregister,+}))++import { signOut } from "./auth-client"++beforeEach(() => {+ vi.clearAllMocks()+ mocks.unregister.mockResolvedValue(undefined)+ mocks.underlyingSignOut.mockResolvedValue({ data: null, error: null })+})++describe("auth client sign out", () => {+ it("deletes the mobile installation before clearing the old session", async () => {+ const calls: string[] = []+ mocks.unregister.mockImplementation(async () => { calls.push("delete") })+ mocks.underlyingSignOut.mockImplementation(async () => {+ calls.push("sign-out")+ return { data: null, error: null }+ })++ await signOut()+ expect(calls).toEqual(["delete", "sign-out"])+ expect(mocks.suspend).toHaveBeenCalledOnce()+ expect(mocks.resume).not.toHaveBeenCalled()+ })++ it("keeps logout best-effort when mobile cleanup is unavailable", async () => {+ mocks.unregister.mockRejectedValue(new Error("native unavailable"))+ await expect(signOut()).resolves.toEqual({ data: null, error: null })+ expect(mocks.underlyingSignOut).toHaveBeenCalledOnce()+ expect(mocks.resume).not.toHaveBeenCalled()+ })++ it("resumes mobile registration when sign out returns an error", async () => {+ const result = { data: null, error: { message: "auth failed" } }+ mocks.underlyingSignOut.mockResolvedValue(result)++ await expect(signOut()).resolves.toBe(result)+ expect(mocks.resume).toHaveBeenCalledOnce()+ })++ it("resumes mobile registration when sign out throws", async () => {+ const error = new Error("auth failed")+ mocks.underlyingSignOut.mockRejectedValue(error)++ await expect(signOut()).rejects.toBe(error)+ expect(mocks.resume).toHaveBeenCalledOnce()+ })+})diff --git a/src/web/src/lib/auth-client.ts b/src/web/src/lib/auth-client.tsindex ae6e9dfa8..b97ca640e 100644--- a/src/web/src/lib/auth-client.ts+++ b/src/web/src/lib/auth-client.ts@@ -1,10 +1,28 @@"use client"import { createAuthClient } from "better-auth/react"import { emailOTPClient, deviceAuthorizationClient } from "better-auth/client/plugins"+import {+ resumeMobileSystemNotificationRegistration,+ suspendMobileSystemNotificationRegistration,+ unregisterCurrentMobileSystemNotification,+} from "@/lib/community/mobile-system-notification"export const authClient = createAuthClient({baseURL: process.env.NEXT_PUBLIC_APP_URL || "",plugins: [emailOTPClient(), deviceAuthorizationClient()],})-export const { signIn, signUp, signOut, useSession } = authClient+export const { signIn, signUp, useSession } = authClient++export const signOut: typeof authClient.signOut = async (...args) => {+ suspendMobileSystemNotificationRegistration()+ await unregisterCurrentMobileSystemNotification().catch(() => undefined)+ try {+ const result = await authClient.signOut(...args)+ if ("error" in result && result.error) resumeMobileSystemNotificationRegistration()+ return result+ } catch (error) {+ resumeMobileSystemNotificationRegistration()+ throw error+ }+}diff --git a/src/web/src/lib/community/desktop-system-notification.test.ts b/src/web/src/lib/community/desktop-system-notification.test.tsnew file mode 100644index 000000000..579ff552f--- /dev/null+++ b/src/web/src/lib/community/desktop-system-notification.test.ts@@ -0,0 +1,176 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import type { CommunityMessageCreate, CommunityWsEvent } from "@alook/shared"+import {+ buildDesktopSystemNotificationCandidate,+ listenDesktopSystemNotificationActivations,+ showDesktopSystemNotification,+ takeDesktopSystemNotificationActivation,+} from "./desktop-system-notification"++const invoke = vi.hoisted(() => vi.fn())+const desktopMode = vi.hoisted(() => ({ value: true }))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return { ...actual, isDesktop: vi.fn(() => desktopMode.value), tauriInvoke: invoke }+})++type UnreadBump = Extract<CommunityWsEvent, { type: "community:unread.bump" }>+const create: CommunityMessageCreate = {+ type: "community:message.create",+ channelId: "channel_1",+ serverId: "server_1",+ message: {+ id: "message_1",+ seq: 7,+ authorId: "author_1",+ authorName: " Ada ",+ authorAvatarVersion: 0,+ content: "**Hello**\n there",+ type: "chat",+ createdAt: "2026-09-12T00:00:00.000Z",+ },+}+const bump: UnreadBump = {+ type: "community:unread.bump",+ userId: "viewer_1",+ channelId: "channel_1",+ serverId: "server_1",+}++afterEach(() => {+ desktopMode.value = true+ vi.unstubAllGlobals()+ vi.clearAllMocks()+})++describe("desktop system notification candidates", () => {+ it("derives a hygienic server notification from one paired bundle", () => {+ expect(buildDesktopSystemNotificationCandidate(create, bump, "viewer_1")).toEqual({+ viewerUserId: "viewer_1",+ title: "Ada",+ body: "Hello there",+ target: {+ kind: "server",+ serverId: "server_1",+ channelId: "channel_1",+ messageId: "message_1",+ seq: 7,+ },+ })+ })++ it("rejects account, channel, scope, and own-author mismatches", () => {+ expect(buildDesktopSystemNotificationCandidate(create, bump, null)).toBeNull()+ expect(buildDesktopSystemNotificationCandidate(create, { ...bump, userId: "other" }, "viewer_1")).toBeNull()+ expect(buildDesktopSystemNotificationCandidate(create, { ...bump, channelId: "other" }, "viewer_1")).toBeNull()+ expect(buildDesktopSystemNotificationCandidate(create, { ...bump, serverId: "other" }, "viewer_1")).toBeNull()+ expect(buildDesktopSystemNotificationCandidate({+ ...create,+ message: { ...create.message, authorId: "viewer_1" },+ }, bump, "viewer_1")).toBeNull()+ })++ it.each([+ ["image/png", "Photo"],+ ["video/mp4", "Video"],+ ["audio/mpeg", "Audio"],+ ["application/pdf", "Attachment"],+ ])("uses the %s attachment fallback", (contentType, expected) => {+ const candidate = buildDesktopSystemNotificationCandidate({+ ...create,+ message: {+ ...create.message,+ content: "",+ attachments: [{ id: "a", filename: "file", url: "/file", contentType }],+ },+ }, bump, "viewer_1")+ expect(candidate?.body).toBe(expected)+ })++ it("uses the generic fallback and derives a DM target", () => {+ expect(buildDesktopSystemNotificationCandidate({+ ...create,+ serverId: null,+ message: {+ ...create.message,+ authorName: " ",+ content: "",+ attachments: [],+ },+ }, { ...bump, serverId: null }, "viewer_1")).toEqual({+ viewerUserId: "viewer_1",+ title: "Alook",+ body: "New message",+ target: {+ kind: "dm",+ channelId: "channel_1",+ messageId: "message_1",+ seq: 7,+ },+ })+ })++ it("invokes only the narrow desktop command", async () => {+ const candidate = buildDesktopSystemNotificationCandidate(create, bump, "viewer_1")!+ await showDesktopSystemNotification(candidate)+ expect(invoke).toHaveBeenCalledWith("desktop_system_notification_show", { candidate })+ })++ it("is a no-op outside the desktop shell", async () => {+ desktopMode.value = false+ const candidate = buildDesktopSystemNotificationCandidate(create, bump, "viewer_1")!+ await showDesktopSystemNotification(candidate)+ expect(invoke).not.toHaveBeenCalled()+ })+})++describe("desktop system notification activation bridge", () => {+ it("rejects listener setup when the native channel bridge is absent", async () => {+ vi.stubGlobal("window", {})+ await expect(listenDesktopSystemNotificationActivations(vi.fn())).rejects.toThrow(+ "native_bridge_unavailable",+ )+ })++ it("registers, forwards native signals, and tolerates unlisten rejection", async () => {+ const channels: Channel[] = []+ class Channel {+ onmessage = (_value: unknown) => undefined++ constructor() {+ channels.push(this)+ }+ }+ vi.stubGlobal("window", { __TAURI__: { core: { Channel } } })+ invoke.mockResolvedValueOnce(27).mockRejectedValueOnce(new Error("already removed"))+ const ready = vi.fn()++ const stop = await listenDesktopSystemNotificationActivations(ready)+ expect(invoke).toHaveBeenCalledWith("desktop_system_notification_listen", { channel: channels[0] })+ channels[0]?.onmessage(undefined)+ expect(ready).toHaveBeenCalledOnce()++ stop()+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledWith(+ "desktop_system_notification_unlisten",+ { registrationId: 27 },+ ))+ })++ it("takes and parses only valid native activations", async () => {+ const dmActivation = {+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ target: {+ kind: "dm",+ channelId: "dm_1",+ messageId: "message_2",+ seq: 8,+ },+ }+ invoke.mockResolvedValueOnce(dmActivation)+ await expect(takeDesktopSystemNotificationActivation()).resolves.toEqual(dmActivation)++ invoke.mockResolvedValueOnce({ href: "https://evil.test" })+ await expect(takeDesktopSystemNotificationActivation()).resolves.toBeNull()+ })+})diff --git a/src/web/src/lib/community/desktop-system-notification.ts b/src/web/src/lib/community/desktop-system-notification.tsnew file mode 100644index 000000000..7a592e7f0--- /dev/null+++ b/src/web/src/lib/community/desktop-system-notification.ts@@ -0,0 +1,94 @@+import {+ isDesktop,+ stripInlineMarkup,+ tauriInvoke,+ truncateMessagePreview,+ type CommunityMessageCreate,+ type CommunityWsEvent,+} from "@alook/shared"+import {+ parseDesktopSystemNotificationActivation,+ type DesktopSystemNotificationActivation,+ type DesktopSystemNotificationTarget,+} from "./system-notification-route"++type CommunityUnreadBump = Extract<CommunityWsEvent, { type: "community:unread.bump" }>++export type DesktopSystemNotificationCandidate = {+ viewerUserId: string+ title: string+ body: string+ target: DesktopSystemNotificationTarget+}++function attachmentFallback(message: CommunityMessageCreate["message"]): string {+ const contentType = message.attachments?.[0]?.contentType?.toLowerCase() ?? ""+ if (contentType.startsWith("image/")) return "Photo"+ if (contentType.startsWith("video/")) return "Video"+ if (contentType.startsWith("audio/")) return "Audio"+ if ((message.attachments?.length ?? 0) > 0) return "Attachment"+ return "New message"+}++export function buildDesktopSystemNotificationCandidate(+ create: CommunityMessageCreate,+ bump: CommunityUnreadBump,+ viewerUserId: string | null,+): DesktopSystemNotificationCandidate | null {+ if (!viewerUserId || bump.userId !== viewerUserId) return null+ if (create.channelId !== bump.channelId || create.serverId !== bump.serverId) return null+ if (create.message.authorId === viewerUserId) return null++ const readable = stripInlineMarkup(create.message.content).replace(/\s+/g, " ").trim()+ const target: DesktopSystemNotificationTarget = create.serverId+ ? {+ kind: "server",+ serverId: create.serverId,+ channelId: create.channelId,+ messageId: create.message.id,+ seq: create.message.seq,+ }+ : {+ kind: "dm",+ channelId: create.channelId,+ messageId: create.message.id,+ seq: create.message.seq,+ }++ return {+ viewerUserId,+ title: create.message.authorName.trim() || "Alook",+ body: truncateMessagePreview(readable || attachmentFallback(create.message)),+ target,+ }+}++export async function showDesktopSystemNotification(+ candidate: DesktopSystemNotificationCandidate,+): Promise<void> {+ if (!isDesktop()) return+ await tauriInvoke("desktop_system_notification_show", { candidate })+}++type TauriChannel = { onmessage: (value: unknown) => void }+type TauriWindow = Window & {+ __TAURI__?: { core?: { Channel?: new () => TauriChannel } }+}++export async function listenDesktopSystemNotificationActivations(+ ready: () => void,+): Promise<() => void> {+ const Channel = (window as TauriWindow).__TAURI__?.core?.Channel+ if (!Channel) throw new Error("native_bridge_unavailable")+ const channel = new Channel()+ channel.onmessage = ready+ const registrationId = await tauriInvoke<number>("desktop_system_notification_listen", { channel })+ return () => {+ void tauriInvoke("desktop_system_notification_unlisten", { registrationId }).catch(() => undefined)+ }+}++export async function takeDesktopSystemNotificationActivation(): Promise<DesktopSystemNotificationActivation | null> {+ const value = await tauriInvoke<unknown>("desktop_system_notification_take_activation")+ return parseDesktopSystemNotificationActivation(value)+}diff --git a/src/web/src/lib/community/message-dispatcher-architecture.test.ts b/src/web/src/lib/community/message-dispatcher-architecture.test.tsindex a7424a6a4..ef42649d9 100644--- a/src/web/src/lib/community/message-dispatcher-architecture.test.ts+++ b/src/web/src/lib/community/message-dispatcher-architecture.test.ts@@ -17,12 +17,12 @@ describe("committed-message delivery architecture", () => {it("removes message wake policy from generic fanout", () => {const fanout = source("./fanout.ts")- expect(fanout).not.toMatch(/wake-producer|wakeMessageRow|excludeWakeUserId|maybeEnqueueWakes/)+ expect(fanout).not.toMatch(/queue-producer|wakeMessageRow|excludeWakeUserId|maybeEnqueueWakes/)})- it("leaves wake-producer as payload transport rather than a second planner", () => {- const producer = source("./wake-producer.ts")- expect(producer).toContain("enqueueBotWakePayloads")+ it("leaves queue-producer as task transport rather than a second planner", () => {+ const producer = source("./queue-producer.ts")+ expect(producer).toContain("enqueueQueueTasks")expect(producer).not.toMatch(/\bqueries\b|findWakeCandidates|resolveNotificationEligibility/)})diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.tsindex 29e21af56..a5b28ddcc 100644--- a/src/web/src/lib/community/message-dispatcher.test.ts+++ b/src/web/src/lib/community/message-dispatcher.test.ts@@ -15,11 +15,19 @@ const mockResolveRecipients = vi.fn()const mockResolveNotificationRecipients = vi.fn()const mockResolveEligibility = vi.fn()const mockFindWakeCandidates = vi.fn()+const mockLogWarn = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return {...actual,+ createLogger: () => ({+ child() { return this },+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: (...args: unknown[]) => mockLogWarn(...args),+ }),withD1Retry: (run: () => Promise<unknown>) => run(),queries: {communityMessage: {@@ -58,9 +66,9 @@ const mockSendMessageDeliveryBatch = vi.fn()vi.mock("./message-delivery-transport", () => ({sendMessageDeliveryBatch: (...args: unknown[]) => mockSendMessageDeliveryBatch(...args),}))-const mockEnqueueBotWakePayloads = vi.fn()-vi.mock("./wake-producer", () => ({- enqueueBotWakePayloads: (...args: unknown[]) => mockEnqueueBotWakePayloads(...args),+const mockEnqueueQueueTasks = vi.fn()+vi.mock("./queue-producer", () => ({+ enqueueQueueTasks: (...args: unknown[]) => mockEnqueueQueueTasks(...args),}))import { dispatchCommittedMessage, planCommittedMessage } from "./message-dispatcher"@@ -141,7 +149,7 @@ describe("planCommittedMessage", () => {{ botUserId: "bot_1", name: "Bot", machineId: "m1", runtime: "codex" },])mockSendMessageDeliveryBatch.mockResolvedValue(undefined)- mockEnqueueBotWakePayloads.mockResolvedValue(undefined)+ mockEnqueueQueueTasks.mockResolvedValue(undefined)})it("derives content, notification, mention, and bot targets from one D1 plan", async () => {@@ -151,6 +159,7 @@ describe("planCommittedMessage", () => {expect(plan.unreadMentionUserIds).toEqual(["u_mentions", "bot_1"])expect(plan.mentionUserIds).toEqual(["u_mentions", "u_mention_only", "bot_1"])expect(plan.wakeBotUserIds).toEqual(["bot_1"])+ expect(plan.pushUserIds).toEqual(["u_all", "u_mentions", "bot_1", "u_mention_only"])expect(plan.messageEvent).toMatchObject({type: "community:message.create",channelId: "c1",@@ -183,6 +192,7 @@ describe("planCommittedMessage", () => {expect(plan.unreadMentionUserIds).toEqual([])expect(plan.mentionUserIds).toEqual([])expect(plan.wakeBotUserIds).toEqual([])+ expect(plan.pushUserIds).toEqual(["u_all"])expect(mockResolveEligibility).toHaveBeenCalledWith({}, ["u_all"], "msg_1")expect(mockFindWakeCandidates).toHaveBeenCalledWith({}, expect.objectContaining({ recipients: ["u_all"] }))})@@ -245,6 +255,7 @@ describe("planCommittedMessage", () => {const plan = await planCommittedMessage({} as never, "msg_1")expect(plan.contentUserIds).toEqual(["author_1", "participant_1"])expect(plan.mentionUserIds).toEqual(["parent_viewer"])+ expect(plan.pushUserIds).toEqual(["participant_1", "parent_viewer"])expect(plan.parentProjectionUserIds).toEqual(["participant_1", "parent_viewer"])expect(plan.parentProjection).toMatchObject({parentChannelId: "forum_1",@@ -265,6 +276,7 @@ describe("planCommittedMessage", () => {const plan = await planCommittedMessage({} as never, "msg_1")expect(plan.contentUserIds).toEqual(["author_1", "private_member"])expect(plan.unreadPlainUserIds).toEqual(["private_member"])+ expect(plan.pushUserIds).toEqual(["private_member"])})it("plans a DM from its two resolved members without server projections", async () => {@@ -284,6 +296,7 @@ describe("planCommittedMessage", () => {const plan = await planCommittedMessage({} as never, "msg_1")expect(plan.contentUserIds).toEqual(["author_1", "dm_peer"])+ expect(plan.pushUserIds).toEqual(["dm_peer"])expect(plan.messageEvent).not.toHaveProperty("serverId")expect(plan).not.toHaveProperty("parentProjection")})@@ -302,6 +315,7 @@ describe("planCommittedMessage", () => {expect(plan.unreadMentionUserIds).toEqual([])expect(plan.mentionUserIds).toEqual([])expect(plan.wakeBotUserIds).toEqual([])+ expect(plan.pushUserIds).toEqual([])expect(mockFindWakeCandidates).toHaveBeenCalledWith({}, {recipients: [],channelId: "c1",@@ -321,6 +335,7 @@ describe("planCommittedMessage", () => {expect(plan.unreadMentionUserIds).toEqual([])expect(plan.mentionUserIds).toEqual([])expect(plan.wakeBotUserIds).toEqual([])+ expect(plan.pushUserIds).toEqual([])})it("filters muted, caught-up, and unread-ineligible users consistently", async () => {@@ -336,6 +351,7 @@ describe("planCommittedMessage", () => {expect(plan.unreadMentionUserIds).toEqual([])expect(plan.mentionUserIds).toEqual([])expect(plan.wakeBotUserIds).toEqual([])+ expect(plan.pushUserIds).toEqual([])})it("accepts only an in-scope structural participant outcome", async () => {@@ -365,6 +381,7 @@ describe("planCommittedMessage", () => {const plan = await planCommittedMessage({} as never, "msg_1")expect(plan.contentUserIds).toEqual(["author_1", "u_mentions"])expect(plan.wakeBotUserIds).toEqual([])+ expect(plan.pushUserIds).toEqual(["u_mentions", "u_mention_only"])})it("deduplicates notification and attention candidates without consulting passive readers", async () => {@@ -377,6 +394,7 @@ describe("planCommittedMessage", () => {expect(plan.unreadPlainUserIds).toEqual(["u_all"])expect(plan.unreadMentionUserIds).toEqual(["u_mentions"])expect(plan.mentionUserIds).toEqual(["u_mentions", "u_mention_only"])+ expect(plan.pushUserIds).toEqual(["u_all", "u_mentions", "u_mention_only"])expect(plan.wakeBotUserIds).toEqual([])})@@ -397,13 +415,16 @@ describe("dispatchCommittedMessage", () => {mockListAttachments.mockResolvedValue([])mockListAttention.mockResolvedValue([])mockResolveRecipients.mockResolvedValue(["author_1"])+ mockResolveNotificationRecipients.mockImplementation(+ (db, id, run) => run("thread-participants", () => mockResolveRecipients(db, id)),+ )mockResolveEligibility.mockResolvedValue(new Map())mockFindWakeCandidates.mockResolvedValue([])mockSendMessageDeliveryBatch.mockResolvedValue(undefined)- mockEnqueueBotWakePayloads.mockResolvedValue(undefined)+ mockEnqueueQueueTasks.mockResolvedValue(undefined)})- it("registers one fail-open dispatch and sends browser plus wake plans", async () => {+ it("registers one fail-open dispatch and sends browser plus queue plans", async () => {const work = dispatchCommittedMessage({} as never, "msg_1")expect(mockWaitUntil).toHaveBeenCalledWith(work)await expect(work).resolves.toBeUndefined()@@ -412,7 +433,25 @@ describe("dispatchCommittedMessage", () => {expect.objectContaining({ messageId: "msg_1" }),await deriveCommunityDeliveryOperationId("msg_1"),)- expect(mockEnqueueBotWakePayloads).toHaveBeenCalledWith([])+ expect(mockEnqueueQueueTasks).toHaveBeenCalledWith([])+ })++ it("enqueues bot wake before the exact three-list mobile push union", async () => {+ mockResolveRecipients.mockResolvedValue(["author_1", "u_all", "bot_1"])+ mockListAttention.mockResolvedValue(["bot_1"])+ mockResolveEligibility.mockResolvedValue(new Map([+ ["u_all", state()],+ ["bot_1", state({ hasAttention: true })],+ ]))+ mockFindWakeCandidates.mockResolvedValue([{ botUserId: "bot_1" }])++ await dispatchCommittedMessage({} as never, "msg_1")++ expect(mockEnqueueQueueTasks).toHaveBeenCalledWith([+ { version: 1, kind: "bot-wake", messageId: "msg_1", botUserId: "bot_1" },+ { version: 1, kind: "mobile-push", messageId: "msg_1", userId: "u_all" },+ { version: 1, kind: "mobile-push", messageId: "msg_1", userId: "bot_1" },+ ])})it("does not reject the committed mutation when planning or transport fails", async () => {@@ -423,4 +462,15 @@ describe("dispatchCommittedMessage", () => {mockSendMessageDeliveryBatch.mockRejectedValueOnce(new Error("ws unavailable"))await expect(dispatchCommittedMessage({} as never, "msg_1")).resolves.toBeUndefined()})++ it("logs a queue rejection while preserving fail-open dispatch", async () => {+ mockEnqueueQueueTasks.mockRejectedValueOnce(new Error("queue unavailable"))++ await expect(dispatchCommittedMessage({} as never, "msg_1")).resolves.toBeUndefined()++ expect(mockLogWarn).toHaveBeenCalledWith("committed_message_queue_delivery_failed", {+ messageId: "msg_1",+ err: "Error: queue unavailable",+ })+ })})diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.tsindex d9b49edc7..ec83b722c 100644--- a/src/web/src/lib/community/message-dispatcher.ts+++ b/src/web/src/lib/community/message-dispatcher.ts@@ -9,11 +9,11 @@ import {type CommunityDeliveryOperationId,type Database,type MessageDeliveryBatch,- type WakePayload,+ type AlookQueueTask,} from "@alook/shared"import { mapMessageForWs } from "./message-payload"import { sendMessageDeliveryBatch } from "./message-delivery-transport"-import { enqueueBotWakePayloads } from "./wake-producer"+import { enqueueQueueTasks } from "./queue-producer"import { attachmentThumbnailUrl, attachmentUrl } from "./storage"const log = createLogger({ service: "committed-message-dispatcher" })@@ -28,6 +28,7 @@ export type CommittedMessageStructuralOutcome = {export type MessageDeliveryPlan = MessageDeliveryBatch & {operationId: CommunityDeliveryOperationIdwakeBotUserIds: string[]+ pushUserIds: string[]}const recipientRetryRoute = {@@ -157,6 +158,11 @@ export async function planCommittedMessage(.map((candidate) => candidate.botUserId).filter((id) => notificationSet.has(id) && allowed(id)),)+ const pushUserIds = unique([+ ...unreadPlainUserIds,+ ...unreadMentionUserIds,+ ...mentionUserIds,+ ])const replyMap = new Map<string, {id: string@@ -227,6 +233,7 @@ export async function planCommittedMessage(unreadMentionUserIds,mentionUserIds,wakeBotUserIds,+ pushUserIds,...(structural.memberAddedUserId && channel.serverId? {memberAdded: {@@ -264,13 +271,23 @@ async function runCommittedMessageDispatch(}: {}),}- const wakePayloads: WakePayload[] = plan.wakeBotUserIds.map((botUserId) => ({- messageId: plan.messageId,- botUserId,- }))- const [browser, wake] = await Promise.allSettled([+ const queueTasks: AlookQueueTask[] = [+ ...plan.wakeBotUserIds.map((botUserId) => ({+ version: 1 as const,+ kind: "bot-wake" as const,+ messageId: plan.messageId,+ botUserId,+ })),+ ...plan.pushUserIds.map((userId) => ({+ version: 1 as const,+ kind: "mobile-push" as const,+ messageId: plan.messageId,+ userId,+ })),+ ]+ const [browser, queue] = await Promise.allSettled([sendMessageDeliveryBatch(browserBatch, plan.operationId),- enqueueBotWakePayloads(wakePayloads),+ enqueueQueueTasks(queueTasks),])if (browser.status === "rejected") {log.warn("committed_message_browser_delivery_failed", {@@ -278,10 +295,10 @@ async function runCommittedMessageDispatch(err: String(browser.reason),})}- if (wake.status === "rejected") {- log.warn("committed_message_wake_delivery_failed", {+ if (queue.status === "rejected") {+ log.warn("committed_message_queue_delivery_failed", {messageId,- err: String(wake.reason),+ err: String(queue.reason),})}log.info("committed_message_dispatch_complete", {@@ -290,6 +307,7 @@ async function runCommittedMessageDispatch(unreadCount: plan.unreadPlainUserIds.length + plan.unreadMentionUserIds.length,mentionCount: plan.mentionUserIds.length,wakeCount: plan.wakeBotUserIds.length,+ pushCount: plan.pushUserIds.length,parentCount: plan.parentProjectionUserIds?.length ?? 0,durationMs: Date.now() - startedAt,})diff --git a/src/web/src/lib/community/mobile-system-notification.test.ts b/src/web/src/lib/community/mobile-system-notification.test.tsnew file mode 100644index 000000000..18c75a187--- /dev/null+++ b/src/web/src/lib/community/mobile-system-notification.test.ts@@ -0,0 +1,598 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import {+ acknowledgeMobileSystemNotificationRegistration,+ checkMobileSystemNotificationPermission,+ createMobileSystemNotificationActivationController,+ createMobileSystemNotificationRegistrationController,+ deleteMobileSystemNotificationRegistration,+ listenMobileSystemNotificationSignals,+ parseMobileSystemNotificationActivation,+ parseMobileSystemNotificationPermission,+ parseMobileSystemNotificationRegistration,+ postMobileSystemNotificationRegistration,+ requestMobileSystemNotificationPermission,+ revalidateMobileSystemNotificationActivation,+ resumeMobileSystemNotificationRegistration,+ snapshotMobileSystemNotificationRegistration,+ suspendMobileSystemNotificationRegistration,+ takeMobileSystemNotificationActivation,+ type MobileSystemNotificationRegistration,+ type MobileSystemNotificationRegistrationDeps,+ unregisterCurrentMobileSystemNotification,+} from "./mobile-system-notification"++const nativeMocks = vi.hoisted(() => ({+ tauri: true,+ mobile: true,+ invoke: vi.fn(),+}))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ isTauri: () => nativeMocks.tauri,+ isMobile: () => nativeMocks.mobile,+ tauriInvoke: nativeMocks.invoke,+ }+})++const installationId = "123e4567-e89b-42d3-a456-426614174000"+const notificationId = "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e"+const token0 = "token-00000000000"+const token1 = "token-11111111111"+const token2 = "token-22222222222"++beforeEach(() => {+ nativeMocks.tauri = true+ nativeMocks.mobile = true+ nativeMocks.invoke.mockReset()+})++afterEach(() => {+ vi.unstubAllGlobals()+})++function snapshot(+ overrides: Partial<MobileSystemNotificationRegistration> = {},+): MobileSystemNotificationRegistration {+ return {+ installationId,+ platform: "ios",+ providerEnvironment: "sandbox",+ providerToken: token0,+ appVersion: "0.1.36",+ ...overrides,+ }+}++function registrationDeps(+ overrides: Partial<MobileSystemNotificationRegistrationDeps> = {},+): MobileSystemNotificationRegistrationDeps {+ return {+ checkPermission: vi.fn(async () => "granted"),+ requestPermission: vi.fn(async () => "granted"),+ snapshot: vi.fn(async () => snapshot()),+ register: vi.fn(async () => undefined),+ acknowledge: vi.fn(async () => undefined),+ unregister: vi.fn(async () => undefined),+ schedule: vi.fn(() => 1),+ cancel: vi.fn(),+ ...overrides,+ }+}++describe("mobile notification native value parsing", () => {+ it("accepts only exact permission and registration shapes", () => {+ expect(parseMobileSystemNotificationPermission({ permissionState: "granted" })).toBe("granted")+ expect(parseMobileSystemNotificationPermission({ permissionState: "granted", token: token0 })).toBeNull()+ expect(parseMobileSystemNotificationPermission({ permissionState: "unknown" })).toBeNull()++ const value = {+ installationId,+ platform: "ios",+ providerEnvironment: "sandbox",+ providerToken: token0,+ previousProviderToken: token1,+ appVersion: "0.1.36",+ }+ expect(parseMobileSystemNotificationRegistration(value)).toEqual(value)+ expect(parseMobileSystemNotificationRegistration({ ...value, secret: token2 })).toBeNull()+ expect(parseMobileSystemNotificationRegistration({+ ...value,+ platform: "android",+ providerEnvironment: "sandbox",+ })).toBeNull()+ expect(parseMobileSystemNotificationRegistration({+ ...value,+ previousProviderToken: token0,+ })).toBeNull()+ })++ it("accepts only the flat allowlisted activation", () => {+ const activation = { notificationId, messageId: "message_1", targetId: "channel_1" }+ expect(parseMobileSystemNotificationActivation(activation)).toEqual(activation)+ expect(parseMobileSystemNotificationActivation({ ...activation, serverId: "server_1" })).toBeNull()+ expect(parseMobileSystemNotificationActivation({ ...activation, messageId: "../message" })).toBeNull()+ expect(parseMobileSystemNotificationActivation({ ...activation, notificationId: "bad" })).toBeNull()+ })+})++describe("mobile notification native adapter", () => {+ const nativeSnapshot = {+ installationId,+ platform: "ios",+ providerEnvironment: "sandbox",+ providerToken: token0,+ previousProviderToken: null,+ appVersion: null,+ }++ it("validates permission, snapshot, acknowledgement, and activation results", async () => {+ nativeMocks.invoke+ .mockResolvedValueOnce({ permissionState: "granted" })+ .mockResolvedValueOnce({ permissionState: "prompt" })+ .mockResolvedValueOnce({ permissionState: "unknown" })+ .mockResolvedValueOnce(nativeSnapshot)+ .mockResolvedValueOnce({ ...nativeSnapshot, secret: true })+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ notificationId, messageId: "message_1", targetId: "channel_1" })+ .mockResolvedValueOnce({ notificationId: "invalid", messageId: "message_1", targetId: "channel_1" })++ await expect(checkMobileSystemNotificationPermission()).resolves.toBe("granted")+ await expect(requestMobileSystemNotificationPermission()).resolves.toBe("prompt")+ await expect(checkMobileSystemNotificationPermission()).rejects.toThrow("invalid_native_response")+ await expect(snapshotMobileSystemNotificationRegistration()).resolves.toEqual({+ installationId,+ platform: "ios",+ providerEnvironment: "sandbox",+ providerToken: token0,+ })+ await expect(snapshotMobileSystemNotificationRegistration()).rejects.toThrow("invalid_native_response")++ await expect(acknowledgeMobileSystemNotificationRegistration(token0)).resolves.toBeUndefined()+ expect(nativeMocks.invoke).toHaveBeenNthCalledWith(+ 6,+ "mobile_system_notification_acknowledge_registration",+ { providerToken: token0 },+ )+ await expect(acknowledgeMobileSystemNotificationRegistration("short")).rejects.toThrow(+ "invalid_provider_token",+ )++ await expect(takeMobileSystemNotificationActivation()).resolves.toBeNull()+ await expect(takeMobileSystemNotificationActivation()).resolves.toEqual({+ notificationId,+ messageId: "message_1",+ targetId: "channel_1",+ })+ await expect(takeMobileSystemNotificationActivation()).rejects.toThrow("invalid_native_response")+ })++ it("bridges native signals and swallows unlisten failures", async () => {+ class Channel {+ onmessage = (_value: unknown) => undefined+ }+ vi.stubGlobal("window", { __TAURI__: { core: { Channel } } })+ nativeMocks.invoke+ .mockResolvedValueOnce(7)+ .mockRejectedValueOnce(new Error("already stopped"))+ const ready = vi.fn()++ const stop = await listenMobileSystemNotificationSignals(ready)+ const channel = nativeMocks.invoke.mock.calls[0]?.[1]?.channel as Channel+ expect(nativeMocks.invoke).toHaveBeenNthCalledWith(+ 1,+ "mobile_system_notification_listen",+ { channel },+ )+ channel.onmessage({})+ expect(ready).toHaveBeenCalledOnce()+ stop()+ expect(nativeMocks.invoke).toHaveBeenNthCalledWith(+ 2,+ "mobile_system_notification_unlisten",+ { registrationId: 7 },+ )+ await Promise.resolve()+ })++ it("rejects missing native channels and invalid listener registrations", async () => {+ vi.stubGlobal("window", {})+ await expect(listenMobileSystemNotificationSignals(vi.fn())).rejects.toThrow(+ "native_bridge_unavailable",+ )++ class Channel {+ onmessage = (_value: unknown) => undefined+ }+ vi.stubGlobal("window", { __TAURI__: { core: { Channel } } })+ nativeMocks.invoke.mockResolvedValue(-1)+ await expect(listenMobileSystemNotificationSignals(vi.fn())).rejects.toThrow(+ "invalid_native_response",+ )+ })++ it("unregisters the current installation only on a mobile Tauri runtime", async () => {+ const fetchImpl = vi.fn(async () => new Response(null, { status: 204 }))++ nativeMocks.tauri = false+ await unregisterCurrentMobileSystemNotification(fetchImpl)+ nativeMocks.tauri = true+ nativeMocks.mobile = false+ await unregisterCurrentMobileSystemNotification(fetchImpl)+ expect(nativeMocks.invoke).not.toHaveBeenCalled()+ expect(fetchImpl).not.toHaveBeenCalled()++ nativeMocks.mobile = true+ nativeMocks.invoke.mockResolvedValue(nativeSnapshot)+ await unregisterCurrentMobileSystemNotification(fetchImpl)+ expect(nativeMocks.invoke).toHaveBeenCalledWith("mobile_system_notification_snapshot")+ expect(fetchImpl).toHaveBeenCalledWith(+ `/api/community/notifications/devices/${installationId}`,+ { method: "DELETE", credentials: "same-origin" },+ )+ })+})++describe("mobile notification HTTP adapter", () => {+ it("uses the global fetch implementation for every default adapter entry", async () => {+ const fetchImpl = vi.fn()+ .mockResolvedValueOnce(new Response(null, { status: 204 }))+ .mockResolvedValueOnce(new Response(null, { status: 204 }))+ .mockResolvedValueOnce(new Response(null, { status: 204 }))+ .mockResolvedValueOnce(new Response(JSON.stringify({+ messages: [{ id: "message_1", seq: 9 }],+ surfaceReceipt: { channelId: "channel_1", surfaceKind: "dm" },+ })))+ vi.stubGlobal("fetch", fetchImpl)++ await postMobileSystemNotificationRegistration(snapshot())+ await deleteMobileSystemNotificationRegistration(installationId)+ nativeMocks.invoke.mockResolvedValue({+ ...snapshot(),+ previousProviderToken: null,+ })+ await unregisterCurrentMobileSystemNotification()+ await expect(revalidateMobileSystemNotificationActivation({+ notificationId,+ messageId: "message_1",+ targetId: "channel_1",+ })).resolves.toEqual({ href: "/c/me/channel_1?seq=9" })++ expect(fetchImpl.mock.calls.map(([url]) => url)).toEqual([+ "/api/community/notifications/devices",+ `/api/community/notifications/devices/${installationId}`,+ `/api/community/notifications/devices/${installationId}`,+ "/api/community/channels/channel_1/messages?anchor=message_1&limit=1",+ ])+ })++ it("posts the exact registration with same-origin cookies", async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ device: {} }), { status: 200 }))+ await postMobileSystemNotificationRegistration(snapshot({ previousProviderToken: token1 }), fetchImpl)+ expect(fetchImpl).toHaveBeenCalledOnce()+ const [url, init] = fetchImpl.mock.calls[0]+ expect(url).toBe("/api/community/notifications/devices")+ expect(init).toMatchObject({+ method: "POST",+ credentials: "same-origin",+ headers: { "Content-Type": "application/json" },+ })+ expect(JSON.parse(String(init?.body))).toEqual({+ installationId,+ platform: "ios",+ providerEnvironment: "sandbox",+ providerToken: token0,+ previousProviderToken: token1,+ appVersion: "0.1.36",+ })+ })++ it("deletes the encoded installation and rejects failed responses", async () => {+ const fetchImpl = vi.fn(async () => new Response(null, { status: 204 }))+ await deleteMobileSystemNotificationRegistration(installationId, fetchImpl)+ expect(fetchImpl).toHaveBeenCalledWith(+ `/api/community/notifications/devices/${installationId}`,+ { method: "DELETE", credentials: "same-origin" },+ )++ await expect(postMobileSystemNotificationRegistration(+ snapshot(),+ vi.fn(async () => new Response(null, { status: 409 })),+ )).rejects.toThrow("registration_failed")+ })++ it("orders logout deletion after an active POST and suppresses later registration", async () => {+ const calls: string[] = []+ let releasePost = () => undefined+ const blockedPost = new Promise<void>((resolve) => { releasePost = resolve })+ const post = postMobileSystemNotificationRegistration(snapshot(), async () => {+ calls.push("post:start")+ await blockedPost+ calls.push("post:end")+ return new Response(null, { status: 204 })+ })+ await vi.waitFor(() => expect(calls).toEqual(["post:start"]))++ suspendMobileSystemNotificationRegistration()+ const remove = deleteMobileSystemNotificationRegistration(installationId, async () => {+ calls.push("delete")+ return new Response(null, { status: 204 })+ })+ releasePost()+ await Promise.all([post, remove])+ expect(calls).toEqual(["post:start", "post:end", "delete"])++ const suppressedFetch = vi.fn()+ await expect(postMobileSystemNotificationRegistration(+ snapshot(),+ suppressedFetch,+ )).rejects.toThrow("registration_suspended")+ expect(suppressedFetch).not.toHaveBeenCalled()+ resumeMobileSystemNotificationRegistration()+ })+})++describe("mobile notification registration controller", () => {+ it("requests permission once, posts, then acknowledges the exact sent token", async () => {+ const calls: string[] = []+ const deps = registrationDeps({+ checkPermission: vi.fn(async () => { calls.push("check"); return "prompt" }),+ requestPermission: vi.fn(async () => { calls.push("request"); return "granted" }),+ snapshot: vi.fn(async () => { calls.push("snapshot"); return snapshot() }),+ register: vi.fn(async () => { calls.push("post") }),+ acknowledge: vi.fn(async (token) => { calls.push(`ack:${token}`) }),+ })+ const controller = createMobileSystemNotificationRegistrationController(deps)+ await controller.sync(true)+ expect(calls).toEqual(["check", "request", "snapshot", "post", `ack:${token0}`])+ })++ it("disables a denied installation and waits for a native signal when no token exists", async () => {+ const denied = registrationDeps({+ checkPermission: vi.fn(async () => "denied"),+ })+ await createMobileSystemNotificationRegistrationController(denied).sync(true)+ expect(denied.unregister).toHaveBeenCalledWith(installationId)+ expect(denied.register).not.toHaveBeenCalled()++ const tokenless = registrationDeps({+ snapshot: vi.fn(async () => snapshot({ providerToken: undefined })),+ })+ await createMobileSystemNotificationRegistrationController(tokenless).sync()+ expect(tokenless.register).not.toHaveBeenCalled()+ expect(tokenless.schedule).not.toHaveBeenCalled()+ })++ it("serializes concurrent signals and coalesces them into one rerun", async () => {+ let release = () => undefined+ const blocked = new Promise<void>((resolve) => { release = resolve })+ let concurrent = 0+ let peak = 0+ const deps = registrationDeps({+ register: vi.fn(async () => {+ concurrent += 1+ peak = Math.max(peak, concurrent)+ await blocked+ concurrent -= 1+ }),+ })+ const controller = createMobileSystemNotificationRegistrationController(deps)+ const first = controller.sync()+ await vi.waitFor(() => expect(deps.register).toHaveBeenCalledOnce())+ const second = controller.sync()+ const third = controller.sync()+ expect(second).toBe(first)+ expect(third).toBe(first)+ release()+ await first+ expect(deps.register).toHaveBeenCalledTimes(2)+ expect(peak).toBe(1)+ })++ it("retains the last acknowledged token across failed rotations", async () => {+ let currentToken = token0+ let acknowledgedToken: string | undefined+ const posted: MobileSystemNotificationRegistration[] = []+ let retry: (() => void) | undefined+ const deps = registrationDeps({+ snapshot: vi.fn(async () => snapshot({+ providerToken: currentToken,+ previousProviderToken: acknowledgedToken === currentToken ? undefined : acknowledgedToken,+ })),+ register: vi.fn(async (value) => {+ posted.push(value)+ if (value.providerToken === token1) throw new Error("offline")+ }),+ acknowledge: vi.fn(async (token) => {+ if (token !== currentToken) throw new Error("stale")+ acknowledgedToken = token+ }),+ schedule: vi.fn((callback) => { retry = callback; return 7 }),+ })+ const controller = createMobileSystemNotificationRegistrationController(deps)+ await controller.sync()+ currentToken = token1+ await controller.sync()+ expect(retry).toBeTypeOf("function")+ currentToken = token2+ await controller.sync()+ expect(posted.map(({ providerToken, previousProviderToken }) => ({+ providerToken,+ previousProviderToken,+ }))).toEqual([+ { providerToken: token0, previousProviderToken: undefined },+ { providerToken: token1, previousProviderToken: token0 },+ { providerToken: token2, previousProviderToken: token0 },+ ])+ expect(acknowledgedToken).toBe(token2)+ expect(deps.cancel).toHaveBeenCalledWith(7)+ })++ it("uses bounded retry delays and cancels a pending retry on disposal", async () => {+ const scheduled: Array<{ callback: () => void; delay: number }> = []+ const deps = registrationDeps({+ checkPermission: vi.fn(async () => { throw new Error("offline") }),+ schedule: vi.fn((callback, delay) => {+ scheduled.push({ callback, delay })+ return scheduled.length+ }),+ retryDelaysMs: [10, 20],+ })+ const controller = createMobileSystemNotificationRegistrationController(deps)+ await controller.sync(true)+ expect(scheduled.map(({ delay }) => delay)).toEqual([10])+ scheduled.shift()?.callback()+ await vi.waitFor(() => expect(scheduled.map(({ delay }) => delay)).toEqual([20]))+ scheduled.shift()?.callback()+ await vi.waitFor(() => expect(deps.checkPermission).toHaveBeenCalledTimes(3))+ expect(scheduled).toHaveLength(0)++ const disposableDeps = registrationDeps({+ checkPermission: vi.fn(async () => { throw new Error("offline") }),+ })+ const disposable = createMobileSystemNotificationRegistrationController(disposableDeps)+ disposable.dispose()+ await disposable.sync()+ expect(disposableDeps.checkPermission).not.toHaveBeenCalled()+ })++ it("preserves an interactive prompt when an active run fails before its rerun", async () => {+ let rejectFirst = (_error: Error) => undefined+ const firstCheck = new Promise<never>((_resolve, reject) => { rejectFirst = reject })+ const deps = registrationDeps({+ checkPermission: vi.fn()+ .mockReturnValueOnce(firstCheck)+ .mockResolvedValueOnce("prompt"),+ })+ const controller = createMobileSystemNotificationRegistrationController(deps)++ const first = controller.sync(true)+ await vi.waitFor(() => expect(deps.checkPermission).toHaveBeenCalledOnce())+ expect(controller.sync()).toBe(first)+ rejectFirst(new Error("offline"))+ await first++ expect(deps.requestPermission).toHaveBeenCalledOnce()+ expect(deps.register).toHaveBeenCalledOnce()+ })+})++describe("mobile notification activation", () => {+ const activation = { notificationId, messageId: "message_1", targetId: "channel_1" }++ it("navigates only after exact DM and server revalidation", async () => {+ const dmFetch = vi.fn()+ .mockResolvedValueOnce(new Response(JSON.stringify({+ messages: [{ id: "message_1", seq: 9 }],+ surfaceReceipt: { channelId: "channel_1", surfaceKind: "dm" },+ })))+ await expect(revalidateMobileSystemNotificationActivation(activation, dmFetch)).resolves.toEqual({+ href: "/c/me/channel_1?seq=9",+ })++ const serverFetch = vi.fn()+ .mockResolvedValueOnce(new Response(JSON.stringify({+ messages: [{ id: "message_1", seq: 9 }],+ surfaceReceipt: { channelId: "channel_1", surfaceKind: "thread" },+ })))+ .mockResolvedValueOnce(new Response(JSON.stringify({+ id: "channel_1",+ serverId: "server_1",+ type: "thread",+ })))+ await expect(revalidateMobileSystemNotificationActivation(activation, serverFetch)).resolves.toEqual({+ href: "/c/channels/server_1/channel_1?msg=message_1",+ })+ expect(serverFetch.mock.calls.map(([url]) => url)).toEqual([+ "/api/community/channels/channel_1/messages?anchor=message_1&limit=1",+ "/api/community/channels/channel_1",+ ])+ })++ it.each([+ ["deleted", new Response(null, { status: 404 })],+ ["revoked", new Response(null, { status: 403 })],+ ["wrong message", new Response(JSON.stringify({+ messages: [{ id: "other", seq: 9 }],+ surfaceReceipt: { channelId: "channel_1", surfaceKind: "dm" },+ }))],+ ["wrong target", new Response(JSON.stringify({+ messages: [{ id: "message_1", seq: 9 }],+ surfaceReceipt: { channelId: "other", surfaceKind: "dm" },+ }))],+ ["receipt extras", new Response(JSON.stringify({+ messages: [{ id: "message_1", seq: 9 }],+ surfaceReceipt: { channelId: "channel_1", surfaceKind: "dm", secret: true },+ }))],+ ["invalid surface", new Response(JSON.stringify({+ messages: [{ id: "message_1", seq: 9 }],+ surfaceReceipt: { channelId: "channel_1", surfaceKind: "private" },+ }))],+ ])("falls back for %s message-door results", async (_label, response) => {+ await expect(revalidateMobileSystemNotificationActivation(+ activation,+ vi.fn(async () => response),+ )).resolves.toBeNull()+ })++ it("opens Inbox on invalid, revoked, or unreadable activations", async () => {+ const openInbox = vi.fn()+ const navigate = vi.fn()+ const controller = createMobileSystemNotificationActivationController({+ take: vi.fn()+ .mockResolvedValueOnce(activation)+ .mockRejectedValueOnce(new Error("invalid native response")),+ revalidate: vi.fn().mockRejectedValueOnce(new Error("offline")),+ navigate,+ openInbox,+ })+ await controller.drain()+ await controller.drain()+ expect(openInbox).toHaveBeenCalledTimes(2)+ expect(navigate).not.toHaveBeenCalled()+ })++ it("coalesces a signal received while an activation drain is active", async () => {+ let releaseTake = (_value: null) => undefined+ const firstTake = new Promise<null>((resolve) => { releaseTake = resolve })+ const take = vi.fn().mockReturnValueOnce(firstTake).mockResolvedValueOnce(null)+ const controller = createMobileSystemNotificationActivationController({+ take,+ revalidate: vi.fn(),+ navigate: vi.fn(),+ openInbox: vi.fn(),+ })++ const first = controller.drain()+ await vi.waitFor(() => expect(take).toHaveBeenCalledOnce())+ await controller.drain()+ releaseTake(null)+ await first+ expect(take).toHaveBeenCalledTimes(2)+ })++ it("rejects invalid server-channel payloads and network failures", async () => {+ const messageResponse = () => new Response(JSON.stringify({+ messages: [{ id: "message_1", seq: 9 }],+ surfaceReceipt: { channelId: "channel_1", surfaceKind: "thread" },+ }))+ const invalidChannel = vi.fn()+ .mockResolvedValueOnce(messageResponse())+ .mockResolvedValueOnce(new Response(JSON.stringify({+ id: "channel_1",+ serverId: "server_1",+ type: "dm",+ })))+ await expect(revalidateMobileSystemNotificationActivation(+ activation,+ invalidChannel,+ )).resolves.toBeNull()++ await expect(revalidateMobileSystemNotificationActivation(+ activation,+ vi.fn(async () => { throw new Error("offline") }),+ )).resolves.toBeNull()+ })+})diff --git a/src/web/src/lib/community/mobile-system-notification.ts b/src/web/src/lib/community/mobile-system-notification.tsnew file mode 100644index 000000000..d175873f7--- /dev/null+++ b/src/web/src/lib/community/mobile-system-notification.ts@@ -0,0 +1,455 @@+import { isMobile, isTauri, tauriInvoke } from "@alook/shared"++export type MobileSystemNotificationPermission = "granted" | "denied" | "prompt"++export type MobileSystemNotificationRegistration = {+ installationId: string+ platform: "ios" | "android"+ providerEnvironment: "sandbox" | "production"+ providerToken?: string+ previousProviderToken?: string+ appVersion?: string+}++export type MobileSystemNotificationActivation = {+ notificationId: string+ messageId: string+ targetId: string+}++export type MobileSystemNotificationDestination = {+ href: string+}++const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i+const RETRY_DELAYS_MS = [1_000, 5_000, 30_000, 60_000] as const+let registrationMutationTail: Promise<void> = Promise.resolve()+let registrationSuppressed = false++function serializeRegistrationMutation<T>(operation: () => Promise<T>): Promise<T> {+ const result = registrationMutationTail.then(operation, operation)+ registrationMutationTail = result.then(() => undefined, () => undefined)+ return result+}++export function suspendMobileSystemNotificationRegistration() {+ registrationSuppressed = true+}++export function resumeMobileSystemNotificationRegistration() {+ registrationSuppressed = false+}++function isObject(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value)+}++function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {+ const actual = Object.keys(value).sort()+ const expected = [...keys].sort()+ return actual.length === expected.length+ && actual.every((key, index) => key === expected[index])+}++function isSafeId(value: unknown): value is string {+ return typeof value === "string" && SAFE_ID.test(value)+}++function isProviderToken(value: unknown): value is string {+ return typeof value === "string"+ && value.length >= 16+ && value.length <= 4096+ && !/\p{Cc}/u.test(value)+}++function optionalString(+ value: unknown,+ validate: (candidate: unknown) => candidate is string,+): string | undefined | false {+ if (value === null || value === undefined) return undefined+ return validate(value) ? value : false+}++export function parseMobileSystemNotificationPermission(+ value: unknown,+): MobileSystemNotificationPermission | null {+ if (!isObject(value) || !hasExactKeys(value, ["permissionState"])) return null+ return value.permissionState === "granted"+ || value.permissionState === "denied"+ || value.permissionState === "prompt"+ ? value.permissionState+ : null+}++export function parseMobileSystemNotificationRegistration(+ value: unknown,+): MobileSystemNotificationRegistration | null {+ if (!isObject(value) || !hasExactKeys(value, [+ "installationId",+ "platform",+ "providerEnvironment",+ "providerToken",+ "previousProviderToken",+ "appVersion",+ ])) return null+ if (typeof value.installationId !== "string" || !UUID.test(value.installationId)) return null+ if (value.platform !== "ios" && value.platform !== "android") return null+ if (value.providerEnvironment !== "sandbox" && value.providerEnvironment !== "production") return null+ if (value.platform === "android" && value.providerEnvironment !== "production") return null++ const providerToken = optionalString(value.providerToken, isProviderToken)+ const previousProviderToken = optionalString(value.previousProviderToken, isProviderToken)+ const appVersion = optionalString(+ value.appVersion,+ (candidate): candidate is string => typeof candidate === "string"+ && candidate.length >= 1+ && candidate.length <= 128,+ )+ if (providerToken === false || previousProviderToken === false || appVersion === false) return null+ if (providerToken !== undefined && providerToken === previousProviderToken) return null++ return {+ installationId: value.installationId.toLowerCase(),+ platform: value.platform,+ providerEnvironment: value.providerEnvironment,+ ...(providerToken === undefined ? {} : { providerToken }),+ ...(previousProviderToken === undefined ? {} : { previousProviderToken }),+ ...(appVersion === undefined ? {} : { appVersion }),+ }+}++export function parseMobileSystemNotificationActivation(+ value: unknown,+): MobileSystemNotificationActivation | null {+ if (!isObject(value) || !hasExactKeys(value, ["notificationId", "messageId", "targetId"])) {+ return null+ }+ if (typeof value.notificationId !== "string" || !UUID.test(value.notificationId)) return null+ if (!isSafeId(value.messageId) || !isSafeId(value.targetId)) return null+ return {+ notificationId: value.notificationId.toLowerCase(),+ messageId: value.messageId,+ targetId: value.targetId,+ }+}++async function permissionCommand(+ command: "mobile_system_notification_check_permission" | "mobile_system_notification_request_permission",+): Promise<MobileSystemNotificationPermission> {+ const permission = parseMobileSystemNotificationPermission(await tauriInvoke<unknown>(command))+ if (!permission) throw new Error("invalid_native_response")+ return permission+}++export function checkMobileSystemNotificationPermission(): Promise<MobileSystemNotificationPermission> {+ return permissionCommand("mobile_system_notification_check_permission")+}++export function requestMobileSystemNotificationPermission(): Promise<MobileSystemNotificationPermission> {+ return permissionCommand("mobile_system_notification_request_permission")+}++export async function snapshotMobileSystemNotificationRegistration(): Promise<MobileSystemNotificationRegistration> {+ const snapshot = parseMobileSystemNotificationRegistration(+ await tauriInvoke<unknown>("mobile_system_notification_snapshot"),+ )+ if (!snapshot) throw new Error("invalid_native_response")+ return snapshot+}++export async function acknowledgeMobileSystemNotificationRegistration(+ providerToken: string,+): Promise<void> {+ if (!isProviderToken(providerToken)) throw new Error("invalid_provider_token")+ await tauriInvoke("mobile_system_notification_acknowledge_registration", { providerToken })+}++type TauriChannel = { onmessage: (value: unknown) => void }+type TauriWindow = Window & {+ __TAURI__?: { core?: { Channel?: new () => TauriChannel } }+}++export async function listenMobileSystemNotificationSignals(+ ready: () => void,+): Promise<() => void> {+ const Channel = (window as TauriWindow).__TAURI__?.core?.Channel+ if (!Channel) throw new Error("native_bridge_unavailable")+ const channel = new Channel()+ channel.onmessage = () => ready()+ const registrationId = await tauriInvoke<number>("mobile_system_notification_listen", { channel })+ if (!Number.isSafeInteger(registrationId) || registrationId < 0) {+ throw new Error("invalid_native_response")+ }+ return () => {+ void tauriInvoke("mobile_system_notification_unlisten", { registrationId }).catch(() => undefined)+ }+}++export async function takeMobileSystemNotificationActivation(): Promise<MobileSystemNotificationActivation | null> {+ const value = await tauriInvoke<unknown>("mobile_system_notification_take_activation")+ if (value === null || value === undefined) return null+ const activation = parseMobileSystemNotificationActivation(value)+ if (!activation) throw new Error("invalid_native_response")+ return activation+}++export async function postMobileSystemNotificationRegistration(+ snapshot: MobileSystemNotificationRegistration,+ fetchImpl: typeof fetch = fetch,+): Promise<void> {+ if (!snapshot.providerToken) throw new Error("provider_token_unavailable")+ await serializeRegistrationMutation(async () => {+ if (registrationSuppressed) throw new Error("registration_suspended")+ const response = await fetchImpl("/api/community/notifications/devices", {+ method: "POST",+ credentials: "same-origin",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ installationId: snapshot.installationId,+ platform: snapshot.platform,+ providerEnvironment: snapshot.providerEnvironment,+ providerToken: snapshot.providerToken,+ ...(snapshot.previousProviderToken+ ? { previousProviderToken: snapshot.previousProviderToken }+ : {}),+ ...(snapshot.appVersion ? { appVersion: snapshot.appVersion } : {}),+ }),+ })+ if (!response.ok) throw new Error("registration_failed")+ })+}++export async function deleteMobileSystemNotificationRegistration(+ installationId: string,+ fetchImpl: typeof fetch = fetch,+): Promise<void> {+ if (!UUID.test(installationId)) throw new Error("invalid_installation_id")+ await serializeRegistrationMutation(async () => {+ const response = await fetchImpl(+ `/api/community/notifications/devices/${encodeURIComponent(installationId)}`,+ { method: "DELETE", credentials: "same-origin" },+ )+ if (!response.ok) throw new Error("unregistration_failed")+ })+}++export async function unregisterCurrentMobileSystemNotification(+ fetchImpl: typeof fetch = fetch,+): Promise<void> {+ if (!isTauri() || !isMobile()) return+ const snapshot = await snapshotMobileSystemNotificationRegistration()+ await deleteMobileSystemNotificationRegistration(snapshot.installationId, fetchImpl)+}++export type MobileSystemNotificationRegistrationDeps = {+ checkPermission: () => Promise<MobileSystemNotificationPermission>+ requestPermission: () => Promise<MobileSystemNotificationPermission>+ snapshot: () => Promise<MobileSystemNotificationRegistration>+ register: (snapshot: MobileSystemNotificationRegistration) => Promise<void>+ acknowledge: (providerToken: string) => Promise<void>+ unregister: (installationId: string) => Promise<void>+ schedule: (callback: () => void, delayMs: number) => unknown+ cancel: (handle: unknown) => void+ retryDelaysMs?: readonly number[]+}++export function createMobileSystemNotificationRegistrationController(+ deps: MobileSystemNotificationRegistrationDeps,+) {+ let disposed = false+ let active: Promise<void> | null = null+ let rerun = false+ let pendingPrompt = false+ let retryAttempt = 0+ let retryTimer: unknown | undefined++ function clearRetry() {+ if (retryTimer === undefined) return+ deps.cancel(retryTimer)+ retryTimer = undefined+ }++ function scheduleRetry(allowPrompt: boolean) {+ if (disposed || retryTimer !== undefined) return+ const delays = deps.retryDelaysMs ?? RETRY_DELAYS_MS+ const delay = delays[retryAttempt]+ if (delay === undefined) return+ retryAttempt += 1+ retryTimer = deps.schedule(() => {+ retryTimer = undefined+ void sync(allowPrompt)+ }, delay)+ }++ async function runOnce(allowPrompt: boolean) {+ let permission = await deps.checkPermission()+ if (permission === "prompt" && allowPrompt) {+ permission = await deps.requestPermission()+ }+ if (permission === "prompt") return++ const snapshot = await deps.snapshot()+ if (permission === "denied") {+ await deps.unregister(snapshot.installationId)+ return+ }+ if (!snapshot.providerToken) return+ const providerToken = snapshot.providerToken+ await deps.register(snapshot)+ await deps.acknowledge(providerToken)+ }++ function sync(allowPrompt = false): Promise<void> {+ if (disposed) return Promise.resolve()+ pendingPrompt ||= allowPrompt+ rerun = true+ clearRetry()+ if (active) return active++ active = (async () => {+ while (rerun && !disposed) {+ rerun = false+ const promptThisRun = pendingPrompt+ pendingPrompt = false+ try {+ await runOnce(promptThisRun)+ retryAttempt = 0+ } catch {+ if (rerun) {+ pendingPrompt ||= promptThisRun+ continue+ }+ scheduleRetry(promptThisRun)+ }+ }+ })().finally(() => {+ active = null+ })+ return active+ }++ return {+ sync,+ dispose() {+ if (disposed) return+ disposed = true+ clearRetry()+ },+ }+}++export type MobileSystemNotificationActivationDeps = {+ take: () => Promise<MobileSystemNotificationActivation | null>+ revalidate: (+ activation: MobileSystemNotificationActivation,+ ) => Promise<MobileSystemNotificationDestination | null>+ navigate: (href: string) => void+ openInbox: () => Promise<void> | void+}++export function createMobileSystemNotificationActivationController(+ deps: MobileSystemNotificationActivationDeps,+) {+ let disposed = false+ let draining = false+ let rerun = false++ async function drain() {+ if (disposed) return+ if (draining) {+ rerun = true+ return+ }+ draining = true+ try {+ do {+ rerun = false+ let activation: MobileSystemNotificationActivation | null+ try {+ activation = await deps.take()+ } catch {+ if (!disposed) await deps.openInbox()+ continue+ }+ if (!activation || disposed) continue+ const destination = await deps.revalidate(activation).catch(() => null)+ if (disposed) continue+ if (destination) deps.navigate(destination.href)+ else await deps.openInbox()+ } while (rerun && !disposed)+ } finally {+ draining = false+ }+ }++ return {+ drain,+ dispose() {+ disposed = true+ },+ }+}++type SurfaceKind = "channel" | "forum" | "thread" | "dm"++function surfaceReceipt(value: unknown): { channelId: string; surfaceKind: SurfaceKind } | null {+ if (!isObject(value) || !hasExactKeys(value, ["channelId", "surfaceKind"])) return null+ if (!isSafeId(value.channelId)) return null+ if (value.surfaceKind !== "channel"+ && value.surfaceKind !== "forum"+ && value.surfaceKind !== "thread"+ && value.surfaceKind !== "dm") return null+ return { channelId: value.channelId, surfaceKind: value.surfaceKind }+}++export async function revalidateMobileSystemNotificationActivation(+ activation: MobileSystemNotificationActivation,+ fetchImpl: typeof fetch = fetch,+): Promise<MobileSystemNotificationDestination | null> {+ try {+ const messageResponse = await fetchImpl(+ `/api/community/channels/${encodeURIComponent(activation.targetId)}/messages?anchor=${encodeURIComponent(activation.messageId)}&limit=1`,+ { method: "GET", credentials: "same-origin", cache: "no-store" },+ )+ if (!messageResponse.ok) return null+ const messagePayload: unknown = await messageResponse.json()+ if (!isObject(messagePayload) || !Array.isArray(messagePayload.messages)) return null+ const receipt = surfaceReceipt(messagePayload.surfaceReceipt)+ if (!receipt || receipt.channelId !== activation.targetId) return null+ const message = messagePayload.messages.find((candidate) => (+ isObject(candidate)+ && candidate.id === activation.messageId+ && typeof candidate.seq === "number"+ && Number.isSafeInteger(candidate.seq)+ && candidate.seq > 0+ ))+ if (!isObject(message) || typeof message.seq !== "number") return null++ if (receipt.surfaceKind === "dm") {+ return {+ href: `/c/me/${encodeURIComponent(activation.targetId)}?seq=${message.seq}`,+ }+ }++ const channelResponse = await fetchImpl(+ `/api/community/channels/${encodeURIComponent(activation.targetId)}`,+ { method: "GET", credentials: "same-origin", cache: "no-store" },+ )+ if (!channelResponse.ok) return null+ const channel: unknown = await channelResponse.json()+ if (!isObject(channel)+ || channel.id !== activation.targetId+ || !isSafeId(channel.serverId)+ || (channel.type !== "text" && channel.type !== "forum" && channel.type !== "thread")) {+ return null+ }+ const expectedType = receipt.surfaceKind === "channel" ? "text" : receipt.surfaceKind+ if (channel.type !== expectedType) return null+ return {+ href: `/c/channels/${encodeURIComponent(channel.serverId)}/${encodeURIComponent(activation.targetId)}?msg=${encodeURIComponent(activation.messageId)}`,+ }+ } catch {+ return null+ }+}diff --git a/src/web/src/lib/community/notification-device-schema.test.ts b/src/web/src/lib/community/notification-device-schema.test.tsnew file mode 100644index 000000000..68087d6d0--- /dev/null+++ b/src/web/src/lib/community/notification-device-schema.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from "vitest";+import {+ hashProviderToken,+ isCookieHumanSameOrigin,+ notificationDeviceInstallationIdSchema,+ notificationDeviceRegistrationSchema,+} from "./notification-device-schema";++function registration(overrides: Record<string, unknown> = {}) {+ return {+ installationId: "installation-123",+ platform: "ios",+ providerEnvironment: "sandbox",+ providerToken: "fake-provider-token-123",+ appVersion: "1.2.3",+ ...overrides,+ };+}++describe("notification device registration schema", () => {+ it("accepts supported iOS and Android provider environments", () => {+ expect(notificationDeviceRegistrationSchema.safeParse(registration()).success)+ .toBe(true);+ expect(notificationDeviceRegistrationSchema.safeParse(registration({+ platform: "ios",+ providerEnvironment: "production",+ })).success).toBe(true);+ expect(notificationDeviceRegistrationSchema.safeParse(registration({+ platform: "android",+ providerEnvironment: "production",+ })).success).toBe(true);+ });++ it("rejects unsupported platform/environment pairs and client-owned fields", () => {+ expect(notificationDeviceRegistrationSchema.safeParse(registration({+ platform: "android",+ providerEnvironment: "sandbox",+ })).success).toBe(false);+ expect(notificationDeviceRegistrationSchema.safeParse(registration({+ platform: "web",+ })).success).toBe(false);++ for (const extra of [+ { userId: "other-user" },+ { providerTokenHash: "a".repeat(64) },+ { providerTokenEncrypted: "client-ciphertext" },+ { disabledAt: null },+ ]) {+ expect(notificationDeviceRegistrationSchema.safeParse(+ registration(extra),+ ).success).toBe(false);+ }+ });++ it("bounds every opaque client value and rejects empty or wrong types", () => {+ expect(notificationDeviceRegistrationSchema.safeParse(registration({+ installationId: "a".repeat(7),+ })).success).toBe(false);+ expect(notificationDeviceRegistrationSchema.safeParse(registration({+ installationId: "a".repeat(129),+ })).success).toBe(false);+ expect(notificationDeviceRegistrationSchema.safeParse(registration({+ installationId: "unsafe value",+ })).success).toBe(false);+ expect(notificationDeviceInstallationIdSchema.safeParse(+ "safe:installation_123",+ ).success).toBe(true);++ for (const invalid of [+ { providerToken: "short" },+ { providerToken: "a".repeat(4097) },+ { previousProviderToken: "short" },+ { previousProviderToken: "a".repeat(4097) },+ { appVersion: "" },+ { appVersion: "a".repeat(129) },+ { appVersion: null },+ { installationId: null },+ { providerToken: 123 },+ ]) {+ expect(notificationDeviceRegistrationSchema.safeParse(+ registration(invalid),+ ).success).toBe(false);+ }+ });++ it("hashes provider tokens deterministically with lowercase SHA-256", async () => {+ await expect(hashProviderToken("fake-provider-token-123")).resolves.toBe(+ "04e7ad517a6cc23fa2c94e37eee8c98fefb772de5d84f73b180c0d344d7c59ac",+ );+ await expect(hashProviderToken("fake-provider-token-456")).resolves.not.toBe(+ "04e7ad517a6cc23fa2c94e37eee8c98fefb772de5d84f73b180c0d344d7c59ac",+ );+ });+});++describe("notification device same-origin gate", () => {+ it("accepts the exact origin and matching loopback host", () => {+ expect(isCookieHumanSameOrigin(new Request(+ "https://alook.ai/api/community/notifications/devices",+ { headers: { Origin: "https://alook.ai" } },+ ))).toBe(true);+ expect(isCookieHumanSameOrigin(new Request(+ "http://127.0.0.1:3001/api/community/notifications/devices",+ {+ headers: {+ Host: "localhost:3001",+ Origin: "http://localhost:3001",+ },+ },+ ))).toBe(true);+ });++ it("rejects missing, malformed, or cross-origin requests", () => {+ expect(isCookieHumanSameOrigin(new Request(+ "https://alook.ai/api/community/notifications/devices",+ ))).toBe(false);+ expect(isCookieHumanSameOrigin(new Request(+ "https://alook.ai/api/community/notifications/devices",+ { headers: { Origin: "not-an-origin" } },+ ))).toBe(false);+ expect(isCookieHumanSameOrigin(new Request(+ "https://alook.ai/api/community/notifications/devices",+ { headers: { Origin: "https://evil.example" } },+ ))).toBe(false);+ });+});diff --git a/src/web/src/lib/community/notification-device-schema.ts b/src/web/src/lib/community/notification-device-schema.tsnew file mode 100644index 000000000..4925c6292--- /dev/null+++ b/src/web/src/lib/community/notification-device-schema.ts@@ -0,0 +1,71 @@+import { z } from "zod";++const INSTALLATION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;++export const notificationDeviceRegistrationSchema = z+ .object({+ installationId: z+ .string()+ .min(8)+ .max(128)+ .regex(INSTALLATION_ID_PATTERN, "invalid installation id"),+ platform: z.enum(["ios", "android"]),+ providerEnvironment: z.enum(["sandbox", "production"]),+ providerToken: z.string().min(16).max(4096),+ previousProviderToken: z.string().min(16).max(4096).optional(),+ appVersion: z.string().min(1).max(128).optional(),+ })+ .strict()+ .refine(+ ({ platform, providerEnvironment }) =>+ platform === "ios" || providerEnvironment === "production",+ {+ path: ["providerEnvironment"],+ message: "Android devices require the production environment",+ },+ );++export const notificationDeviceInstallationIdSchema = z+ .string()+ .min(8)+ .max(128)+ .regex(INSTALLATION_ID_PATTERN, "invalid installation id");++export async function hashProviderToken(token: string): Promise<string> {+ const digest = await crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(token),+ );+ return Array.from(new Uint8Array(digest), (byte) =>+ byte.toString(16).padStart(2, "0"),+ ).join("");+}++function isLoopbackHostname(hostname: string): boolean {+ return (+ hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]"+ );+}++export function isCookieHumanSameOrigin(req: Request): boolean {+ const originHeader = req.headers.get("Origin");+ if (!originHeader) return false;++ let originUrl: URL;+ try {+ originUrl = new URL(originHeader);+ } catch {+ return false;+ }++ if (originHeader !== originUrl.origin) return false;++ const requestUrl = new URL(req.url);+ if (originUrl.origin === requestUrl.origin) return true;++ return (+ isLoopbackHostname(originUrl.hostname) &&+ isLoopbackHostname(requestUrl.hostname) &&+ req.headers.get("Host") === originUrl.host+ );+}diff --git a/src/web/src/lib/community/wake-producer.test.ts b/src/web/src/lib/community/queue-producer.test.tssimilarity index 56%rename from src/web/src/lib/community/wake-producer.test.tsrename to src/web/src/lib/community/queue-producer.test.tsindex 8412c3d94..1a368c8c1 100644--- a/src/web/src/lib/community/wake-producer.test.ts+++ b/src/web/src/lib/community/queue-producer.test.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"const mockGetCloudflareContext = vi.fn(() => ({- env: { WAKE_QUEUE: { queue: true } },+ env: { TASK_QUEUE: { queue: true } },}))vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: () => mockGetCloudflareContext(),@@ -9,16 +9,16 @@ vi.mock("@opennextjs/cloudflare", () => ({const mockQueueSend = vi.fn()const mockDevSend = vi.fn()-const mockCreateQueueWakeTransport = vi.fn(() => ({ send: mockQueueSend }))-const mockCreateDevHttpWakeTransport = vi.fn(() => ({ send: mockDevSend }))-vi.mock("./wake-transport", () => ({- createQueueWakeTransport: (...args: unknown[]) => mockCreateQueueWakeTransport(...args),- createDevHttpWakeTransport: (...args: unknown[]) => mockCreateDevHttpWakeTransport(...args),+const mockCreateQueueTransport = vi.fn(() => ({ send: mockQueueSend }))+const mockCreateDevHttpQueueTransport = vi.fn(() => ({ send: mockDevSend }))+vi.mock("./queue-transport", () => ({+ createQueueTransport: (...args: unknown[]) => mockCreateQueueTransport(...args),+ createDevHttpQueueTransport: (...args: unknown[]) => mockCreateDevHttpQueueTransport(...args),}))-import { enqueueBotWakePayloads } from "./wake-producer"+import { enqueueQueueTasks } from "./queue-producer"-describe("enqueueBotWakePayloads", () => {+describe("enqueueQueueTasks", () => {beforeEach(() => {vi.clearAllMocks()vi.stubEnv("NODE_ENV", "test")@@ -29,35 +29,37 @@ describe("enqueueBotWakePayloads", () => {afterEach(() => vi.unstubAllEnvs())it("does not construct a transport for an empty plan", async () => {- await expect(enqueueBotWakePayloads([])).resolves.toBeUndefined()- expect(mockCreateQueueWakeTransport).not.toHaveBeenCalled()- expect(mockCreateDevHttpWakeTransport).not.toHaveBeenCalled()+ await expect(enqueueQueueTasks([])).resolves.toBeUndefined()+ expect(mockCreateQueueTransport).not.toHaveBeenCalled()+ expect(mockCreateDevHttpQueueTransport).not.toHaveBeenCalled()})it("sends only stable minimal payloads through the queue", async () => {const payloads = [- { messageId: "msg_1", botUserId: "bot_1" },- { messageId: "msg_1", botUserId: "bot_2" },+ { version: 1 as const, kind: "bot-wake" as const, messageId: "msg_1", botUserId: "bot_1" },+ { version: 1 as const, kind: "mobile-push" as const, messageId: "msg_1", userId: "user_1" },]- await enqueueBotWakePayloads(payloads)+ await enqueueQueueTasks(payloads)expect(mockQueueSend).toHaveBeenCalledWith(payloads)expect(mockDevSend).not.toHaveBeenCalled()})it("chunks the transport at 100 payloads", async () => {const payloads = Array.from({ length: 201 }, (_, index) => ({+ version: 1 as const,+ kind: "mobile-push" as const,messageId: "msg_1",- botUserId: `bot_${index}`,+ userId: `user_${index}`,}))- await enqueueBotWakePayloads(payloads)+ await enqueueQueueTasks(payloads)expect(mockQueueSend).toHaveBeenCalledTimes(3)expect(mockQueueSend.mock.calls.map(([chunk]) => chunk.length)).toEqual([100, 100, 1])})it("uses the dev HTTP transport only in development", async () => {vi.stubEnv("NODE_ENV", "development")- const payloads = [{ messageId: "msg_1", botUserId: "bot_1" }]- await enqueueBotWakePayloads(payloads)+ const payloads = [{ version: 1 as const, kind: "bot-wake" as const, messageId: "msg_1", botUserId: "bot_1" }]+ await enqueueQueueTasks(payloads)expect(mockDevSend).toHaveBeenCalledWith(payloads)expect(mockQueueSend).not.toHaveBeenCalled()})@@ -67,10 +69,12 @@ describe("enqueueBotWakePayloads", () => {.mockRejectedValueOnce(new Error("queue down")).mockResolvedValueOnce(undefined)const payloads = Array.from({ length: 101 }, (_, index) => ({+ version: 1 as const,+ kind: "bot-wake" as const,messageId: "msg_1",botUserId: `bot_${index}`,}))- await expect(enqueueBotWakePayloads(payloads)).rejects.toThrow("1 chunk")+ await expect(enqueueQueueTasks(payloads)).rejects.toThrow("1 chunk")expect(mockQueueSend).toHaveBeenCalledTimes(2)})})diff --git a/src/web/src/lib/community/queue-producer.ts b/src/web/src/lib/community/queue-producer.tsnew file mode 100644index 000000000..968e32eb9--- /dev/null+++ b/src/web/src/lib/community/queue-producer.ts@@ -0,0 +1,42 @@+/**+ * Transport-only producer for already planned committed-message queue tasks.+ * Audience, policy, readability, cursor, and bot selection stay in the+ * committed-message dispatcher.+ */+import { getCloudflareContext } from "@opennextjs/cloudflare"+import { createLogger, type AlookQueueTask } from "@alook/shared"+import { createDevHttpQueueTransport, createQueueTransport } from "./queue-transport"+import type { QueueTransport } from "./queue-transport"++const log = createLogger({ service: "community-queue-producer" })+const QUEUE_BATCH_SIZE = 100++function selectQueueTransport(env: Env): QueueTransport {+ return process.env.NODE_ENV === "development"+ ? createDevHttpQueueTransport(env)+ : createQueueTransport(env.TASK_QUEUE)+}++async function sendQueueTasks(env: Env, tasks: AlookQueueTask[]): Promise<void> {+ if (tasks.length === 0) return+ const transport = selectQueueTransport(env)+ const chunks: AlookQueueTask[][] = []+ for (let index = 0; index < tasks.length; index += QUEUE_BATCH_SIZE) {+ chunks.push(tasks.slice(index, index + QUEUE_BATCH_SIZE))+ }+ const results = await Promise.allSettled(chunks.map((chunk) => transport.send(chunk)))+ const failures = results.filter((result) => result.status === "rejected")+ if (failures.length > 0) {+ log.warn("queue_batch_delivery_failed", {+ chunkCount: chunks.length,+ failedChunkCount: failures.length,+ taskCount: tasks.length,+ })+ throw new Error(`queue delivery failed for ${failures.length} chunk(s)`)+ }+}++export function enqueueQueueTasks(tasks: AlookQueueTask[]): Promise<void> {+ const { env } = getCloudflareContext()+ return sendQueueTasks(env as Env, tasks)+}diff --git a/src/web/src/lib/community/wake-transport.test.ts b/src/web/src/lib/community/queue-transport.test.tssimilarity index 66%rename from src/web/src/lib/community/wake-transport.test.tsrename to src/web/src/lib/community/queue-transport.test.tsindex 5481e3a9d..ae01af587 100644--- a/src/web/src/lib/community/wake-transport.test.ts+++ b/src/web/src/lib/community/queue-transport.test.ts@@ -17,34 +17,37 @@ vi.mock("@alook/shared", async () => {}})-import { createQueueWakeTransport, createDevHttpWakeTransport } from "./wake-transport"+import { createQueueTransport, createDevHttpQueueTransport } from "./queue-transport"const payloads = [- { messageId: "msg_1", botUserId: "bot1" },- { messageId: "msg_1", botUserId: "bot2" },+ { version: 1 as const, kind: "bot-wake" as const, messageId: "msg_1", botUserId: "bot1" },+ { version: 1 as const, kind: "mobile-push" as const, messageId: "msg_1", userId: "user1" },]-describe("createQueueWakeTransport", () => {+describe("createQueueTransport", () => {it("sends the payloads as a single sendBatch call, one body per candidate", async () => {const mockSendBatch = vi.fn(async () => { })- const transport = createQueueWakeTransport({ sendBatch: mockSendBatch } as unknown as Queue<unknown>)+ const transport = createQueueTransport({ sendBatch: mockSendBatch } as unknown as Queue<unknown>)await transport.send(payloads)expect(mockSendBatch).toHaveBeenCalledTimes(1)const [messages] = mockSendBatch.mock.calls[0]!- expect(messages).toEqual([{ body: payloads[0] }, { body: payloads[1] }])+ expect(messages).toEqual([+ { body: payloads[0], contentType: "json" },+ { body: payloads[1], contentType: "json" },+ ])})it("propagates a sendBatch rejection (caller decides how to handle per-chunk failure)", async () => {const mockSendBatch = vi.fn(async () => { throw new Error("queue unavailable") })- const transport = createQueueWakeTransport({ sendBatch: mockSendBatch } as unknown as Queue<unknown>)+ const transport = createQueueTransport({ sendBatch: mockSendBatch } as unknown as Queue<unknown>)await expect(transport.send(payloads)).rejects.toThrow("queue unavailable")})})-describe("createDevHttpWakeTransport", () => {+describe("createDevHttpQueueTransport", () => {const originalFetch = globalThis.fetchconst mockGlobalFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()@@ -59,19 +62,19 @@ describe("createDevHttpWakeTransport", () => {function makeEnv(bindingFetch?: (...a: unknown[]) => Promise<Response>) {return {- WAKE_WORKER: bindingFetch ? { fetch: bindingFetch } : undefined,- DEV_WAKE_WORKER_URL: "http://dev-wake:8790",+ QUEUE_WORKER: bindingFetch ? { fetch: bindingFetch } : undefined,+ DEV_QUEUE_WORKER_URL: "http://dev-queue:8790",} as unknown as Env}- it("POSTs the full payload batch as JSON to the alook-wake-worker binding", async () => {+ it("POSTs the full task batch as JSON to the alook-queue-worker binding", async () => {const bindingFetch = vi.fn(async (url: string, init?: RequestInit) => {expect(url).toBe("http://internal/")expect(init?.method).toBe("POST")expect(JSON.parse(init!.body as string)).toEqual(payloads)return new Response(null, { status: 202 })})- const transport = createDevHttpWakeTransport(makeEnv(bindingFetch))+ const transport = createDevHttpQueueTransport(makeEnv(bindingFetch))await expect(transport.send(payloads)).resolves.toBeUndefined()expect(bindingFetch).toHaveBeenCalledTimes(1)@@ -80,18 +83,18 @@ describe("createDevHttpWakeTransport", () => {it("falls back to the raw dev HTTP URL when the binding is absent", async () => {mockGlobalFetch.mockResolvedValue(new Response(null, { status: 202 }))- const transport = createDevHttpWakeTransport(makeEnv())+ const transport = createDevHttpQueueTransport(makeEnv())await transport.send(payloads)expect(mockGlobalFetch).toHaveBeenCalledTimes(1)- expect(String(mockGlobalFetch.mock.calls[0]![0])).toBe("http://dev-wake:8790/")+ expect(String(mockGlobalFetch.mock.calls[0]![0])).toBe("http://dev-queue:8790/")})it("falls back to HTTP when the binding throws (getPlatformProxy binding unreachable)", async () => {const bindingFetch = vi.fn(async () => { throw new Error("binding missing") })mockGlobalFetch.mockResolvedValue(new Response(null, { status: 202 }))- const transport = createDevHttpWakeTransport(makeEnv(bindingFetch))+ const transport = createDevHttpQueueTransport(makeEnv(bindingFetch))await transport.send(payloads)@@ -101,13 +104,27 @@ describe("createDevHttpWakeTransport", () => {it("does not replay a processed batch through HTTP fallback when the binding reports partial candidate exhaustion", async () => {const bindingFetch = vi.fn(async () => Response.json(- { failed: [{ messageId: "msg_1", botUserId: "bot1" }] },+ { failed: [payloads[0]] },{ status: 207 },))mockGlobalFetch.mockResolvedValue(new Response(null, { status: 202 }))- const transport = createDevHttpWakeTransport(makeEnv(bindingFetch))+ const transport = createDevHttpQueueTransport(makeEnv(bindingFetch))- await expect(transport.send(payloads)).rejects.toThrow(/partial.*1 candidate/i)+ await expect(transport.send(payloads)).rejects.toThrow(/partial.*1 task/i)++ expect(bindingFetch).toHaveBeenCalledTimes(1)+ expect(mockGlobalFetch).not.toHaveBeenCalled()+ })++ it("accepts an exact mobile-push candidate in a partial response", async () => {+ const bindingFetch = vi.fn(async () => Response.json(+ { failed: [payloads[1]] },+ { status: 207 },+ ))+ mockGlobalFetch.mockResolvedValue(new Response(null, { status: 202 }))+ const transport = createDevHttpQueueTransport(makeEnv(bindingFetch))++ await expect(transport.send(payloads)).rejects.toThrow(/partial.*1 task/i)expect(bindingFetch).toHaveBeenCalledTimes(1)expect(mockGlobalFetch).not.toHaveBeenCalled()@@ -115,15 +132,17 @@ describe("createDevHttpWakeTransport", () => {it.each([{ name: "non-JSON body", body: "not json" },- { name: "missing botUserId", body: JSON.stringify({ failed: [{ messageId: "msg_1" }] }) },+ { name: "invalid common fields", body: JSON.stringify({ failed: [{ version: 2, kind: "bot-wake", messageId: "msg_1", botUserId: "bot1" }] }) },+ { name: "missing botUserId", body: JSON.stringify({ failed: [{ version: 1, kind: "bot-wake", messageId: "msg_1" }] }) },+ { name: "unknown kind", body: JSON.stringify({ failed: [{ version: 1, kind: "email", messageId: "msg_1", userId: "user1" }] }) },{ name: "unexpected top-level field", body: JSON.stringify({ failed: [], extra: true }) },{ name: "empty failed list", body: JSON.stringify({ failed: [] }) },- { name: "candidate outside the sent batch", body: JSON.stringify({ failed: [{ messageId: "other", botUserId: "bot1" }] }) },+ { name: "candidate outside the sent batch", body: JSON.stringify({ failed: [{ ...payloads[0], messageId: "other" }] }) },{ name: "duplicate failed tuple", body: JSON.stringify({ failed: [payloads[0], payloads[0]] }) },])("fails closed without fallback for an invalid 207 response: $name", async ({ body }) => {const bindingFetch = vi.fn(async () => new Response(body, { status: 207 }))mockGlobalFetch.mockResolvedValue(new Response(null, { status: 202 }))- const transport = createDevHttpWakeTransport(makeEnv(bindingFetch))+ const transport = createDevHttpQueueTransport(makeEnv(bindingFetch))await expect(transport.send(payloads)).rejects.toThrow(/invalid partial response/i)@@ -134,7 +153,7 @@ describe("createDevHttpWakeTransport", () => {it("still falls back to HTTP when the binding returns a worker-level 5xx", async () => {const bindingFetch = vi.fn(async () => new Response("worker unavailable", { status: 503 }))mockGlobalFetch.mockResolvedValue(new Response(null, { status: 202 }))- const transport = createDevHttpWakeTransport(makeEnv(bindingFetch))+ const transport = createDevHttpQueueTransport(makeEnv(bindingFetch))await expect(transport.send(payloads)).resolves.toBeUndefined()@@ -145,7 +164,7 @@ describe("createDevHttpWakeTransport", () => {it("throws when both the binding and the HTTP fallback respond non-OK (caller logs, dev-only best effort)", async () => {const bindingFetch = vi.fn(async () => new Response("boom", { status: 500 }))mockGlobalFetch.mockResolvedValue(new Response("still bad", { status: 500 }))- const transport = createDevHttpWakeTransport(makeEnv(bindingFetch))+ const transport = createDevHttpQueueTransport(makeEnv(bindingFetch))await expect(transport.send(payloads)).rejects.toThrow(/500/)})diff --git a/src/web/src/lib/community/queue-transport.ts b/src/web/src/lib/community/queue-transport.tsnew file mode 100644index 000000000..467811fbd--- /dev/null+++ b/src/web/src/lib/community/queue-transport.ts@@ -0,0 +1,108 @@+import { createLogger, DEV_QUEUE_WORKER_URL, parseStrictFailedSubset } from "@alook/shared"+import type { AlookQueueTask } from "@alook/shared"+import { fetchViaBindingOrDevFallback } from "../dev-binding-fetch"++const log = createLogger({ service: "queue-transport" })++function isExactFailedCandidate(value: unknown): value is AlookQueueTask {+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false+ const keys = Object.keys(value)+ const candidate = value as Record<string, unknown>+ if (+ candidate.version !== 1+ || typeof candidate.kind !== "string"+ || typeof candidate.messageId !== "string"+ || candidate.messageId.length === 0+ ) return false+ if (candidate.kind === "bot-wake") {+ return keys.length === 4+ && typeof candidate.botUserId === "string"+ && candidate.botUserId.length > 0+ }+ if (candidate.kind === "mobile-push") {+ return keys.length === 4+ && typeof candidate.userId === "string"+ && candidate.userId.length > 0+ }+ return false+}++function parsePartialFailure(value: unknown, tasks: AlookQueueTask[]): AlookQueueTask[] | null {+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null+ const keys = Object.keys(value)+ if (keys.length !== 1 || keys[0] !== "failed") return null++ return parseStrictFailedSubset(+ (value as Record<string, unknown>).failed,+ tasks,+ {+ isTarget: isExactFailedCandidate,+ key: (item) => JSON.stringify([+ item.kind,+ item.messageId,+ item.kind === "bot-wake" ? item.botUserId : item.userId,+ ]),+ },+ )+}++/**+ * The committed-message dispatcher hands already-planned versioned tasks to+ * exactly one of these transports. Neither transport owns audience or policy.+ */+export interface QueueTransport {+ send(tasks: AlookQueueTask[]): Promise<void>+}++/** Production (and any non-`development` environment): the real Cloudflare Queue. */+export function createQueueTransport(queue: Queue<AlookQueueTask>): QueueTransport {+ return {+ async send(tasks) {+ await queue.sendBatch(tasks.map((body) => ({ body, contentType: "json" })))+ },+ }+}++/**+ * Dev-only. Local Cloudflare Queues simulation cannot bridge separate+ * `wrangler dev`/`next dev` processes (plans/minimal-wake-queue-unread-notice.md)+ * — every cross-process Queue send from `next dev` lands nowhere. This+ * transport instead calls the real `alook-queue-worker` process directly over+ * HTTP (its `fetch()` dev entrypoint, see `src/queue-worker/src/index.ts`),+ * via the `QUEUE_WORKER` service binding with the same binding-first/+ * HTTP-fallback reliability pattern `broadcast.ts` uses for `WS_DO_WORKER`+ * (`next dev`'s `getPlatformProxy` service bindings to separately-run+ * `wrangler dev` workers are not reliably reachable on their own). The+ * task then runs through the same worker task handler as production traffic.+ */+export function createDevHttpQueueTransport(env: Env): QueueTransport {+ return {+ async send(tasks) {+ const res = await fetchViaBindingOrDevFallback(+ env.QUEUE_WORKER,+ env.DEV_QUEUE_WORKER_URL || DEV_QUEUE_WORKER_URL,+ "/",+ {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(tasks),+ },+ { logPrefix: "queue_transport", log, label: `${tasks.length}_tasks` },+ )+ if (res.status === 207) {+ let body: unknown+ try {+ body = await res.json()+ } catch {+ throw new Error("dev queue transport: invalid partial response")+ }+ const failed = parsePartialFailure(body, tasks)+ if (!failed) throw new Error("dev queue transport: invalid partial response")+ throw new Error(`dev queue transport partial failure: ${failed.length} task(s) exhausted`)+ }+ if (!res.ok) {+ throw new Error(`dev queue transport: alook-queue-worker responded ${res.status}`)+ }+ },+ }+}diff --git a/src/web/src/lib/community/system-notification-route.test.ts b/src/web/src/lib/community/system-notification-route.test.tsnew file mode 100644index 000000000..5571242bd--- /dev/null+++ b/src/web/src/lib/community/system-notification-route.test.ts@@ -0,0 +1,110 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import {+ desktopSystemNotificationHref,+ parseDesktopSystemNotificationActivation,+ revalidateDesktopSystemNotificationTarget,+ type DesktopSystemNotificationActivation,+} from "./system-notification-route"++const activation: DesktopSystemNotificationActivation = {+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ target: {+ kind: "server",+ serverId: "server_1",+ channelId: "channel-2",+ messageId: "message_3",+ seq: 9,+ },+}++afterEach(() => vi.unstubAllGlobals())++describe("desktop system notification routes", () => {+ it("accepts only exact allowlisted activation fields", () => {+ expect(parseDesktopSystemNotificationActivation(activation)).toEqual(activation)+ expect(parseDesktopSystemNotificationActivation({ ...activation, href: "https://evil.test" })).toBeNull()+ expect(parseDesktopSystemNotificationActivation({+ ...activation,+ target: { ...activation.target, serverId: "../escape" },+ })).toBeNull()+ expect(parseDesktopSystemNotificationActivation({+ ...activation,+ target: { ...activation.target, extra: true },+ })).toBeNull()+ })++ it("accepts an exact DM activation and rejects malformed or unknown targets", () => {+ const dmActivation: DesktopSystemNotificationActivation = {+ notificationId: activation.notificationId,+ target: {+ kind: "dm",+ channelId: "dm_1",+ messageId: "message_4",+ seq: 12,+ },+ }+ expect(parseDesktopSystemNotificationActivation(dmActivation)).toEqual(dmActivation)+ expect(parseDesktopSystemNotificationActivation({+ ...dmActivation,+ target: { ...dmActivation.target, extra: true },+ })).toBeNull()+ expect(parseDesktopSystemNotificationActivation({+ ...dmActivation,+ target: { ...dmActivation.target, channelId: "../escape" },+ })).toBeNull()+ expect(parseDesktopSystemNotificationActivation({+ ...dmActivation,+ target: { ...dmActivation.target, kind: "external" },+ })).toBeNull()+ })++ it("derives only first-party server and DM routes", () => {+ expect(desktopSystemNotificationHref(activation.target)).toBe(+ "/c/channels/server_1/channel-2?msg=message_3",+ )+ expect(desktopSystemNotificationHref({+ kind: "dm",+ channelId: "dm_1",+ messageId: "message_4",+ seq: 12,+ })).toBe("/c/me/dm_1?seq=12")+ })++ it("revalidates the exact message through the authenticated API", async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ id: "message_3" }), {+ status: 200,+ headers: { "content-type": "application/json" },+ }))+ await expect(revalidateDesktopSystemNotificationTarget(activation.target, fetchImpl)).resolves.toBe(true)+ expect(fetchImpl).toHaveBeenCalledWith("/api/community/messages/message_3", {+ method: "GET",+ credentials: "same-origin",+ cache: "no-store",+ })+ })++ it("uses the global fetch implementation by default", async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ id: "message_3" }), {+ status: 200,+ headers: { "content-type": "application/json" },+ }))+ vi.stubGlobal("fetch", fetchImpl)++ await expect(revalidateDesktopSystemNotificationTarget(activation.target)).resolves.toBe(true)+ expect(fetchImpl).toHaveBeenCalledOnce()+ })++ it("rejects deleted, revoked, malformed, and mismatched responses", async () => {+ for (const response of [+ new Response(null, { status: 404 }),+ new Response(null, { status: 403 }),+ new Response("nope", { status: 200 }),+ new Response(JSON.stringify({ id: "other" }), { status: 200 }),+ ]) {+ await expect(revalidateDesktopSystemNotificationTarget(+ activation.target,+ vi.fn(async () => response),+ )).resolves.toBe(false)+ }+ })+})diff --git a/src/web/src/lib/community/system-notification-route.ts b/src/web/src/lib/community/system-notification-route.tsnew file mode 100644index 000000000..496c46459--- /dev/null+++ b/src/web/src/lib/community/system-notification-route.ts@@ -0,0 +1,105 @@+export type DesktopSystemNotificationTarget =+ | {+ kind: "server"+ serverId: string+ channelId: string+ messageId: string+ seq: number+ }+ | {+ kind: "dm"+ channelId: string+ messageId: string+ seq: number+ }++export type DesktopSystemNotificationActivation = {+ notificationId: string+ target: DesktopSystemNotificationTarget+}++const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/+const NOTIFICATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i++function exactKeys(value: Record<string, unknown>, keys: readonly string[]) {+ const actual = Object.keys(value).sort()+ const expected = [...keys].sort()+ return actual.length === expected.length && actual.every((key, index) => key === expected[index])+}++function isObject(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value)+}++function safeId(value: unknown): value is string {+ return typeof value === "string" && SAFE_ID.test(value)+}++function safeSeq(value: unknown): value is number {+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0+}++export function parseDesktopSystemNotificationActivation(+ value: unknown,+): DesktopSystemNotificationActivation | null {+ if (!isObject(value) || !exactKeys(value, ["notificationId", "target"])) return null+ if (typeof value.notificationId !== "string" || !NOTIFICATION_ID.test(value.notificationId)) return null+ if (!isObject(value.target) || typeof value.target.kind !== "string") return null++ const target = value.target+ if (target.kind === "server") {+ if (!exactKeys(target, ["kind", "serverId", "channelId", "messageId", "seq"])) return null+ if (!safeId(target.serverId) || !safeId(target.channelId) || !safeId(target.messageId) || !safeSeq(target.seq)) return null+ return {+ notificationId: value.notificationId,+ target: {+ kind: "server",+ serverId: target.serverId,+ channelId: target.channelId,+ messageId: target.messageId,+ seq: target.seq,+ },+ }+ }++ if (target.kind === "dm") {+ if (!exactKeys(target, ["kind", "channelId", "messageId", "seq"])) return null+ if (!safeId(target.channelId) || !safeId(target.messageId) || !safeSeq(target.seq)) return null+ return {+ notificationId: value.notificationId,+ target: {+ kind: "dm",+ channelId: target.channelId,+ messageId: target.messageId,+ seq: target.seq,+ },+ }+ }++ return null+}++export function desktopSystemNotificationHref(target: DesktopSystemNotificationTarget): string {+ if (target.kind === "dm") {+ return `/c/me/${encodeURIComponent(target.channelId)}?seq=${target.seq}`+ }+ return `/c/channels/${encodeURIComponent(target.serverId)}/${encodeURIComponent(target.channelId)}?msg=${encodeURIComponent(target.messageId)}`+}++export async function revalidateDesktopSystemNotificationTarget(+ target: DesktopSystemNotificationTarget,+ fetchImpl: typeof fetch = fetch,+): Promise<boolean> {+ try {+ const response = await fetchImpl(`/api/community/messages/${encodeURIComponent(target.messageId)}`, {+ method: "GET",+ credentials: "same-origin",+ cache: "no-store",+ })+ if (!response.ok) return false+ const payload: unknown = await response.json()+ return isObject(payload) && payload.id === target.messageId+ } catch {+ return false+ }+}diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.tsdeleted file mode 100644index 8935551bf..000000000--- a/src/web/src/lib/community/wake-producer.ts+++ /dev/null@@ -1,43 +0,0 @@-/**- * Transport-only producer for already planned committed-message wake targets.- * Audience, policy, readability, cursor, and bot selection live in the- * committed-message dispatcher; this seam only chunks stable minimal payloads- * onto the environment-appropriate transport.- */-import { getCloudflareContext } from "@opennextjs/cloudflare"-import { createLogger, type WakePayload } from "@alook/shared"-import { createDevHttpWakeTransport, createQueueWakeTransport } from "./wake-transport"-import type { WakeTransport } from "./wake-transport"--const log = createLogger({ service: "community-wake-producer" })-const WAKE_BATCH_SIZE = 100--function selectWakeTransport(env: Env): WakeTransport {- return process.env.NODE_ENV === "development"- ? createDevHttpWakeTransport(env)- : createQueueWakeTransport(env.WAKE_QUEUE)-}--async function sendWakePayloads(env: Env, payloads: WakePayload[]): Promise<void> {- if (payloads.length === 0) return- const transport = selectWakeTransport(env)- const chunks: WakePayload[][] = []- for (let index = 0; index < payloads.length; index += WAKE_BATCH_SIZE) {- chunks.push(payloads.slice(index, index + WAKE_BATCH_SIZE))- }- const results = await Promise.allSettled(chunks.map((chunk) => transport.send(chunk)))- const failures = results.filter((result) => result.status === "rejected")- if (failures.length > 0) {- log.warn("wake_batch_delivery_failed", {- chunkCount: chunks.length,- failedChunkCount: failures.length,- payloadCount: payloads.length,- })- throw new Error(`wake delivery failed for ${failures.length} chunk(s)`)- }-}--export function enqueueBotWakePayloads(payloads: WakePayload[]): Promise<void> {- const { env } = getCloudflareContext()- return sendWakePayloads(env as Env, payloads)-}diff --git a/src/web/src/lib/community/wake-transport.ts b/src/web/src/lib/community/wake-transport.tsdeleted file mode 100644index 1d12d86b1..000000000--- a/src/web/src/lib/community/wake-transport.ts+++ /dev/null@@ -1,99 +0,0 @@-import { createLogger, DEV_WAKE_WORKER_URL, parseStrictFailedSubset } from "@alook/shared"-import type { WakePayload } from "@alook/shared"-import { fetchViaBindingOrDevFallback } from "../dev-binding-fetch"--const log = createLogger({ service: "wake-transport" })--function isExactFailedCandidate(value: unknown): value is WakePayload {- if (typeof value !== "object" || value === null || Array.isArray(value)) return false- const keys = Object.keys(value)- if (keys.length !== 2 || !keys.includes("messageId") || !keys.includes("botUserId")) return false- const candidate = value as Record<string, unknown>- return typeof candidate.messageId === "string"- && candidate.messageId.length > 0- && typeof candidate.botUserId === "string"- && candidate.botUserId.length > 0-}--function parsePartialFailure(value: unknown, payloads: WakePayload[]): WakePayload[] | null {- if (typeof value !== "object" || value === null || Array.isArray(value)) return null- const keys = Object.keys(value)- if (keys.length !== 1 || keys[0] !== "failed") return null-- return parseStrictFailedSubset(- (value as Record<string, unknown>).failed,- payloads,- {- isTarget: isExactFailedCandidate,- key: (item) => `${item.messageId}\u0000${item.botUserId}`,- },- )-}--/**- * How the committed-message dispatcher hands a batch of wake candidates to- * will actually resolve them. Exactly two implementations below — neither- * caller (`wake-producer.ts`) ever talks to `WAKE_QUEUE`/`WAKE_WORKER`- * directly, and neither ever re-implements "rebuild from D1, skip or- * forward" (that logic lives once, in `@alook/shared`'s- * `dispatchOneUnreadWake`, and is exercised by whichever transport actually- * runs it).- */-export interface WakeTransport {- send(payloads: WakePayload[]): Promise<void>-}--/** Production (and any non-`development` environment): the real Cloudflare Queue. */-export function createQueueWakeTransport(queue: Queue<WakePayload>): WakeTransport {- return {- async send(payloads) {- await queue.sendBatch(payloads.map((body) => ({ body })))- },- }-}--/**- * Dev-only. Local Cloudflare Queues simulation cannot bridge separate- * `wrangler dev`/`next dev` processes (plans/minimal-wake-queue-unread-notice.md)- * — every `WAKE_QUEUE.sendBatch()` call from `next dev` lands nowhere. This- * transport instead calls the REAL `alook-wake-worker` process directly over- * HTTP (its `fetch()` dev entrypoint, see `src/wake-worker/src/index.ts`),- * via the `WAKE_WORKER` service binding with the same binding-first/- * HTTP-fallback reliability pattern `broadcast.ts` uses for `WS_DO_WORKER`- * (`next dev`'s `getPlatformProxy` service bindings to separately-run- * `wrangler dev` workers are not reliably reachable on their own). The- * candidate then gets resolved by `alook-wake-worker`'s own process, against- * the real D1 database, with a real forward to `alook-ws-do` — the actual- * production code path, not a local stand-in for it.- */-export function createDevHttpWakeTransport(env: Env): WakeTransport {- return {- async send(payloads) {- const res = await fetchViaBindingOrDevFallback(- env.WAKE_WORKER,- env.DEV_WAKE_WORKER_URL || DEV_WAKE_WORKER_URL,- "/",- {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify(payloads),- },- { logPrefix: "wake_transport", log, label: `${payloads.length}_candidates` },- )- if (res.status === 207) {- let body: unknown- try {- body = await res.json()- } catch {- throw new Error("dev wake transport: invalid partial response")- }- const failed = parsePartialFailure(body, payloads)- if (!failed) throw new Error("dev wake transport: invalid partial response")- throw new Error(`dev wake transport partial failure: ${failed.length} candidate(s) exhausted`)- }- if (!res.ok) {- throw new Error(`dev wake transport: alook-wake-worker responded ${res.status}`)- }- },- }-}diff --git a/src/web/src/lib/dev-binding-fetch.ts b/src/web/src/lib/dev-binding-fetch.tsindex 848a996aa..7e75ac0a1 100644--- a/src/web/src/lib/dev-binding-fetch.ts+++ b/src/web/src/lib/dev-binding-fetch.ts@@ -8,7 +8,7 @@ interface FetcherLike {* Service-binding-first, dev-HTTP-fallback fetch. Extracted from* `broadcast.ts`'s original `wsDoFetch` (that's still the canonical* caller/behavior spec — see its tests) because `wake-transport.ts` needs- * the EXACT same shape of fallback for `WAKE_WORKER`: `next dev`'s+ * the EXACT same shape of fallback for `QUEUE_WORKER`: `next dev`'s* `getPlatformProxy` service bindings to separately-run `wrangler dev`* workers are not reliably reachable, so every cross-worker call from* `src/web` needs "try the real binding, fall back to a plain HTTP URL atdiff --git a/src/web/src/lib/utils-getmode.test.ts b/src/web/src/lib/utils-getmode.test.tsindex e2d3b8ae0..074ad2823 100644--- a/src/web/src/lib/utils-getmode.test.ts+++ b/src/web/src/lib/utils-getmode.test.ts@@ -10,7 +10,7 @@ vi.mock("@alook/shared", () => ({daemonCommand: vi.fn(() => "npx @alook/cli daemon start"),isTauri: (...args: any[]) => mockIsTauri(...args),isMobile: (...args: any[]) => mockIsMobile(...args),- DEV_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789, wakeWorker: 8790 },+ DEV_PORTS: { web: 3000, emailWorker: 8787, wsDo: 8789, queueWorker: 8790 },devWsDoPort: () => 8789,}));diff --git a/src/web/src/test/e2e-ui/05-mention-bot.spec.ts b/src/web/src/test/e2e-ui/05-mention-bot.spec.tsindex 2c80c0aae..a3d11297d 100644--- a/src/web/src/test/e2e-ui/05-mention-bot.spec.ts+++ b/src/web/src/test/e2e-ui/05-mention-bot.spec.ts@@ -5,7 +5,7 @@ import { seedServer, seedChannel, seedJoinServer } from "./_fixtures/seed"// Journey 5 — @-mentions. The mention popup shows SERVER MEMBERS (regression// a4672ca2: not the viewer's friends). Bot reply is out of scope (no daemon /-// wake-worker); we assert the mention UI + that a mention produces an inbox+// queue-worker); we assert the mention UI + that a mention produces an inbox// entry for the mentioned user.test.describe.serial("mentions", () => {let serverId: stringdiff --git a/src/web/src/test/e2e-ui/58-system-notifications.spec.ts b/src/web/src/test/e2e-ui/58-system-notifications.spec.tsnew file mode 100644index 000000000..8d2e5b11d--- /dev/null+++ b/src/web/src/test/e2e-ui/58-system-notifications.spec.ts@@ -0,0 +1,135 @@+import type { Page } from "@playwright/test"+import { expect, test } from "./_fixtures/community-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"++type Activation = {+ notificationId: string+ target: {+ kind: "server"+ serverId: string+ channelId: string+ messageId: string+ seq: number+ }+}++async function installDesktopNotificationBridge(+ page: Page,+ activation: Activation | null = null,+) {+ await page.addInitScript((initialActivation) => {+ const usedKey = initialActivation+ ? `notification-activation:${initialActivation.notificationId}`+ : ""+ let pending = initialActivation && sessionStorage.getItem(usedKey) !== "used"+ ? initialActivation+ : null+ const state = {+ shows: [] as unknown[],+ listener: null as null | { onmessage?: (value: unknown) => void },+ }+ class Channel {+ onmessage?: (value: unknown) => void+ }+ Object.defineProperty(window, "__desktopNotificationTest", {+ configurable: true,+ value: state,+ })+ Object.defineProperty(window, "__TAURI__", {+ configurable: true,+ value: {+ core: {+ Channel,+ invoke: async (command: string, args?: Record<string, unknown>) => {+ if (command === "desktop_system_notification_listen") {+ state.listener = args?.channel as typeof state.listener+ return 1+ }+ if (command === "desktop_system_notification_unlisten") return undefined+ if (command === "desktop_system_notification_take_activation") {+ const value = pending+ pending = null+ if (value) sessionStorage.setItem(usedKey, "used")+ return value+ }+ if (command === "desktop_system_notification_show") {+ state.shows.push(args?.candidate)+ return undefined+ }+ return undefined+ },+ },+ },+ })+ }, activation)+}++async function shownNotifications(page: Page) {+ return page.evaluate(() => (+ window as typeof window & { __desktopNotificationTest: { shows: unknown[] } }+ ).__desktopNotificationTest.shows)+}++test.describe.serial("desktop system notifications", () => {+ test("a delivered message+bump bundle invokes the native command with the exact target", async ({ asUser }) => {+ const stamp = Date.now()+ const serverId = await seedServer("alice", `notification-live-${stamp}`)+ const channelId = await seedChannel("alice", serverId, `notification-live-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ const bob = await asUser("bob")+ await installDesktopNotificationBridge(bob.page)+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")++ const body = `Native notification ${stamp}`+ const messageId = await seedMessage("alice", channelId, body)+ await expect.poll(() => shownNotifications(bob.page)).toEqual([+ expect.objectContaining({+ title: expect.any(String),+ body,+ target: {+ kind: "server",+ serverId,+ channelId,+ messageId,+ seq: expect.any(Number),+ },+ }),+ ])+ })++ test("a cold activation revalidates access and opens the exact message", async ({ asUser }) => {+ test.setTimeout(90_000)+ const stamp = Date.now()+ const serverId = await seedServer("alice", `notification-cold-${stamp}`)+ const channelId = await seedChannel("alice", serverId, `notification-cold-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ const messageId = await seedMessage("alice", channelId, `Cold activation ${stamp}`)+ const bob = await asUser("bob")+ await installDesktopNotificationBridge(bob.page, {+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71e",+ target: { kind: "server", serverId, channelId, messageId, seq: 1 },+ })++ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")+ await expect(bob.page).toHaveURL(new RegExp(`/c/channels/${serverId}/${channelId}`))+ await expect(bob.page.getByTestId(tid.message(messageId))).toBeVisible({ timeout: 30_000 })+ })++ test("a deleted or inaccessible activation falls back to Inbox", async ({ asUser }) => {+ const bob = await asUser("bob")+ await installDesktopNotificationBridge(bob.page, {+ notificationId: "4f3bb3fd-5d7f-4a26-8e0e-3ddd1154f71f",+ target: {+ kind: "server",+ serverId: "missing_server",+ channelId: "missing_channel",+ messageId: "missing_message",+ seq: 1,+ },+ })+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")+ await expect(bob.page.getByTestId(tid.inboxTrigger)).toHaveAttribute("aria-expanded", "true")+ })+})diff --git a/src/web/vitest.runtime.config.mts b/src/web/vitest.runtime.config.mtsindex 4373bf590..753703313 100644--- a/src/web/vitest.runtime.config.mts+++ b/src/web/vitest.runtime.config.mts@@ -47,7 +47,7 @@ export default defineProject({WS_DO_WORKER: "ws-do-runtime-stub",EMAIL_WORKER: () => new Response("email"),BLOG_WORKER: () => new Response("blog"),- WAKE_WORKER: () => new Response("wake"),+ QUEUE_WORKER: () => new Response("queue"),},},}),diff --git a/src/web/wrangler.toml b/src/web/wrangler.tomlindex bba2712d4..84c2f14f7 100644--- a/src/web/wrangler.toml+++ b/src/web/wrangler.toml@@ -79,20 +79,19 @@ service = "alook-email-worker"binding = "BLOG_WORKER"service = "alook-blog"-# Bot wake-on-unread producer — see plans/community-agent-cli-bridge.md §8.-# Consumer is the separate `alook-wake-worker` (src/wake-worker).+# Versioned background-task producer. The consumer is `alook-queue-worker`.[[queues.producers]]-binding = "WAKE_QUEUE"-queue = "alook-wake"+binding = "TASK_QUEUE"+queue = "alook-queue"-# Dev-only direct path to the `alook-wake-worker` HTTP dev endpoint — local+# Dev-only direct path to the `alook-queue-worker` HTTP dev endpoint — local# Cloudflare Queues can't bridge separate `wrangler dev`/`next dev` processes-# (see plans/minimal-wake-queue-unread-notice.md), so `wake-transport.ts` uses+# (see plans/minimal-wake-queue-unread-notice.md), so `queue-transport.ts` uses# this binding (with an HTTP fallback, like `WS_DO_WORKER`) instead of-# `WAKE_QUEUE` when `NODE_ENV === "development"`. Unused in production.+# `TASK_QUEUE` when `NODE_ENV === "development"`. Unused in production.[[services]]-binding = "WAKE_WORKER"-service = "alook-wake-worker"+binding = "QUEUE_WORKER"+service = "alook-queue-worker"[[kv_namespaces]]binding = "CACHE_KV"diff --git a/src/ws-do/src/routes/audit-broadcast.ts b/src/ws-do/src/routes/audit-broadcast.tsindex e22328e06..b34c6748b 100644--- a/src/ws-do/src/routes/audit-broadcast.ts+++ b/src/ws-do/src/routes/audit-broadcast.ts@@ -8,12 +8,12 @@ import { createInternalCommunityUserBroadcastRequest } from "../internal-user-brimport { logCommunityBrowserEventRejected } from "../community-browser-event-ingress"export async function handleAuditBroadcast({ request, env, url, log }: RouterContext): Promise<Response | null> {- // POST /internal/broadcast-bot-audit-event — the wake-worker calls this+ // POST /internal/broadcast-bot-audit-event — the queue-worker calls this// right after `insertBotAuditWakeTrigger` writes a `wake_trigger` row, so// the owner's UI receives the audit-event WS frame in the same beat as// the D1 insert (matching the daemon-originating path at// `ws-durable.ts:906-915`). Reachable ONLY via service binding- // (`WS_DO_WORKER: Fetcher` in wake-worker's wrangler.toml), so origin is+ // (`WS_DO_WORKER: Fetcher` in queue-worker's wrangler.toml), so origin is// implicitly restricted to same-project workers.//// Body: { botId, ownerUserId, id, kind, payload, createdAt, sessionId?,diff --git a/src/ws-do/src/routes/message-delivery.test.ts b/src/ws-do/src/routes/message-delivery.test.tsindex 686f1013c..48c9f23ad 100644--- a/src/ws-do/src/routes/message-delivery.test.ts+++ b/src/ws-do/src/routes/message-delivery.test.ts@@ -122,7 +122,7 @@ describe("message delivery route", () => {expect(inputs.get("transient")![0]).toEqual(inputs.get("transient")![1])})- it("inverts buckets into one ordered bundle per user", async () => {+ it("keeps message and unread events in one ordered bundle per desktop user", async () => {doMock.stubFetch.mockImplementation(successfulReceipt)const response = await handler.fetch(await deliveryRequest(), env as never)diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.tsindex 471221d13..5e4ca7eee 100644--- a/tests/integration/daemon/control-plane.test.ts+++ b/tests/integration/daemon/control-plane.test.ts@@ -5,7 +5,7 @@** POST /api/community/channels/:id/messages (human, real HTTP)* → committed message dispatcher → wake producer (dev HTTP transport)- * → alook-wake-worker (real process) → dispatchOneUnreadWake+ * → alook-queue-worker (real process) → dispatchOneUnreadWake* → sendWakeToMachine → alook-ws-do (real DO) → the daemon's real* `WsControlChannel`, over a real WebSocket, receives `agent:wake`* → the test (playing the "agent" — no CLI spawned) replies via the@@ -13,8 +13,8 @@* → the reply is visible via a real read of the channel.** Requires `wrangler dev` (`@alook/web`), `@alook/ws-do dev`, and- * `@alook/wake-worker dev` all already running (same servers CI's `e2e`- * job boots for `@alook/cli`'s integration tests, plus `wake-worker`).+ * `@alook/queue-worker dev` all already running (same servers CI's `e2e`+ * job boots for `@alook/cli`'s integration tests, plus `queue-worker`).*/import { describe, it, expect, beforeAll, afterAll } from "vitest"import { WebSocket } from "ws"@@ -148,7 +148,7 @@ describe("daemon control plane — real ws-do wake round-trip", () => {// Human owner posts a real message — exercises the real wake-producer// path (committed dispatcher → wake producer → dev HTTP transport →- // wake-worker → forward-agent-wake → the DO → our open socket).+ // queue-worker → forward-agent-wake → the DO → our open socket).const postRes = await sessionRequest(`/api/community/channels/${fixture.channelId}/messages`, cookie, {method: "POST",headers: { "content-type": "application/json" },diff --git a/tests/integration/daemon/setup.ts b/tests/integration/daemon/setup.tsindex 2d99064c1..7e87111c6 100644--- a/tests/integration/daemon/setup.ts+++ b/tests/integration/daemon/setup.ts@@ -4,6 +4,6 @@ if (!process.env.APP_URL) {if (!process.env.WS_DO_URL) {process.env.WS_DO_URL = "ws://localhost:8789"}-if (!process.env.WAKE_WORKER_HEALTH_URL) {- process.env.WAKE_WORKER_HEALTH_URL = "http://localhost:8790"+if (!process.env.QUEUE_WORKER_HEALTH_URL) {+ process.env.QUEUE_WORKER_HEALTH_URL = "http://localhost:8790"}diff --git a/vitest.config.ts b/vitest.config.tsindex 1d61ec0e7..52958055a 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -12,14 +12,14 @@ export default defineConfig({"src/daemon/agent-driver","src/email-worker","src/ws-do",- "src/wake-worker",+ "src/queue-worker","src/app","tests/utils","scripts/ci","src/web/vitest.dom.config.ts","src/ws-do/vitest.runtime.config.mts","src/email-worker/vitest.runtime.config.mts",- "src/wake-worker/vitest.runtime.config.mts",+ "src/queue-worker/vitest.runtime.config.mts","src/web/vitest.runtime.config.mts",],coverage: {