diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..bcd15b7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +**/node_modules +**/dist +.git +.github +docs +**/*.test.ts +.DS_Store diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..f2de637 --- /dev/null +++ b/.env.example @@ -0,0 +1,9 @@ +# Required: the handle or DID whose `rfd` repo this instance serves. +RFD_OWNER=you.example.com + +# Optional (defaults shown). +RFD_REPO_NAME=rfd +BOBBIN_URL=https://api.tangled.org +RFD_CACHE_TTL=60 +# PUBLIC_ORIGIN=https://rfd.example.com +# PORT is provided by the host (Railway/Docker); the server honors it. diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml new file mode 100644 index 0000000..72cb1c3 --- /dev/null +++ b/.github/workflows/docker-publish.yml @@ -0,0 +1,41 @@ +name: Publish Docker image + +on: + push: + tags: ['v*'] + workflow_dispatch: + +jobs: + publish: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Derive tags + id: meta + uses: docker/metadata-action@v5 + with: + images: natemoo-re/rfd + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..bfc5f5d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +# syntax=docker/dockerfile:1 + +FROM node:24-slim AS base +ENV PNPM_HOME=/pnpm PATH=/pnpm:$PATH +RUN corepack enable +WORKDIR /app + +# --- build stage: install the workspace and build the www server --- +FROM base AS build +COPY pnpm-workspace.yaml pnpm-lock.yaml package.json tsconfig.json ./ +COPY packages/core/package.json ./packages/core/package.json +COPY packages/www/package.json ./packages/www/package.json +RUN pnpm install --frozen-lockfile +COPY packages ./packages +RUN pnpm --filter www build + +# --- runtime stage: node server --- +FROM base AS runtime +ENV NODE_ENV=production +# Bind to all interfaces so Docker/Railway can route to it; honor $PORT if set. +ENV HOST=0.0.0.0 +ENV PORT=4321 +COPY --from=build /app /app +WORKDIR /app/packages/www +EXPOSE 4321 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \ + CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||4321)+'/api/v0/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" +CMD ["node", "./dist/server/entry.mjs"] diff --git a/README.md b/README.md index abf5ce3..5bdde8e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,51 @@ # rfd -experimental atproto-powered request for discussion (rfd) platform -> [WARNING] -> prototype, more to come +An atproto-powered request-for-discussion (RFD) platform. A thin, single-tenant, +self-hostable client over [tangled](https://tangled.org)'s **bobbin** appview — no custom +indexing infrastructure required. +## How it works + +- Proposals are numbered Markdown files (`NNNN-slug.md`) in a tangled git repo named `rfd`. +- Discussion happens through tangled pulls, issues, and comments. +- This app reads everything from a **bobbin** appview (default: `https://api.tangled.org`) + and writes go browser-side directly to the author's PDS via OAuth. + +## Packages + +- `packages/core` (`@rfd/core`) — headless, transport-agnostic library over bobbin. +- `packages/www` — Astro (Node) server that renders one owner's `rfd` repo. + +## Self-hosting + +The app is single-tenant: one instance serves one owner's `rfd` repo. + +### Docker + +```bash +docker run -p 4321:4321 -e RFD_OWNER=you.example.com natemoo-re/rfd +``` + +### Railway + +Deploy this repo; Railway builds the `Dockerfile` and injects `PORT`. Set `RFD_OWNER` +(and any optional vars below) in the service settings. + +### Configuration + +| Var | Default | Purpose | +|---|---|---| +| `RFD_OWNER` | — (required) | Handle or DID of the repo owner | +| `RFD_REPO_NAME` | `rfd` | Canonical repo name to serve | +| `BOBBIN_URL` | `https://api.tangled.org` | Comma-separated, preference-ordered bobbin pool | +| `RFD_CACHE_TTL` | `60` | Seconds to cache known-content responses | +| `PUBLIC_ORIGIN` | request-derived | Origin for OAuth client metadata | +| `PORT` | host-provided | HTTP listen port | + +## Development + +```bash +pnpm install +RFD_OWNER=you.example.com pnpm --filter www dev +pnpm --filter @rfd/core test +``` diff --git a/docs/superpowers/plans/2026-07-30-rfd-core-assembly.md b/docs/superpowers/plans/2026-07-30-rfd-core-assembly.md new file mode 100644 index 0000000..d1c559b --- /dev/null +++ b/docs/superpowers/plans/2026-07-30-rfd-core-assembly.md @@ -0,0 +1,922 @@ +# @rfd/core Proposal Assembly Implementation Plan (Plan 2 of 4) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax. + +**Goal:** Extend `@rfd/core` with the proposal *file assembly* layer — git-proxy reads (default branch, tree, blob) and the `listProposals()` / `getProposal()` orchestration that maps proposal Markdown files to their pulls and discussion — so the web app can render RFDs entirely from bobbin. + +**Architecture:** Adds a git-proxy client (`git.ts`) over the existing `BobbinPool`, a patch-fetch helper that reads a pull's patch blob from the author's PDS and parses which `.md` files it touches (reusing the existing pure `patch.ts`), and two orchestration functions ported from the legacy `packages/www/src/lib/proposal.ts` but sourced entirely from bobbin (no D1, no PDS `listRecords` walks). Wired into the `createRfd()` factory. + +**Tech Stack:** TypeScript (ESM), Vitest, the existing `@rfd/core` primitives (`BobbinPool`, `createReads`, `identity`, `patch.ts`, `proposal.ts` pure helpers). + +**Prereq:** Plan 1 (`docs/superpowers/plans/2026-07-30-rfd-core-library.md`) is complete — `@rfd/core` exists with `bobbin.ts`, `reads.ts`, `resolve.ts`, `identity.ts`, `proposal.ts` (pure helpers), `patch.ts`, `types.ts`, `index.ts` (`createRfd`). + +**Spec:** `docs/superpowers/specs/2026-07-30-rfd-bobbin-thin-client-design.md` + +**Confirmed against the live API (2026-07-30):** git-proxy methods take the repo **AT-URI** as `repo=`. `getDefaultBranch` → `{name, hash, when}`; `tree` → `{ref, files:[{name,mode,size,last_commit}]}`. `blob` response shape is `{content, encoding:'utf-8'|'base64', size, isBinary?}` (same as the legacy `knot.ts` since bobbin proxies the identical knot XRPC) — **reconfirm the blob shape with one live call during Task 3** and adjust the parse if it differs. + +--- + +## File Structure + +``` +packages/core/ + src/ + bobbin.ts # MODIFY: export XrpcRequestError + index.ts # MODIFY: export git types; add listProposals/getProposal to factory + identity.ts # MODIFY: add resolvePds(did) + git.ts # NEW: git-proxy reads (default branch, tree, blob) + patch-fetch.ts # NEW: fetch + parse a pull's patch blob from the author PDS + assembly.ts # NEW: listProposals() + getProposal() orchestration + test/ + git.test.ts + patch-fetch.test.ts + assembly.test.ts + fixtures/ + tree.json # NEW + blob.json # NEW + patch.diff # NEW (a small git-format-patch text) +``` + +--- + +## Task 1: Export `XrpcRequestError` from the pool + +`git.ts` needs to distinguish a 404 (missing blob/path → return null) from a pool-exhaustion error (throw). The typed error already exists in `bobbin.ts` but is not exported. + +**Files:** +- Modify: `packages/core/src/bobbin.ts` +- Modify: `packages/core/src/index.ts` +- Create: `packages/core/test/xrpc-error.test.ts` + +- [ ] **Step 1: Write the failing test** — `packages/core/test/xrpc-error.test.ts` + +```ts +import { expect, test } from 'vitest'; +import { XrpcRequestError } from '../src/bobbin.ts'; + +test('XrpcRequestError carries the HTTP status', () => { + const err = new XrpcRequestError(404, 'x -> 404 not found'); + expect(err).toBeInstanceOf(Error); + expect(err.status).toBe(404); + expect(err.name).toBe('XrpcRequestError'); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test xrpc-error` +Expected: FAIL — `XrpcRequestError` is not exported. + +- [ ] **Step 3: Implement** — in `packages/core/src/bobbin.ts`, add the `export` keyword to the existing class declaration so it reads `export class XrpcRequestError extends Error {`. Then add to `packages/core/src/index.ts` (near the other re-exports): + +```ts +export { XrpcRequestError } from './bobbin.ts'; +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test xrpc-error` +Expected: PASS. Also run `pnpm --filter @rfd/core test` — all prior tests still pass. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/bobbin.ts packages/core/src/index.ts packages/core/test/xrpc-error.test.ts +git commit -m "feat(core): export XrpcRequestError" +``` + +--- + +## Task 2: `identity.resolvePds(did)` + +Patch blobs live in the pull author's PDS, so we must resolve a DID → PDS URL. Extend the `Identity` interface and its adapter. + +**Files:** +- Modify: `packages/core/src/resolve.ts` (the `Identity` interface) +- Modify: `packages/core/src/identity.ts` (the adapter) +- Create: `packages/core/test/identity.test.ts` + +- [ ] **Step 1: Write the failing test** — `packages/core/test/identity.test.ts` + +```ts +import { expect, test, vi } from 'vitest'; +import { createIdentityFrom } from '../src/identity.ts'; + +test('resolvePds returns the PDS from the resolver', async () => { + const resolver = { resolve: vi.fn().mockResolvedValue({ did: 'did:plc:x', handle: 'a.b', pds: 'https://pds.example' }) }; + const identity = createIdentityFrom(resolver as never); + expect(await identity.resolvePds('did:plc:x')).toBe('https://pds.example'); + expect(await identity.resolveDid('a.b')).toBe('did:plc:x'); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test identity` +Expected: FAIL — `createIdentityFrom` is not exported. + +- [ ] **Step 3: Implement** + +First, in `packages/core/src/resolve.ts`, extend the `Identity` interface: + +```ts +export interface Identity { + /** Resolve a handle to a DID. */ + resolveDid(handle: string): Promise; + /** Resolve a DID (or handle) to its PDS service URL. */ + resolvePds(actor: string): Promise; +} +``` + +Then, in `packages/core/src/identity.ts`, refactor so the resolver-backed logic is separated from the wiring, and export both. Replace the file's `createIdentity` export with: + +```ts +export interface ActorResolver { + resolve(actor: string): Promise<{ did: string; handle: string; pds: string }>; +} + +/** Build an Identity from any actor resolver (injectable for tests). */ +export function createIdentityFrom(resolver: ActorResolver): Identity { + return { + async resolveDid(handle: string): Promise { + const r = await resolver.resolve(handle); + return r.did; + }, + async resolvePds(actor: string): Promise { + const r = await resolver.resolve(actor); + return r.pds; + }, + }; +} +``` + +Keep the existing `createIdentity()` (the `@atcute/identity-resolver` wiring), but have it delegate to `createIdentityFrom`: + +```ts +export function createIdentity(): Identity { + const handleResolver = new CompositeHandleResolver({ + strategy: 'race', + methods: { + dns: new DohJsonHandleResolver({ dohUrl: 'https://mozilla.cloudflare-dns.com/dns-query' }), + http: new WellKnownHandleResolver(), + }, + }); + const didDocumentResolver = new CompositeDidDocumentResolver({ + methods: { plc: new PlcDidDocumentResolver(), web: new WebDidDocumentResolver() }, + }); + const local = new LocalActorResolver({ handleResolver, didDocumentResolver }); + return createIdentityFrom({ + async resolve(actor: string) { + const r = await local.resolve(actor as never); + return { did: r.did, handle: r.handle, pds: r.pds }; + }, + }); +} +``` + +Add the `Identity` import to `identity.ts`: `import type { Identity } from './resolve.ts';` (keep existing imports). + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test identity` +Expected: PASS. Run `pnpm --filter @rfd/core test` — all pass. Run `pnpm --filter @rfd/core check` — no type errors (the factory in `index.ts` still type-checks; `createRfd` uses `createIdentity()` which is unchanged in signature). + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/resolve.ts packages/core/src/identity.ts packages/core/test/identity.test.ts +git commit -m "feat(core): add identity.resolvePds" +``` + +--- + +## Task 3: git-proxy reads (`git.ts`) + +**Files:** +- Create: `packages/core/src/git.ts` +- Create: `packages/core/test/git.test.ts` +- Create: `packages/core/test/fixtures/tree.json` +- Create: `packages/core/test/fixtures/blob.json` + +- [ ] **Step 1: Reconfirm the blob shape live** (rate-limit tolerant; retry after a few seconds if needed) + +Run: +```bash +CORE="at://did:plc:wshs7t2adsemcrrd4snkeqli/sh.tangled.repo/core" +curl -s "https://api.tangled.org/xrpc/sh.tangled.repo.blob?repo=$CORE&ref=master&path=README.md" | head -c 200 +``` +Expected: a JSON object with `content`, `encoding`, `size`. If the field names differ from the `BlobResponse` interface below, adjust the interface and `getBlob` accordingly before proceeding. + +- [ ] **Step 2: Create fixtures** + +`packages/core/test/fixtures/tree.json`: +```json +{ + "ref": "main", + "files": [ + { "name": "0001-charter.md", "mode": "0100644", "size": 1200 }, + { "name": "0002-governance.md", "mode": "0100644", "size": 800 }, + { "name": "README.md", "mode": "0100644", "size": 300 } + ] +} +``` + +`packages/core/test/fixtures/blob.json`: +```json +{ "content": "# Charter\n\nThe founding proposal.\n", "encoding": "utf-8", "size": 30 } +``` + +- [ ] **Step 3: Write the failing test** — `packages/core/test/git.test.ts` + +```ts +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { createGit } from '../src/git.ts'; +import { XrpcRequestError } from '../src/bobbin.ts'; + +const tree = JSON.parse(readFileSync(fileURLToPath(new URL('./fixtures/tree.json', import.meta.url)), 'utf8')); +const blob = JSON.parse(readFileSync(fileURLToPath(new URL('./fixtures/blob.json', import.meta.url)), 'utf8')); +const REPO = 'at://did:plc:owner/sh.tangled.repo/rfd'; + +test('getDefaultBranch passes the repo AT-URI', async () => { + const get = vi.fn().mockResolvedValue({ name: 'main', hash: 'abc', when: '2026-01-01T00:00:00Z' }); + const git = createGit({ get }, REPO); + expect((await git.getDefaultBranch()).name).toBe('main'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.getDefaultBranch', { repo: REPO }); +}); + +test('listTree passes repo + ref', async () => { + const get = vi.fn().mockResolvedValue(tree); + const git = createGit({ get }, REPO); + const out = await git.listTree('main'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.tree', { repo: REPO, ref: 'main' }); + expect(out.files).toHaveLength(3); +}); + +test('getBlob returns decoded utf-8 content', async () => { + const get = vi.fn().mockResolvedValue(blob); + const git = createGit({ get }, REPO); + expect(await git.getBlob('main', '0001-charter.md')).toBe('# Charter\n\nThe founding proposal.\n'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.blob', { repo: REPO, ref: 'main', path: '0001-charter.md' }); +}); + +test('getBlob decodes base64 content', async () => { + const get = vi.fn().mockResolvedValue({ content: btoa('hello'), encoding: 'base64', size: 5 }); + const git = createGit({ get }, REPO); + expect(await git.getBlob('main', 'x.md')).toBe('hello'); +}); + +test('getBlob returns null for a missing path (4xx), rethrows other errors', async () => { + const missing = vi.fn().mockRejectedValue(new XrpcRequestError(404, 'not found')); + expect(await createGit({ get: missing }, REPO).getBlob('main', 'nope.md')).toBeNull(); + + const boom = vi.fn().mockRejectedValue(new Error('all bobbin instances failed')); + await expect(createGit({ get: boom }, REPO).getBlob('main', 'x.md')).rejects.toThrow(/all bobbin/); +}); + +test('getBlob returns null for binary blobs', async () => { + const get = vi.fn().mockResolvedValue({ content: 'AAAA', encoding: 'base64', size: 3, isBinary: true }); + expect(await createGit({ get }, REPO).getBlob('main', 'logo.png')).toBeNull(); +}); +``` + +- [ ] **Step 4: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test git` +Expected: FAIL — cannot find `../src/git.ts`. + +- [ ] **Step 5: Implement** — `packages/core/src/git.ts` + +```ts +import { XrpcRequestError } from './bobbin.ts'; +import type { Getter } from './reads.ts'; + +export interface DefaultBranch { + name: string; + hash: string; + when: string; +} + +export interface TreeFile { + name: string; + mode: string; + size: number; +} + +export interface TreeResponse { + ref: string; + files: TreeFile[]; +} + +export interface BlobResponse { + content: string; + encoding: 'utf-8' | 'base64'; + size: number; + isBinary?: boolean; +} + +export function createGit(pool: Getter, repoUri: string) { + return { + getDefaultBranch(): Promise { + return pool.get('sh.tangled.repo.getDefaultBranch', { repo: repoUri }); + }, + listTree(ref: string): Promise { + return pool.get('sh.tangled.repo.tree', { repo: repoUri, ref }); + }, + async getBlob(ref: string, path: string): Promise { + let data: BlobResponse; + try { + data = await pool.get('sh.tangled.repo.blob', { repo: repoUri, ref, path }); + } catch (err) { + // A 4xx means the path/ref doesn't exist — treat as absent. Anything + // else (pool exhaustion, 5xx) is a real failure and propagates. + if (err instanceof XrpcRequestError) return null; + throw err; + } + if (data.isBinary) return null; + return data.encoding === 'base64' ? atob(data.content) : data.content; + }, + }; +} + +export type Git = ReturnType; +``` + +- [ ] **Step 6: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test git` +Expected: 6 passing tests. + +- [ ] **Step 7: Commit** + +```bash +git add packages/core/src/git.ts packages/core/test/git.test.ts packages/core/test/fixtures/tree.json packages/core/test/fixtures/blob.json +git commit -m "feat(core): add git-proxy reads (branch, tree, blob)" +``` + +--- + +## Task 4: patch fetch + parse (`patch-fetch.ts`) + +Given a pull, fetch its latest patch blob from the author's PDS and return the proposal slugs / markdown it touches. Reuses the pure `gunzipToString` and `listMarkdownFilesInDiff` from `patch.ts`. + +**Files:** +- Create: `packages/core/src/patch-fetch.ts` +- Create: `packages/core/test/patch-fetch.test.ts` +- Create: `packages/core/test/fixtures/patch.diff` + +- [ ] **Step 1: Create the patch fixture** — `packages/core/test/fixtures/patch.diff` (a minimal new-file git diff for `0007-caching.md`) + +``` +diff --git a/0007-caching.md b/0007-caching.md +new file mode 100644 +index 0000000..1111111 +--- /dev/null ++++ b/0007-caching.md +@@ -0,0 +1,3 @@ ++# Caching ++ ++Add a read-through cache. +``` + +- [ ] **Step 2: Write the failing test** — `packages/core/test/patch-fetch.test.ts` + +```ts +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { latestPatchCid, fetchPatchText, pullMarkdownPaths } from '../src/patch-fetch.ts'; +import type { PullRecord } from '../src/types.ts'; + +const diff = readFileSync(fileURLToPath(new URL('./fixtures/patch.diff', import.meta.url)), 'utf8'); + +function gzip(text: string): Promise { + const stream = new Response(new TextEncoder().encode(text)).body!.pipeThrough(new CompressionStream('gzip')); + return new Response(stream).arrayBuffer().then((b) => new Uint8Array(b)); +} + +const pull: PullRecord = { + $type: 'sh.tangled.repo.pull', + title: 'add caching', + target: { repo: 'did:plc:repo', branch: 'main' }, + createdAt: '2026-06-01T00:00:00Z', + rounds: [ + { createdAt: '2026-06-01T00:00:00Z', patchBlob: { ref: { $link: 'bafyOLD' } } }, + { createdAt: '2026-06-02T00:00:00Z', patchBlob: { ref: { $link: 'bafyNEW' } } }, + ], +}; + +test('latestPatchCid returns the last round patch cid', () => { + expect(latestPatchCid(pull)).toBe('bafyNEW'); + expect(latestPatchCid({ ...pull, rounds: [] })).toBeNull(); +}); + +test('fetchPatchText gunzips a getBlob response from the author PDS', async () => { + const gz = await gzip(diff); + const fetchImpl = vi.fn(async (input: string | URL) => { + const url = new URL(String(input)); + expect(url.pathname).toBe('/xrpc/com.atproto.sync.getBlob'); + expect(url.searchParams.get('did')).toBe('did:plc:author'); + expect(url.searchParams.get('cid')).toBe('bafyNEW'); + return new Response(gz, { status: 200 }); + }); + const text = await fetchPatchText('https://pds.example', 'did:plc:author', 'bafyNEW', fetchImpl as never); + expect(text).toContain('0007-caching.md'); +}); + +test('fetchPatchText returns null on a non-ok response', async () => { + const fetchImpl = vi.fn(async () => new Response('nope', { status: 404 })); + expect(await fetchPatchText('https://pds.example', 'did:plc:author', 'x', fetchImpl as never)).toBeNull(); +}); + +test('pullMarkdownPaths returns the .md paths the latest patch touches', async () => { + const gz = await gzip(diff); + const deps = { + resolvePds: vi.fn().mockResolvedValue('https://pds.example'), + fetchImpl: vi.fn(async () => new Response(gz, { status: 200 })), + }; + const paths = await pullMarkdownPaths('at://did:plc:author/sh.tangled.repo.pull/1', pull, deps as never); + expect(paths).toEqual(['0007-caching.md']); + expect(deps.resolvePds).toHaveBeenCalledWith('did:plc:author'); +}); +``` + +- [ ] **Step 3: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test patch-fetch` +Expected: FAIL — cannot find `../src/patch-fetch.ts`. + +- [ ] **Step 4: Implement** — `packages/core/src/patch-fetch.ts` + +```ts +import { parseAtUri } from './at-uri.ts'; +import { gunzipToString, listMarkdownFilesInDiff } from './patch.ts'; +import type { PullRecord } from './types.ts'; + +export type FetchImpl = (input: string | URL, init?: RequestInit) => Promise; + +export function latestPatchCid(pull: PullRecord): string | null { + const rounds = pull.rounds ?? []; + const latest = rounds[rounds.length - 1]; + return latest?.patchBlob?.ref?.$link ?? null; +} + +/** Fetch and gunzip a patch blob from the author's PDS. Returns null on any failure. */ +export async function fetchPatchText( + pds: string, + authorDid: string, + patchCid: string, + fetchImpl: FetchImpl = fetch, +): Promise { + const url = new URL('/xrpc/com.atproto.sync.getBlob', pds); + url.searchParams.set('did', authorDid); + url.searchParams.set('cid', patchCid); + const res = await fetchImpl(url); + if (!res.ok) return null; + const bytes = new Uint8Array(await res.arrayBuffer()); + try { + return await gunzipToString(bytes); + } catch { + return null; + } +} + +export interface PullPatchDeps { + resolvePds: (did: string) => Promise; + fetchImpl?: FetchImpl; +} + +/** Resolve the pull author's PDS, fetch the latest patch, and return the `.md` paths it touches. */ +export async function pullMarkdownPaths( + pullUri: string, + pull: PullRecord, + deps: PullPatchDeps, +): Promise { + const cid = latestPatchCid(pull); + const parsed = parseAtUri(pullUri); + if (!cid || !parsed) return []; + let pds: string; + try { + pds = await deps.resolvePds(parsed.did); + } catch { + return []; + } + const text = await fetchPatchText(pds, parsed.did, cid, deps.fetchImpl); + if (!text) return []; + return listMarkdownFilesInDiff(text).map((entry) => entry.path); +} +``` + +- [ ] **Step 5: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test patch-fetch` +Expected: 4 passing tests. + +- [ ] **Step 6: Commit** + +```bash +git add packages/core/src/patch-fetch.ts packages/core/test/patch-fetch.test.ts packages/core/test/fixtures/patch.diff +git commit -m "feat(core): fetch + parse a pull's patch from the author PDS" +``` + +--- + +## Task 5: `listProposals()` + `getProposal()` orchestration (`assembly.ts`) + +This ports the logic of the legacy `packages/www/src/lib/proposal.ts` (READ IT for reference) onto bobbin: default-branch tree gives committed proposals; `listPulls` (all authors, from bobbin) plus patch parsing map pulls to proposal slugs; `feed.listComments` gives discussion. No D1, no PDS `listRecords` walk. + +**Files:** +- Create: `packages/core/src/assembly.ts` +- Create: `packages/core/test/assembly.test.ts` + +The tests fully pin the behavior; implement `assembly.ts` to satisfy them, using the reference file for the status/merge logic. + +- [ ] **Step 1: Write the failing test** — `packages/core/test/assembly.test.ts` + +```ts +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { listProposals, getProposal } from '../src/assembly.ts'; +import type { AssemblyDeps } from '../src/assembly.ts'; + +const tree = JSON.parse(readFileSync(fileURLToPath(new URL('./fixtures/tree.json', import.meta.url)), 'utf8')); + +// A pull that introduces 0007-caching.md (open) and one that introduced 0002 (merged). +const pulls = [ + { + uri: 'at://did:plc:a/sh.tangled.repo.pull/open7', + cid: 'c1', + state: 'open', + commentCount: 1, + value: { + $type: 'sh.tangled.repo.pull', title: 'caching', + target: { repo: 'did:plc:repo', branch: 'main' }, createdAt: '2026-06-01T00:00:00Z', + rounds: [{ createdAt: '2026-06-01T00:00:00Z', patchBlob: { ref: { $link: 'cid7' } } }], + }, + }, + { + uri: 'at://did:plc:b/sh.tangled.repo.pull/merged2', + cid: 'c2', + state: 'merged', + commentCount: 0, + value: { + $type: 'sh.tangled.repo.pull', title: 'governance', + target: { repo: 'did:plc:repo', branch: 'main' }, createdAt: '2026-05-01T00:00:00Z', + rounds: [{ createdAt: '2026-05-01T00:00:00Z', patchBlob: { ref: { $link: 'cid2' } } }], + }, + }, +]; + +// Map each pull URI to the .md paths it touches (bypasses real patch fetching in these tests). +const pathsByPull: Record = { + 'at://did:plc:a/sh.tangled.repo.pull/open7': ['0007-caching.md'], + 'at://did:plc:b/sh.tangled.repo.pull/merged2': ['0002-governance.md'], +}; + +function deps(overrides: Partial = {}): AssemblyDeps { + return { + repoUri: 'at://did:plc:owner/sh.tangled.repo/rfd', + repoDid: 'did:plc:repo', + git: { + getDefaultBranch: vi.fn().mockResolvedValue({ name: 'main', hash: '', when: '' }), + listTree: vi.fn().mockResolvedValue(tree), + getBlob: vi.fn().mockResolvedValue(null), + }, + reads: { + listPulls: vi.fn().mockResolvedValue({ items: pulls, cursor: null }), + getDiscussion: vi.fn().mockResolvedValue({ items: [], cursor: null }), + }, + pullMarkdownPaths: vi.fn(async (uri: string) => pathsByPull[uri] ?? []), + ...overrides, + } as AssemblyDeps; +} + +test('listProposals merges committed tree files with in-discussion pulls', async () => { + const out = await listProposals(deps()); + const bySlug = Object.fromEntries(out.map((p) => [p.slug, p.status])); + // committed on the default branch (no open pull touching them) + expect(bySlug['0001-charter']).toBe('committed'); + // 0002 is on the default branch AND has a merged pull -> published + expect(bySlug['0002-governance']).toBe('published'); + // 0007 exists only in an open pull -> discussion + expect(bySlug['0007-caching']).toBe('discussion'); + // README.md is not a proposal file + expect(bySlug['README']).toBeUndefined(); + // sorted by slug + expect(out.map((p) => p.slug)).toEqual(['0001-charter', '0002-governance', '0007-caching']); +}); + +test('getProposal returns committed content from the default branch + derived status', async () => { + const d = deps({ + git: { + getDefaultBranch: vi.fn().mockResolvedValue({ name: 'main', hash: '', when: '' }), + listTree: vi.fn().mockResolvedValue(tree), + getBlob: vi.fn(async (_ref: string, path: string) => + path === '0002-governance.md' ? '# Governance\n' : null), + } as never, + }); + const detail = await getProposal(d, '0002-governance'); + expect(detail).not.toBeNull(); + expect(detail!.content).toEqual({ source: 'default', text: '# Governance\n' }); + expect(detail!.status).toBe('published'); + expect(detail!.pulls.map((p) => p.uri)).toContain('at://did:plc:b/sh.tangled.repo.pull/merged2'); +}); + +test('getProposal returns null for an unknown slug with no pulls', async () => { + expect(await getProposal(deps(), '9999-nope')).toBeNull(); +}); + +test('getProposal collects discussion comments for the proposal pulls', async () => { + const getDiscussion = vi.fn().mockResolvedValue({ + items: [ + { uri: 'at://did:plc:c/sh.tangled.feed.comment/1', cid: 'x', value: { $type: 'sh.tangled.feed.comment', subject: 'at://did:plc:a/sh.tangled.repo.pull/open7', body: { original: 'nice' }, createdAt: '2026-06-02T00:00:00Z' } }, + ], + cursor: null, + }); + const d = deps({ reads: { listPulls: vi.fn().mockResolvedValue({ items: pulls, cursor: null }), getDiscussion } as never }); + const detail = await getProposal(d, '0007-caching'); + expect(detail!.discussion).toHaveLength(1); + expect(detail!.discussion[0]).toMatchObject({ body: 'nice', authorDid: 'did:plc:c', source: 'pull' }); + expect(getDiscussion).toHaveBeenCalledWith('at://did:plc:a/sh.tangled.repo.pull/open7'); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test assembly` +Expected: FAIL — cannot find `../src/assembly.ts`. + +- [ ] **Step 3: Implement** — `packages/core/src/assembly.ts` + +Reference the legacy `packages/www/src/lib/proposal.ts` for the status/content logic. Note the pure `deriveStatus`, `fileNameToSlug`, `isProposalFile` already exist in `./proposal.ts`. Implement to satisfy the tests: + +```ts +import { parseAtUri } from './at-uri.ts'; +import { deriveStatus, fileNameToSlug, isProposalFile, type ProposalStatus } from './proposal.ts'; +import type { Git } from './git.ts'; +import type { PullPatchDeps } from './patch-fetch.ts'; +import { pullMarkdownPaths as defaultPullMarkdownPaths } from './patch-fetch.ts'; +import type { CommentListItem, ListResponse, PullListItem, PullState } from './types.ts'; + +export interface ProposalSummary { + slug: string; + status: ProposalStatus; +} + +export interface DiscussionEntry { + source: 'pull' | 'issue'; + uri: string; + authorDid: string; + body: string; + createdAt: string; +} + +export interface ProposalDetail { + slug: string; + status: ProposalStatus; + content: { source: 'default' | 'pull'; text: string } | null; + pulls: PullListItem[]; + discussion: DiscussionEntry[]; +} + +export interface AssemblyDeps { + repoUri: string; + repoDid: string; + git: Pick; + reads: { + listPulls: (repoDid: string, cursor?: string) => Promise>; + getDiscussion: (subjectUri: string, cursor?: string) => Promise>; + }; + /** Override for tests; defaults to the real PDS patch fetch. */ + pullMarkdownPaths?: (uri: string, pull: PullListItem['value'], deps: PullPatchDeps) => Promise; + /** Passed through to the default pullMarkdownPaths. */ + patchDeps?: PullPatchDeps; +} + +async function defaultBranchName(deps: AssemblyDeps): Promise { + try { + return (await deps.git.getDefaultBranch()).name || 'main'; + } catch { + return 'main'; + } +} + +async function committedSlugs(deps: AssemblyDeps, ref: string): Promise> { + const slugs = new Set(); + try { + const tree = await deps.git.listTree(ref); + for (const f of tree.files) { + if (isProposalFile(f.name)) { + const slug = fileNameToSlug(f.name); + if (slug) slugs.add(slug); + } + } + } catch { + // empty repo / knot unreachable — no committed proposals + } + return slugs; +} + +/** Map every pull to the proposal slugs its latest patch touches. */ +async function pullsBySlug(deps: AssemblyDeps): Promise> { + const resolvePaths = + deps.pullMarkdownPaths ?? + ((uri, pull, d) => defaultPullMarkdownPaths(uri, pull, d)); + const patchDeps = deps.patchDeps ?? { resolvePds: async () => '' }; + const bySlug = new Map(); + + let cursor: string | undefined; + do { + const page = await deps.reads.listPulls(deps.repoDid, cursor); + for (const item of page.items) { + const paths = await resolvePaths(item.uri, item.value, patchDeps); + for (const path of paths) { + const slug = fileNameToSlug(path); + if (!slug) continue; + const arr = bySlug.get(slug) ?? []; + arr.push(item); + bySlug.set(slug, arr); + } + } + cursor = page.cursor ?? undefined; + } while (cursor); + + return bySlug; +} + +export async function listProposals(deps: AssemblyDeps): Promise { + const ref = await defaultBranchName(deps); + const committed = await committedSlugs(deps, ref); + const byslug = await pullsBySlug(deps); + + const slugs = new Set([...committed, ...byslug.keys()]); + const summaries: ProposalSummary[] = []; + for (const slug of slugs) { + const pulls = byslug.get(slug) ?? []; + const status = deriveStatus({ + onDefaultBranch: committed.has(slug), + pulls: pulls.map((p) => ({ state: p.state as PullState })), + }); + summaries.push({ slug, status }); + } + summaries.sort((a, b) => a.slug.localeCompare(b.slug)); + return summaries; +} + +export async function getProposal(deps: AssemblyDeps, slug: string): Promise { + const ref = await defaultBranchName(deps); + const filename = `${slug}.md`; + + const fromDefault = await deps.git.getBlob(ref, filename); + const onDefaultBranch = fromDefault !== null; + + const byslug = await pullsBySlug(deps); + const pulls = byslug.get(slug) ?? []; + + if (!onDefaultBranch && pulls.length === 0) return null; + + let content: ProposalDetail['content'] = null; + if (fromDefault !== null) { + content = { source: 'default', text: fromDefault }; + } + // (Reading proposal body from an open pull's patch is left to the www layer, + // which has the author PDS wiring; here we surface pulls + default content.) + + const status = deriveStatus({ + onDefaultBranch, + pulls: pulls.map((p) => ({ state: p.state as PullState })), + }); + + const discussion: DiscussionEntry[] = []; + for (const pull of pulls) { + const comments = await deps.reads.getDiscussion(pull.uri); + for (const c of comments.items) { + const parsed = parseAtUri(c.uri); + discussion.push({ + source: 'pull', + uri: c.uri, + authorDid: parsed?.did ?? '', + body: c.value.body.original, + createdAt: c.value.createdAt, + }); + } + } + discussion.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + + return { slug, status, content, pulls, discussion }; +} +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test assembly` +Expected: 4 passing tests. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/assembly.ts packages/core/test/assembly.test.ts +git commit -m "feat(core): assemble proposals from tree + pulls + discussion" +``` + +--- + +## Task 6: Wire assembly into `createRfd()` + +**Files:** +- Modify: `packages/core/src/index.ts` +- Create: `packages/core/test/factory-assembly.test.ts` + +- [ ] **Step 1: Write the failing test** — `packages/core/test/factory-assembly.test.ts` + +```ts +import { expect, test, vi } from 'vitest'; +import { createRfd } from '../src/index.ts'; + +const repos = { items: [{ uri: 'at://did:plc:owner/sh.tangled.repo/rfd', value: { name: 'rfd', knot: 'knot1', repoDid: 'did:plc:repo' } }], cursor: null }; + +test('createRfd exposes listProposals scoped to the resolved repo', async () => { + const get = vi.fn(async (method: string, params?: Record) => { + if (method === 'sh.tangled.repo.listRepos') return repos; + if (method === 'sh.tangled.repo.getDefaultBranch') return { name: 'main', hash: '', when: '' }; + if (method === 'sh.tangled.repo.tree') return { ref: 'main', files: [{ name: '0001-charter.md', mode: '0100644', size: 1 }] }; + if (method === 'sh.tangled.repo.listPulls') return { items: [], cursor: null }; + throw new Error(`unexpected ${method} ${JSON.stringify(params)}`); + }); + const identity = { resolveDid: vi.fn().mockResolvedValue('did:plc:owner'), resolvePds: vi.fn() }; + const rfd = createRfd({ + config: { owner: 'natemoo.re', repoName: 'rfd', bobbinUrls: ['https://a.test'], cacheTtlSeconds: 60 }, + pool: { get }, + identity, + }); + const proposals = await rfd.listProposals(); + expect(proposals).toEqual([{ slug: '0001-charter', status: 'committed' }]); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test factory-assembly` +Expected: FAIL — `rfd.listProposals` is not a function. + +- [ ] **Step 3: Implement** — in `packages/core/src/index.ts`: + +Add imports: +```ts +import { createGit } from './git.ts'; +import { listProposals as assembleList, getProposal as assembleGet } from './assembly.ts'; +``` +Add re-exports (near the others): +```ts +export * from './git.ts'; +export type { ProposalSummary, ProposalDetail, DiscussionEntry } from './assembly.ts'; +``` +Inside `createRfd`, after `const reads = createReads(pool);`, add a per-call assembly-deps builder and the two methods. Add to the returned object: +```ts + async listProposals() { + const ctx = await context(); + const git = createGit(pool, ctx.repoUri); + return assembleList({ + repoUri: ctx.repoUri, + repoDid: ctx.repoDid, + git, + reads: { listPulls: (d, c) => reads.listPulls(d, c), getDiscussion: (u, c) => reads.getDiscussion(u, c) }, + patchDeps: { resolvePds: (did) => identity.resolvePds(did) }, + }); + }, + async getProposal(slug: string) { + const ctx = await context(); + const git = createGit(pool, ctx.repoUri); + return assembleGet({ + repoUri: ctx.repoUri, + repoDid: ctx.repoDid, + git, + reads: { listPulls: (d, c) => reads.listPulls(d, c), getDiscussion: (u, c) => reads.getDiscussion(u, c) }, + patchDeps: { resolvePds: (did) => identity.resolvePds(did) }, + }, slug); + }, +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test factory-assembly` +Expected: PASS. Then run the FULL suite `pnpm --filter @rfd/core test` and the type-check `pnpm --filter @rfd/core check` — everything passes. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/index.ts packages/core/test/factory-assembly.test.ts +git commit -m "feat(core): expose listProposals/getProposal on createRfd" +``` + +--- + +## Self-Review Notes (for the implementer) + +- **Spec coverage:** git-proxy reads scoped to the repo AT-URI (Task 3); proposal file assembly from bobbin (`listPulls` across all authors + patch parsing + `feed.listComments`), replacing the legacy D1/PDS-walk fallbacks (Tasks 4–5); exposed on the factory (Task 6). +- **Deliberately deferred to Plan 3 (`www`):** reading a proposal *body* from an open pull's patch (needs the author-PDS wiring the www layer will own), and rendering. `getProposal` here returns default-branch content + the pull list + discussion; the www page fills pull-sourced body if needed via the same `patch-fetch` helper. +- **Perf caveat:** `pullsBySlug` fetches every pull's patch. Fine for an RFD-sized repo; if a repo has thousands of pulls this should later be bounded. Note it, don't fix it now. +- **Consistency:** `AssemblyDeps.reads` is a structural subset of the `Reads` type; `pullMarkdownPaths` is injectable (tests bypass real fetch); `PullListItem.state` is narrowed to `PullState` before `deriveStatus`. +``` diff --git a/docs/superpowers/plans/2026-07-30-rfd-core-library.md b/docs/superpowers/plans/2026-07-30-rfd-core-library.md new file mode 100644 index 0000000..2f575ce --- /dev/null +++ b/docs/superpowers/plans/2026-07-30-rfd-core-library.md @@ -0,0 +1,1448 @@ +# @rfd/core Library Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build `@rfd/core`, a headless, transport-agnostic TypeScript library that reads a single Tangled RFD repo from a failover pool of bobbin appview instances and exposes plain-data methods for the web app (and a future CLI) to consume. + +**Architecture:** A new `packages/core` workspace package. A resilient bobbin XRPC client (`BobbinPool`) with sticky-primary failover and health gating sits under typed read methods. Identity + repo resolution turns an owner handle/DID into the repo's `repoDid` (the scoping key). Pure domain helpers (proposal status derivation, slug parsing, diff parsing) are isolated and table-tested. A `createRfd()` factory wires it together. Proposal *file assembly* (git-proxy) is deliberately out of scope here — it lands in the `www` plan once the git-proxy repo-param form is confirmed. + +**Tech Stack:** TypeScript (ESM), Vitest, `@atcute/identity-resolver` (handle/DID resolution), pnpm workspaces. No Astro, Hono, DOM, or Cloudflare dependencies. + +**Spec:** `docs/superpowers/specs/2026-07-30-rfd-bobbin-thin-client-design.md` + +--- + +## File Structure + +``` +packages/core/ + package.json # @rfd/core, ESM, vitest + tsconfig.json # extends root + src/ + index.ts # createRfd() factory + public re-exports + config.ts # RfdConfig + parseConfig(env) + types.ts # hand-authored record + envelope types + at-uri.ts # parseAtUri (moved from www index-event.ts) + patch.ts # pure diff parsing (moved verbatim from www) + bobbin.ts # BobbinPool: resilient XRPC GET client + resolve.ts # owner handle/DID -> repoDid context + proposal.ts # pure status/slug helpers (file assembly deferred to Plan 2) + test/ + fixtures/ + getRepo.json + listPulls.json + listComments.json + getCoverage.json + config.test.ts + at-uri.test.ts + patch.test.ts + bobbin.test.ts + resolve.test.ts + proposal.test.ts +``` + +Each `src` file has one responsibility. `bobbin.ts` is transport, `resolve.ts` is identity, `proposal.ts` is pure domain logic, `types.ts` is shape declarations only. + +--- + +## Task 1: Scaffold the `@rfd/core` package + +**Files:** +- Create: `packages/core/package.json` +- Create: `packages/core/tsconfig.json` +- Create: `packages/core/src/index.ts` +- Create: `packages/core/test/smoke.test.ts` + +- [ ] **Step 1: Create `packages/core/package.json`** + +```json +{ + "name": "@rfd/core", + "type": "module", + "version": "0.0.1", + "devEngines": { + "node": ">=24.15.0" + }, + "main": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./package.json": "./package.json" + }, + "scripts": { + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "@atcute/identity-resolver": "^2.0.0" + }, + "devDependencies": { + "vitest": "^4.0.0" + } +} +``` + +- [ ] **Step 2: Create `packages/core/tsconfig.json`** + +`allowImportingTsExtensions` + `noEmit` are required because every import uses an explicit +`.ts` extension (matching the existing `lexicon`/`www` convention). If the extended base +already sets them, they are harmless to repeat. + +```json +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "noEmit": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true + }, + "include": ["src", "test"] +} +``` + +- [ ] **Step 3: Create `packages/core/src/index.ts` placeholder** + +```ts +export const RFD_CORE_VERSION = '0.0.1'; +``` + +- [ ] **Step 4: Create `packages/core/test/smoke.test.ts`** + +```ts +import { expect, test } from 'vitest'; +import { RFD_CORE_VERSION } from '../src/index.ts'; + +test('package is importable', () => { + expect(RFD_CORE_VERSION).toBe('0.0.1'); +}); +``` + +- [ ] **Step 5: Install and run the smoke test** + +Run: `pnpm install && pnpm --filter @rfd/core test` +Expected: 1 passing test. If pnpm reports the package isn't found, confirm `pnpm-workspace.yaml` globs `packages/**` (it does) and that `pnpm install` linked the new package. + +- [ ] **Step 6: Commit** + +```bash +git add packages/core pnpm-lock.yaml +git commit -m "feat(core): scaffold @rfd/core package" +``` + +--- + +## Task 2: `parseAtUri` helper + +**Files:** +- Create: `packages/core/src/at-uri.ts` +- Create: `packages/core/test/at-uri.test.ts` + +- [ ] **Step 1: Write the failing test** — `packages/core/test/at-uri.test.ts` + +```ts +import { expect, test } from 'vitest'; +import { parseAtUri } from '../src/at-uri.ts'; + +test('parses a well-formed at-uri', () => { + expect(parseAtUri('at://did:plc:abc/sh.tangled.repo.pull/3lz')).toEqual({ + did: 'did:plc:abc', + collection: 'sh.tangled.repo.pull', + rkey: '3lz', + }); +}); + +test('supports multi-segment rkeys', () => { + expect(parseAtUri('at://did:plc:abc/coll/a/b')?.rkey).toBe('a/b'); +}); + +test('returns null for non-at-uris and short uris', () => { + expect(parseAtUri('https://example.com')).toBeNull(); + expect(parseAtUri('at://did:plc:abc')).toBeNull(); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test at-uri` +Expected: FAIL — cannot find module `../src/at-uri.ts`. + +- [ ] **Step 3: Implement `packages/core/src/at-uri.ts`** + +```ts +export interface ParsedAtUri { + did: string; + collection: string; + rkey: string; +} + +export function parseAtUri(uri: string): ParsedAtUri | null { + if (!uri.startsWith('at://')) return null; + const rest = uri.slice('at://'.length); + const parts = rest.split('/'); + if (parts.length < 3) return null; + const [did, collection, ...rkeyParts] = parts; + if (!did || !collection || rkeyParts.length === 0) return null; + return { did, collection, rkey: rkeyParts.join('/') }; +} +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test at-uri` +Expected: 3 passing tests. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/at-uri.ts packages/core/test/at-uri.test.ts +git commit -m "feat(core): add parseAtUri" +``` + +--- + +## Task 3: Move pure diff parsing into core + +**Files:** +- Create: `packages/core/src/patch.ts` +- Create: `packages/core/test/patch.test.ts` + +The source is `packages/www/src/lib/patch.ts` (pure; no changes needed). We copy it into core now; the www copy is deleted in the distribution plan. + +- [ ] **Step 1: Copy the failing test** — copy `packages/www/test/patch.test.ts` to `packages/core/test/patch.test.ts` and fix the import path so the first line reads: + +```ts +import { + extractMarkdownFileFromDiff, + extractMarkdownFromDiff, + listMarkdownFilesInDiff, +} from '../src/patch.ts'; +``` + +(Keep the rest of the test body identical to the www version.) + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test patch` +Expected: FAIL — cannot find module `../src/patch.ts`. + +- [ ] **Step 3: Copy the implementation** — copy `packages/www/src/lib/patch.ts` verbatim to `packages/core/src/patch.ts`. No edits (it uses only `Response`, `DecompressionStream`, `TextDecoder`, all available on Node ≥24). + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test patch` +Expected: all patch tests pass. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/patch.ts packages/core/test/patch.test.ts +git commit -m "feat(core): move pure diff parsing into core" +``` + +--- + +## Task 4: Record + envelope types + +**Files:** +- Create: `packages/core/src/types.ts` +- Create: `packages/core/test/types.test.ts` + +Types are compile-checked; the test asserts a couple of shapes to keep them exercised. + +- [ ] **Step 1: Write the failing test** — `packages/core/test/types.test.ts` + +```ts +import { expectTypeOf, test } from 'vitest'; +import type { + CommentRecord, + PullListItem, + PullState, + RecordEnvelope, + RepoRecord, +} from '../src/types.ts'; + +test('PullListItem carries aggregated state + commentCount', () => { + expectTypeOf().toMatchObjectType<{ + uri: string; + state: PullState; + commentCount: number; + }>(); +}); + +test('RepoRecord exposes repoDid and knot', () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); +}); + +test('a comment envelope wraps a CommentRecord', () => { + expectTypeOf['value']['body']['original']>() + .toEqualTypeOf(); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test types` +Expected: FAIL — cannot find module `../src/types.ts`. + +- [ ] **Step 3: Implement `packages/core/src/types.ts`** + +Shapes are from the live spike against `api.tangled.org` (2026-07-30). + +```ts +/** Envelope bobbin returns for a single record. */ +export interface RecordEnvelope { + uri: string; + cid: string; + value: T; +} + +/** Paginated list response shape used across list* methods. */ +export interface ListResponse { + items: T[]; + cursor: string | null; +} + +export type PullState = 'open' | 'closed' | 'merged'; + +/** sh.tangled.repo */ +export interface RepoRecord { + $type: 'sh.tangled.repo'; + name: string; + knot: string; + description?: string; + createdAt: string; + /** Knot-assigned DID for the repo; the scoping key for issues/pulls. */ + repoDid?: string; + labels?: string[]; +} + +/** One patch round on a pull. */ +export interface PullRound { + createdAt: string; + patchBlob?: { ref?: { $link?: string } }; +} + +/** sh.tangled.repo.pull */ +export interface PullRecord { + $type: 'sh.tangled.repo.pull'; + title: string; + body?: string; + target: { repo: string; branch: string }; + source?: { repo?: string; branch?: string }; + rounds?: PullRound[]; + createdAt: string; +} + +/** sh.tangled.repo.issue */ +export interface IssueRecord { + $type: 'sh.tangled.repo.issue'; + title: string; + body?: string; + repo: string; + createdAt: string; +} + +/** sh.tangled.feed.comment — the current unified comment model. */ +export interface CommentRecord { + $type: 'sh.tangled.feed.comment'; + subject: string; + body: { original: string }; + createdAt: string; +} + +/** Item shape from sh.tangled.repo.listPulls (aggregated fields alongside the record). */ +export interface PullListItem extends RecordEnvelope { + state: PullState; + commentCount: number; +} + +export type IssueListItem = RecordEnvelope; +export type CommentListItem = RecordEnvelope; +export type RepoListItem = RecordEnvelope; + +export interface Coverage { + ready: boolean; + eventsProcessed: number; + lastCursor: number; +} +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test types` +Expected: 3 passing type tests. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/types.ts packages/core/test/types.test.ts +git commit -m "feat(core): add record + envelope types" +``` + +--- + +## Task 5: Config parsing + +**Files:** +- Create: `packages/core/src/config.ts` +- Create: `packages/core/test/config.test.ts` + +- [ ] **Step 1: Write the failing test** — `packages/core/test/config.test.ts` + +```ts +import { expect, test } from 'vitest'; +import { parseConfig } from '../src/config.ts'; + +test('applies defaults with only RFD_OWNER set', () => { + const cfg = parseConfig({ RFD_OWNER: 'natemoo.re' }); + expect(cfg).toEqual({ + owner: 'natemoo.re', + repoName: 'rfd', + bobbinUrls: ['https://api.tangled.org'], + cacheTtlSeconds: 60, + }); +}); + +test('parses a comma-separated, preference-ordered bobbin pool', () => { + const cfg = parseConfig({ + RFD_OWNER: 'did:plc:abc', + BOBBIN_URL: 'https://a.example , https://b.example', + }); + expect(cfg.bobbinUrls).toEqual(['https://a.example', 'https://b.example']); +}); + +test('coerces RFD_CACHE_TTL and RFD_REPO_NAME', () => { + const cfg = parseConfig({ RFD_OWNER: 'x', RFD_REPO_NAME: 'rfc', RFD_CACHE_TTL: '15' }); + expect(cfg.repoName).toBe('rfc'); + expect(cfg.cacheTtlSeconds).toBe(15); +}); + +test('throws when RFD_OWNER is missing', () => { + expect(() => parseConfig({})).toThrow(/RFD_OWNER/); +}); + +test('throws on a non-numeric RFD_CACHE_TTL', () => { + expect(() => parseConfig({ RFD_OWNER: 'x', RFD_CACHE_TTL: 'soon' })).toThrow(/RFD_CACHE_TTL/); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test config` +Expected: FAIL — cannot find module `../src/config.ts`. + +- [ ] **Step 3: Implement `packages/core/src/config.ts`** + +```ts +export interface RfdConfig { + owner: string; + repoName: string; + bobbinUrls: string[]; + cacheTtlSeconds: number; +} + +export type Env = Record; + +const DEFAULT_BOBBIN = 'https://api.tangled.org'; + +export function parseConfig(env: Env): RfdConfig { + const owner = env.RFD_OWNER?.trim(); + if (!owner) { + throw new Error('RFD_OWNER is required (the handle or DID of the RFD repo owner)'); + } + + const bobbinUrls = (env.BOBBIN_URL ?? DEFAULT_BOBBIN) + .split(',') + .map((u) => u.trim()) + .filter((u) => u.length > 0); + if (bobbinUrls.length === 0) { + throw new Error('BOBBIN_URL must contain at least one URL'); + } + + const ttlRaw = env.RFD_CACHE_TTL ?? '60'; + const cacheTtlSeconds = Number(ttlRaw); + if (!Number.isFinite(cacheTtlSeconds) || cacheTtlSeconds < 0) { + throw new Error(`RFD_CACHE_TTL must be a non-negative number, got: ${ttlRaw}`); + } + + return { + owner, + repoName: env.RFD_REPO_NAME?.trim() || 'rfd', + bobbinUrls, + cacheTtlSeconds, + }; +} +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test config` +Expected: 5 passing tests. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/config.ts packages/core/test/config.test.ts +git commit -m "feat(core): add config parsing" +``` + +--- + +## Task 6: Capture bobbin fixtures + +**Files:** +- Create: `packages/core/test/fixtures/getRepo.json` +- Create: `packages/core/test/fixtures/listPulls.json` +- Create: `packages/core/test/fixtures/listComments.json` +- Create: `packages/core/test/fixtures/getCoverage.json` + +These are trimmed real responses used by later tests. No test of their own. + +- [ ] **Step 1: Create `getRepo.json`** (trimmed real shape) + +```json +{ + "cid": "bafyreidehocneckziff4uffajjqyhqgwxxze364qhcaxtfvv46t4avdqku", + "uri": "at://did:plc:wshs7t2adsemcrrd4snkeqli/sh.tangled.repo/core", + "value": { + "$type": "sh.tangled.repo", + "createdAt": "2025-02-23T18:43:18Z", + "description": "Monorepo for Tangled", + "knot": "knot1.tangled.sh", + "name": "core", + "repoDid": "did:plc:j5hmlfdrwkvtxm7cjmu7j2is" + } +} +``` + +- [ ] **Step 2: Create `listPulls.json`** (two items; note top-level `state` + `commentCount`) + +```json +{ + "items": [ + { + "uri": "at://did:plc:kic7mqihegzbj2ojesltkvho/sh.tangled.repo.pull/3mrn7dysfp522", + "cid": "bafyreici556u3cnkdqcim4wsydvjnrwvzavrdr4qt4achgtkgn5g3eim34", + "state": "open", + "commentCount": 2, + "value": { + "$type": "sh.tangled.repo.pull", + "title": "improve repo index performance", + "body": "exploratory work", + "createdAt": "2026-06-01T10:00:00Z", + "target": { "repo": "did:plc:j5hmlfdrwkvtxm7cjmu7j2is", "branch": "master" }, + "rounds": [ + { "createdAt": "2026-06-01T10:00:00Z", "patchBlob": { "ref": { "$link": "bafypatch1" } } } + ] + } + }, + { + "uri": "at://did:plc:kic7mqihegzbj2ojesltkvho/sh.tangled.repo.pull/3mrn7dysfp600", + "cid": "bafyreicid600", + "state": "merged", + "commentCount": 0, + "value": { + "$type": "sh.tangled.repo.pull", + "title": "0002 add governance doc", + "createdAt": "2026-05-01T10:00:00Z", + "target": { "repo": "did:plc:j5hmlfdrwkvtxm7cjmu7j2is", "branch": "master" }, + "rounds": [ + { "createdAt": "2026-05-01T10:00:00Z", "patchBlob": { "ref": { "$link": "bafypatch2" } } } + ] + } + } + ], + "cursor": null +} +``` + +- [ ] **Step 3: Create `listComments.json`** + +```json +{ + "items": [ + { + "uri": "at://did:plc:qfpnj4og54vl56wngdriaxug/sh.tangled.feed.comment/3mrp4r3uhpa22", + "cid": "bafyreiabuj5zezrksmkt5vhhrntpzy6crgwiggtnni2wchn6zyw6ovueju", + "value": { + "$type": "sh.tangled.feed.comment", + "subject": "at://did:plc:kic7mqihegzbj2ojesltkvho/sh.tangled.repo.pull/3mrn7dysfp522", + "body": { "original": "yes that is correct!" }, + "createdAt": "2026-06-01T11:00:00Z" + } + } + ], + "cursor": null +} +``` + +- [ ] **Step 4: Create `getCoverage.json`** + +```json +{ "ready": true, "eventsProcessed": 135389, "lastCursor": 158872 } +``` + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/test/fixtures +git commit -m "test(core): add captured bobbin fixtures" +``` + +--- + +## Task 7: `BobbinPool` — resilient XRPC client with failover + +**Files:** +- Create: `packages/core/src/bobbin.ts` +- Create: `packages/core/test/bobbin.test.ts` + +The pool exposes `get(method, params)`. It tries the sticky instance first, fails over on network error / timeout / 5xx, health-gates *new* instances via `getCoverage`, and makes the last successful instance sticky. `fetchImpl` and `nowMs` are injected for testing. + +- [ ] **Step 1: Write the failing test** — `packages/core/test/bobbin.test.ts` + +```ts +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test } from 'vitest'; +import { createBobbinPool } from '../src/bobbin.ts'; + +const coverage = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/getCoverage.json', import.meta.url)), 'utf8'), +); +const repo = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/getRepo.json', import.meta.url)), 'utf8'), +); + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' }, + }); +} + +/** Build a fetch stub keyed by "|". */ +function stubFetch(routes: Record Promise | Response>) { + const calls: string[] = []; + const fetchImpl = async (input: string | URL): Promise => { + const url = new URL(String(input)); + const nsid = url.pathname.replace('/xrpc/', ''); + const key = `${url.origin}|${nsid}`; + calls.push(key); + const handler = routes[key]; + if (!handler) throw new TypeError(`no route for ${key}`); + return handler(); + }; + return { fetchImpl, calls }; +} + +test('returns data from the primary without health-checking it', async () => { + const { fetchImpl, calls } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse(repo), + }); + const pool = createBobbinPool({ urls: ['https://a.test'], fetchImpl }); + const out = await pool.get('sh.tangled.repo.getRepo', { repo: 'at://x' }); + expect(out).toEqual(repo); + // Primary is used directly — no coverage probe. + expect(calls).toEqual(['https://a.test|sh.tangled.repo.getRepo']); +}); + +test('fails over to a healthy secondary when the primary errors', async () => { + const { fetchImpl, calls } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse({ error: 'boom' }, 500), + 'https://b.test|sh.tangled.bobbin.getCoverage': () => jsonResponse(coverage), + 'https://b.test|sh.tangled.repo.getRepo': () => jsonResponse(repo), + }); + const pool = createBobbinPool({ urls: ['https://a.test', 'https://b.test'], fetchImpl }); + const out = await pool.get('sh.tangled.repo.getRepo', { repo: 'at://x' }); + expect(out).toEqual(repo); + // Secondary was health-gated before use. + expect(calls).toContain('https://b.test|sh.tangled.bobbin.getCoverage'); +}); + +test('skips a secondary that reports not-ready', async () => { + const { fetchImpl } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse({ error: 'boom' }, 500), + 'https://b.test|sh.tangled.bobbin.getCoverage': () => jsonResponse({ ready: false }), + 'https://c.test|sh.tangled.bobbin.getCoverage': () => jsonResponse(coverage), + 'https://c.test|sh.tangled.repo.getRepo': () => jsonResponse(repo), + }); + const pool = createBobbinPool({ + urls: ['https://a.test', 'https://b.test', 'https://c.test'], + fetchImpl, + }); + expect(await pool.get('sh.tangled.repo.getRepo', { repo: 'at://x' })).toEqual(repo); +}); + +test('throws when every instance is exhausted', async () => { + const { fetchImpl } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse({ error: 'boom' }, 500), + 'https://b.test|sh.tangled.bobbin.getCoverage': () => jsonResponse({ ready: false }), + }); + const pool = createBobbinPool({ urls: ['https://a.test', 'https://b.test'], fetchImpl }); + await expect(pool.get('sh.tangled.repo.getRepo', { repo: 'at://x' })).rejects.toThrow( + /all bobbin instances failed/i, + ); +}); + +test('makes the last successful instance sticky', async () => { + let aFails = true; + const { fetchImpl, calls } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => + aFails ? jsonResponse({ error: 'boom' }, 500) : jsonResponse(repo), + 'https://b.test|sh.tangled.bobbin.getCoverage': () => jsonResponse(coverage), + 'https://b.test|sh.tangled.repo.getRepo': () => jsonResponse(repo), + }); + const pool = createBobbinPool({ urls: ['https://a.test', 'https://b.test'], fetchImpl }); + await pool.get('sh.tangled.repo.getRepo', {}); // fails over to b, b becomes sticky + calls.length = 0; + await pool.get('sh.tangled.repo.getRepo', {}); // should start at b now + expect(calls[0]).toBe('https://b.test|sh.tangled.repo.getRepo'); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test bobbin` +Expected: FAIL — cannot find module `../src/bobbin.ts`. + +- [ ] **Step 3: Implement `packages/core/src/bobbin.ts`** + +```ts +import type { Coverage } from './types.ts'; + +export type FetchImpl = (input: string | URL, init?: RequestInit) => Promise; + +export interface BobbinPoolOptions { + urls: string[]; + fetchImpl?: FetchImpl; + /** Per-request timeout in ms. */ + timeoutMs?: number; + /** How long a health-check result is trusted, in ms. */ + healthTtlMs?: number; + /** Injectable clock for tests. */ + nowMs?: () => number; +} + +export interface BobbinPool { + get(method: string, params?: Record): Promise; +} + +interface HealthEntry { + ready: boolean; + checkedAtMs: number; +} + +function buildUrl(base: string, method: string, params: Record): string { + const url = new URL(`/xrpc/${method}`, base); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined) url.searchParams.set(key, String(value)); + } + return url.toString(); +} + +export function createBobbinPool(options: BobbinPoolOptions): BobbinPool { + const { + urls, + fetchImpl = fetch, + timeoutMs = 10_000, + healthTtlMs = 30_000, + nowMs = () => Date.now(), + } = options; + + if (urls.length === 0) throw new Error('createBobbinPool requires at least one URL'); + + let stickyIndex = 0; + const health = new Map(); + + async function rawGet(base: string, method: string, params: Record): Promise { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + try { + return await fetchImpl(buildUrl(base, method, params), { signal: controller.signal }); + } finally { + clearTimeout(timer); + } + } + + async function isReady(base: string): Promise { + const cached = health.get(base); + if (cached && nowMs() - cached.checkedAtMs < healthTtlMs) return cached.ready; + let ready = false; + try { + const res = await rawGet(base, 'sh.tangled.bobbin.getCoverage', {}); + if (res.ok) ready = ((await res.json()) as Coverage).ready === true; + } catch { + ready = false; + } + health.set(base, { ready, checkedAtMs: nowMs() }); + return ready; + } + + async function get(method: string, params: Record = {}): Promise { + // Ordered candidate list beginning at the sticky instance. + const order = urls.map((_, i) => (stickyIndex + i) % urls.length); + let lastError: unknown; + + for (let pos = 0; pos < order.length; pos++) { + const idx = order[pos]!; + const base = urls[idx]!; + // The sticky primary (pos 0) is used directly; failover targets are health-gated. + if (pos > 0 && !(await isReady(base))) continue; + try { + const res = await rawGet(base, method, params); + if (res.status >= 500) { + lastError = new Error(`${base} ${method} -> ${res.status}`); + continue; + } + if (!res.ok) { + // 4xx is a request-level error, not an instance failure — surface it. + throw new Error(`${base} ${method} -> ${res.status} ${await res.text()}`); + } + stickyIndex = idx; + return (await res.json()) as T; + } catch (err) { + if (err instanceof Error && err.message.includes('-> 4')) throw err; + lastError = err; + } + } + + throw new Error(`all bobbin instances failed for ${method}: ${String(lastError)}`); + } + + return { get }; +} +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test bobbin` +Expected: 5 passing tests. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/bobbin.ts packages/core/test/bobbin.test.ts +git commit -m "feat(core): add resilient BobbinPool with failover + health gating" +``` + +--- + +## Task 8: Typed bobbin read methods + +**Files:** +- Create: `packages/core/src/reads.ts` +- Create: `packages/core/test/reads.test.ts` + +Thin typed wrappers over `pool.get` for the repo-scoped read surface. + +- [ ] **Step 1: Write the failing test** — `packages/core/test/reads.test.ts` + +```ts +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { createReads } from '../src/reads.ts'; + +const listPulls = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/listPulls.json', import.meta.url)), 'utf8'), +); +const listComments = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/listComments.json', import.meta.url)), 'utf8'), +); + +test('listPulls passes repoDid as subject and returns typed items', async () => { + const get = vi.fn().mockResolvedValue(listPulls); + const reads = createReads({ get }); + const out = await reads.listPulls('did:plc:repo'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.listPulls', { + subject: 'did:plc:repo', + limit: 100, + cursor: undefined, + }); + expect(out.items[0].state).toBe('open'); + expect(out.items[0].commentCount).toBe(2); +}); + +test('getDiscussion lists feed comments by subject uri', async () => { + const get = vi.fn().mockResolvedValue(listComments); + const reads = createReads({ get }); + const out = await reads.getDiscussion('at://did:plc:x/sh.tangled.repo.pull/1'); + expect(get).toHaveBeenCalledWith('sh.tangled.feed.listComments', { + subject: 'at://did:plc:x/sh.tangled.repo.pull/1', + limit: 100, + cursor: undefined, + }); + expect(out.items[0].value.body.original).toBe('yes that is correct!'); +}); + +test('getPull fetches a single record by uri', async () => { + const get = vi.fn().mockResolvedValue(listPulls.items[0]); + const reads = createReads({ get }); + await reads.getPull('at://did:plc:x/sh.tangled.repo.pull/1'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.getPull', { + pull: 'at://did:plc:x/sh.tangled.repo.pull/1', + }); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test reads` +Expected: FAIL — cannot find module `../src/reads.ts`. + +- [ ] **Step 3: Implement `packages/core/src/reads.ts`** + +```ts +import type { + CommentListItem, + IssueListItem, + IssueRecord, + ListResponse, + PullListItem, + PullRecord, + RecordEnvelope, + RepoListItem, + RepoRecord, +} from './types.ts'; + +export interface Getter { + get(method: string, params?: Record): Promise; +} + +const PAGE = 100; + +export function createReads(pool: Getter) { + return { + listRepos(ownerDid: string, cursor?: string) { + return pool.get>('sh.tangled.repo.listRepos', { + subject: ownerDid, + limit: PAGE, + cursor, + }); + }, + getRepo(repoUri: string) { + return pool.get>('sh.tangled.repo.getRepo', { repo: repoUri }); + }, + listPulls(repoDid: string, cursor?: string) { + return pool.get>('sh.tangled.repo.listPulls', { + subject: repoDid, + limit: PAGE, + cursor, + }); + }, + listIssues(repoDid: string, cursor?: string) { + return pool.get>('sh.tangled.repo.listIssues', { + subject: repoDid, + limit: PAGE, + cursor, + }); + }, + getPull(pullUri: string) { + return pool.get>('sh.tangled.repo.getPull', { pull: pullUri }); + }, + getIssue(issueUri: string) { + return pool.get>('sh.tangled.repo.getIssue', { issue: issueUri }); + }, + getDiscussion(subjectUri: string, cursor?: string) { + return pool.get>('sh.tangled.feed.listComments', { + subject: subjectUri, + limit: PAGE, + cursor, + }); + }, + }; +} + +export type Reads = ReturnType; +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test reads` +Expected: 3 passing tests. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/reads.ts packages/core/test/reads.test.ts +git commit -m "feat(core): add typed bobbin read methods" +``` + +--- + +## Task 9: Owner + repo resolution + +**Files:** +- Create: `packages/core/src/resolve.ts` +- Create: `packages/core/test/resolve.test.ts` + +Turn an owner handle/DID + repo name into a `RepoContext` (ownerDid, repoUri, repoDid, knot). Identity resolution is injected so the test needs no network. + +- [ ] **Step 1: Write the failing test** — `packages/core/test/resolve.test.ts` + +```ts +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { NoRfdRepoError, resolveRepoContext } from '../src/resolve.ts'; + +const repo = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/getRepo.json', import.meta.url)), 'utf8'), +); + +function readsStub(repos: unknown[]) { + return { + listRepos: vi.fn().mockResolvedValue({ items: repos, cursor: null }), + } as any; +} + +test('resolves a handle to did, then finds the named repo', async () => { + const identity = { resolveDid: vi.fn().mockResolvedValue('did:plc:owner') }; + const reads = readsStub([ + { uri: 'at://did:plc:owner/sh.tangled.repo/other', value: { name: 'other', knot: 'k', repoDid: 'did:plc:x' } }, + { uri: 'at://did:plc:owner/sh.tangled.repo/rfd', value: { name: 'rfd', knot: 'knot1', repoDid: 'did:plc:repo' } }, + ]); + const ctx = await resolveRepoContext({ reads, identity, owner: 'natemoo.re', repoName: 'rfd' }); + expect(identity.resolveDid).toHaveBeenCalledWith('natemoo.re'); + expect(reads.listRepos).toHaveBeenCalledWith('did:plc:owner', undefined); + expect(ctx).toEqual({ + ownerDid: 'did:plc:owner', + repoUri: 'at://did:plc:owner/sh.tangled.repo/rfd', + repoDid: 'did:plc:repo', + knot: 'knot1', + name: 'rfd', + }); +}); + +test('accepts a DID owner without identity resolution', async () => { + const identity = { resolveDid: vi.fn() }; + const reads = readsStub([repo]); // fixture name is "core" + const ctx = await resolveRepoContext({ reads, identity, owner: 'did:plc:wshs7t2adsemcrrd4snkeqli', repoName: 'core' }); + expect(identity.resolveDid).not.toHaveBeenCalled(); + expect(ctx.repoDid).toBe('did:plc:j5hmlfdrwkvtxm7cjmu7j2is'); +}); + +test('throws NoRfdRepoError when no repo matches the name', async () => { + const identity = { resolveDid: vi.fn().mockResolvedValue('did:plc:owner') }; + const reads = readsStub([ + { uri: 'at://x', value: { name: 'notrfd', knot: 'k', repoDid: 'did:plc:x' } }, + ]); + await expect( + resolveRepoContext({ reads, identity, owner: 'x', repoName: 'rfd' }), + ).rejects.toBeInstanceOf(NoRfdRepoError); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test resolve` +Expected: FAIL — cannot find module `../src/resolve.ts`. + +- [ ] **Step 3: Implement `packages/core/src/resolve.ts`** + +```ts +import type { Reads } from './reads.ts'; + +export interface Identity { + /** Resolve a handle to a DID. */ + resolveDid(handle: string): Promise; +} + +export interface RepoContext { + ownerDid: string; + repoUri: string; + repoDid: string; + knot: string; + name: string; +} + +export class NoRfdRepoError extends Error { + override name = 'NoRfdRepoError'; + constructor(owner: string, repoName: string) { + super(`no repo named "${repoName}" found for ${owner}`); + } +} + +export interface ResolveArgs { + reads: Pick; + identity: Identity; + owner: string; + repoName: string; +} + +function isDid(value: string): boolean { + return value.startsWith('did:'); +} + +export async function resolveRepoContext(args: ResolveArgs): Promise { + const { reads, identity, owner, repoName } = args; + const ownerDid = isDid(owner) ? owner : await identity.resolveDid(owner); + + let cursor: string | undefined; + do { + const page = await reads.listRepos(ownerDid, cursor); + for (const item of page.items) { + if (item.value.name === repoName) { + const repoDid = item.value.repoDid; + if (!repoDid) { + throw new Error(`repo "${repoName}" has no repoDid; cannot scope reads`); + } + return { + ownerDid, + repoUri: item.uri, + repoDid, + knot: item.value.knot, + name: item.value.name, + }; + } + } + cursor = page.cursor ?? undefined; + } while (cursor); + + throw new NoRfdRepoError(owner, repoName); +} +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test resolve` +Expected: 3 passing tests. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/resolve.ts packages/core/test/resolve.test.ts +git commit -m "feat(core): resolve owner + repo name to a repoDid context" +``` + +--- + +## Task 10: Pure proposal helpers (status + slug) + +**Files:** +- Create: `packages/core/src/proposal.ts` +- Create: `packages/core/test/proposal.test.ts` + +Pure functions only. File assembly (git-proxy tree/blob + patch reads) is Plan 2. The status logic is ported verbatim from `packages/www/src/lib/proposal.ts`. + +- [ ] **Step 1: Write the failing test** — `packages/core/test/proposal.test.ts` + +```ts +import { expect, test } from 'vitest'; +import { deriveStatus, fileNameToSlug, isProposalFile } from '../src/proposal.ts'; + +test('recognises numbered proposal filenames', () => { + expect(isProposalFile('0001.md')).toBe(true); + expect(isProposalFile('0002-governance.md')).toBe(true); + expect(isProposalFile('README.md')).toBe(false); + expect(isProposalFile('0001.txt')).toBe(false); +}); + +test('derives slug from filename', () => { + expect(fileNameToSlug('0002-governance.md')).toBe('0002-governance'); + expect(fileNameToSlug('notes.txt')).toBeNull(); +}); + +test('an open pull means discussion', () => { + expect(deriveStatus({ onDefaultBranch: false, pulls: [{ state: 'open' }] })).toBe('discussion'); +}); + +test('default branch + a merged pull means published', () => { + expect(deriveStatus({ onDefaultBranch: true, pulls: [{ state: 'merged' }] })).toBe('published'); +}); + +test('default branch with no relevant merged pull means committed', () => { + expect(deriveStatus({ onDefaultBranch: true, pulls: [] })).toBe('committed'); +}); + +test('all pulls closed off the default branch means abandoned', () => { + expect(deriveStatus({ onDefaultBranch: false, pulls: [{ state: 'closed' }] })).toBe('abandoned'); +}); + +test('nothing known means unknown', () => { + expect(deriveStatus({ onDefaultBranch: false, pulls: [] })).toBe('unknown'); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test proposal` +Expected: FAIL — cannot find module `../src/proposal.ts`. + +- [ ] **Step 3: Implement `packages/core/src/proposal.ts`** + +```ts +import type { PullState } from './types.ts'; + +export type ProposalStatus = + | 'discussion' + | 'abandoned' + | 'published' + | 'committed' + | 'unknown'; + +const PROPOSAL_FILE_RE = /^\d{4}(?:-[a-z0-9][a-z0-9-]*)?\.md$/; + +export function isProposalFile(name: string): boolean { + return PROPOSAL_FILE_RE.test(name); +} + +export function fileNameToSlug(name: string): string | null { + if (!isProposalFile(name)) return null; + return name.slice(0, -'.md'.length); +} + +export function deriveStatus(opts: { + onDefaultBranch: boolean; + pulls: { state: PullState }[]; +}): ProposalStatus { + const { onDefaultBranch, pulls } = opts; + const hasOpen = pulls.some((p) => p.state === 'open'); + const hasMerged = pulls.some((p) => p.state === 'merged'); + const allClosed = pulls.length > 0 && pulls.every((p) => p.state === 'closed'); + + if (hasOpen) return 'discussion'; + if (onDefaultBranch && hasMerged) return 'published'; + if (onDefaultBranch) return 'committed'; + if (allClosed) return 'abandoned'; + return 'unknown'; +} +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test proposal` +Expected: 7 passing tests. + +- [ ] **Step 5: Commit** + +```bash +git add packages/core/src/proposal.ts packages/core/test/proposal.test.ts +git commit -m "feat(core): add pure proposal status + slug helpers" +``` + +--- + +## Task 11: `createRfd()` factory + identity adapter + public exports + +**Files:** +- Create: `packages/core/src/identity.ts` +- Modify: `packages/core/src/index.ts` +- Create: `packages/core/test/index.test.ts` + +`createRfd()` resolves the repo context lazily (once) and exposes the read methods bound to `repoDid`. A real identity adapter wraps `@atcute/identity-resolver`. + +- [ ] **Step 1: Write the failing test** — `packages/core/test/index.test.ts` + +```ts +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { createRfd } from '../src/index.ts'; + +const repos = { + items: [ + { uri: 'at://did:plc:owner/sh.tangled.repo/rfd', value: { name: 'rfd', knot: 'knot1', repoDid: 'did:plc:repo' } }, + ], + cursor: null, +}; +const listPulls = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/listPulls.json', import.meta.url)), 'utf8'), +); + +test('createRfd resolves once, then scopes listPulls by repoDid', async () => { + const get = vi.fn(async (method: string) => { + if (method === 'sh.tangled.repo.listRepos') return repos; + if (method === 'sh.tangled.repo.listPulls') return listPulls; + throw new Error(`unexpected ${method}`); + }); + const identity = { resolveDid: vi.fn().mockResolvedValue('did:plc:owner') }; + const rfd = createRfd({ + config: { owner: 'natemoo.re', repoName: 'rfd', bobbinUrls: ['https://a.test'], cacheTtlSeconds: 60 }, + pool: { get }, + identity, + }); + + const a = await rfd.listPulls(); + const b = await rfd.listPulls(); + expect(a.items[0].state).toBe('open'); + // Resolution happened exactly once across both calls. + expect(get.mock.calls.filter(([m]) => m === 'sh.tangled.repo.listRepos')).toHaveLength(1); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.listPulls', { + subject: 'did:plc:repo', + limit: 100, + cursor: undefined, + }); + expect(b.items).toHaveLength(2); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter @rfd/core test index` +Expected: FAIL — `createRfd` is not exported. + +- [ ] **Step 3: Implement `packages/core/src/identity.ts`** + +```ts +import { + CompositeDidDocumentResolver, + CompositeHandleResolver, + DohJsonHandleResolver, + LocalActorResolver, + PlcDidDocumentResolver, + WebDidDocumentResolver, + WellKnownHandleResolver, +} from '@atcute/identity-resolver'; +import type { Identity } from './resolve.ts'; + +/** Real identity adapter backed by @atcute/identity-resolver. */ +export function createIdentity(): Identity { + const handleResolver = new CompositeHandleResolver({ + strategy: 'race', + methods: { + dns: new DohJsonHandleResolver({ dohUrl: 'https://mozilla.cloudflare-dns.com/dns-query' }), + http: new WellKnownHandleResolver(), + }, + }); + const didDocumentResolver = new CompositeDidDocumentResolver({ + methods: { plc: new PlcDidDocumentResolver(), web: new WebDidDocumentResolver() }, + }); + const resolver = new LocalActorResolver({ handleResolver, didDocumentResolver }); + return { + async resolveDid(handle: string): Promise { + const r = await resolver.resolve(handle as never); + return r.did; + }, + }; +} +``` + +- [ ] **Step 4: Implement `packages/core/src/index.ts`** + +```ts +import { createBobbinPool } from './bobbin.ts'; +import type { RfdConfig } from './config.ts'; +import { createIdentity } from './identity.ts'; +import { createReads } from './reads.ts'; +import type { Getter } from './reads.ts'; +import type { Identity, RepoContext } from './resolve.ts'; +import { resolveRepoContext } from './resolve.ts'; + +export { parseConfig } from './config.ts'; +export type { RfdConfig } from './config.ts'; +export { NoRfdRepoError } from './resolve.ts'; +export * from './types.ts'; +export { + deriveStatus, + fileNameToSlug, + isProposalFile, + type ProposalStatus, +} from './proposal.ts'; + +export interface CreateRfdArgs { + config: RfdConfig; + /** Override the transport (tests). Defaults to a BobbinPool over config.bobbinUrls. */ + pool?: Getter; + /** Override identity resolution (tests). Defaults to the @atcute adapter. */ + identity?: Identity; +} + +export function createRfd(args: CreateRfdArgs) { + const { config } = args; + const pool = args.pool ?? createBobbinPool({ urls: config.bobbinUrls }); + const identity = args.identity ?? createIdentity(); + const reads = createReads(pool); + + let contextPromise: Promise | null = null; + function context(): Promise { + contextPromise ??= resolveRepoContext({ + reads, + identity, + owner: config.owner, + repoName: config.repoName, + }); + return contextPromise; + } + + return { + getContext: context, + async getRepo() { + const ctx = await context(); + return reads.getRepo(ctx.repoUri); + }, + async listPulls(cursor?: string) { + const ctx = await context(); + return reads.listPulls(ctx.repoDid, cursor); + }, + async listIssues(cursor?: string) { + const ctx = await context(); + return reads.listIssues(ctx.repoDid, cursor); + }, + getPull(pullUri: string) { + return reads.getPull(pullUri); + }, + getIssue(issueUri: string) { + return reads.getIssue(issueUri); + }, + getDiscussion(subjectUri: string, cursor?: string) { + return reads.getDiscussion(subjectUri, cursor); + }, + }; +} + +export type Rfd = ReturnType; +``` + +- [ ] **Step 5: Run to verify it passes** + +Run: `pnpm --filter @rfd/core test index` +Expected: 1 passing test. + +- [ ] **Step 6: Run the whole core suite** + +Run: `pnpm --filter @rfd/core test` +Expected: every task's tests pass (at-uri, patch, types, config, bobbin, reads, resolve, proposal, index, smoke). + +- [ ] **Step 7: Commit** + +```bash +git add packages/core/src/identity.ts packages/core/src/index.ts packages/core/test/index.test.ts +git commit -m "feat(core): add createRfd factory + identity adapter" +``` + +--- + +## Task 12: Type-check the package + +**Files:** +- Modify: `packages/core/package.json` (add a `check` script) + +- [ ] **Step 1: Add a type-check script** to `packages/core/package.json` scripts: + +```json + "check": "tsc --noEmit -p tsconfig.json" +``` + +- [ ] **Step 2: Run the type-check** + +Run: `pnpm --filter @rfd/core check` +Expected: no type errors. If `tsc` isn't resolvable, add `"typescript": "^5"` to `devDependencies`, `pnpm install`, and re-run. + +- [ ] **Step 3: Commit** + +```bash +git add packages/core/package.json pnpm-lock.yaml +git commit -m "chore(core): add type-check script" +``` + +--- + +## Self-Review Notes (for the implementer) + +- **Spec coverage (Plan 1 slice):** bobbin failover pool + sticky + health gate (Task 7); `repoDid` scoping (Tasks 8–9, 11); `feed.comment` reads (Task 8); config incl. `BOBBIN_URL` pool + `RFD_CACHE_TTL` (Task 5); pure status/slug/patch domain logic (Tasks 3, 10); types-only record shapes, no lexicon codegen (Task 4). Deferred to later plans: proposal **file assembly** via git-proxy, the SSR short-TTL cache, `www` rewrite, web components/tokens, Cloudflare/microcosm deletion, Dockerfile/CI/Railway. +- **Open items carried forward:** git-proxy repo-param form and the `feed.comment` *write* body shape are resolved in Plan 2 (they only affect file assembly and the comment form). +- **Consistency:** `Getter` is the single transport interface consumed by `createReads` and `createRfd`; `Reads` is `ReturnType`; `RepoContext.repoDid` is the value threaded into every `subject` param. +``` diff --git a/docs/superpowers/plans/2026-07-30-rfd-distribution.md b/docs/superpowers/plans/2026-07-30-rfd-distribution.md new file mode 100644 index 0000000..79a4baf --- /dev/null +++ b/docs/superpowers/plans/2026-07-30-rfd-distribution.md @@ -0,0 +1,344 @@ +# Distribution & Cleanup Implementation Plan (Plan 4 of 4) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans. Steps use checkbox (`- [ ]`) syntax. + +**Goal:** Delete the now-dead Cloudflare + microcosm machinery and the lexicon codegen package, and add self-host distribution artifacts (Dockerfile, GitHub Actions publish workflow, Railway config, `.env.example`, README self-host docs) so any community can run their own RFD instance. + +**Architecture:** Pure subtraction plus static artifacts. Nothing runtime-behavioral changes — the app already runs entirely on `@rfd/core` after Plan 3. Deleting the legacy `src/lib/*` microcosm files also clears the last `astro check` errors. The Docker image builds the pnpm workspace and runs the `@astrojs/node` standalone server; the CI workflow and Railway config are authored but NOT executed (publishing/deploying needs the owner's credentials). + +**Tech Stack:** Docker, GitHub Actions, Railway, pnpm workspaces. + +**Prereqs:** Plans 1–3 complete. `www` builds on Node and imports only `@rfd/core` + retained `lib/oauth.ts`, `lib/draft.ts`, `lib/cache.ts`. + +**Autonomous guardrail:** Do NOT run `docker push`, `railway up`, publish an image, or open a PR. Author the artifacts and stop. A local `docker build` is allowed only if Docker is available; if not, skip it (the build command it runs — `pnpm --filter www build` — is already verified). + +--- + +## Task 1: Delete legacy microcosm/Cloudflare library + tests + workers + +**Files (delete):** +- `packages/www/src/lib/proposal.ts`, `discussion.ts`, `pull.ts`, `knot.ts`, `db.ts`, `patch.ts`, `atproto.ts`, `slingshot.ts`, `constellation.ts`, `spacedust.ts`, `spacedust-subscriber.ts`, `cold-start.ts`, `backfill.ts`, `index-event.ts` +- `packages/www/test/slingshot.test.ts`, `constellation.test.ts`, `spacedust.test.ts`, `pull-comments.test.ts`, `index-event.test.ts`, `resolve-actor.test.ts`, `patch.test.ts` +- `packages/www/workers/` (whole dir), `packages/www/wrangler.jsonc` +- Also delete `packages/www/worker-configuration.d.ts` if present, and remove `./worker-configuration.d.ts` from `packages/www/tsconfig.json`'s `include` if referenced. + +**Retained (do NOT delete):** `packages/www/src/lib/oauth.ts`, `draft.ts`, `cache.ts`; `packages/www/test/draft.test.ts`, `cache.test.ts`. + +- [ ] **Step 1: Delete the legacy lib, tests, and workers** + +```bash +cd packages/www +git rm src/lib/proposal.ts src/lib/discussion.ts src/lib/pull.ts src/lib/knot.ts \ + src/lib/db.ts src/lib/patch.ts src/lib/atproto.ts src/lib/slingshot.ts \ + src/lib/constellation.ts src/lib/spacedust.ts src/lib/spacedust-subscriber.ts \ + src/lib/cold-start.ts src/lib/backfill.ts src/lib/index-event.ts +git rm test/slingshot.test.ts test/constellation.test.ts test/spacedust.test.ts \ + test/pull-comments.test.ts test/index-event.test.ts test/resolve-actor.test.ts test/patch.test.ts +git rm -r workers wrangler.jsonc +git rm worker-configuration.d.ts 2>/dev/null || true +cd ../.. +``` + +- [ ] **Step 2: Clean `packages/www/tsconfig.json`** — if `include` lists `"./worker-configuration.d.ts"`, remove that entry. Leave the rest. + +- [ ] **Step 3: Verify the app still builds, type-checks clean, and tests pass** + +Run: +```bash +RFD_OWNER=example.com pnpm --filter www build +pnpm --filter www exec astro check +pnpm --filter www test +``` +Expected: build succeeds; **`astro check` now reports 0 errors** (the files that produced the 4 residual errors are gone); `www` tests pass (only `draft.test.ts` + `cache.test.ts` remain). If `astro check` still reports an error, it points at a file that still imports a deleted module — fix that import or delete the offending dead file, and note it. + +- [ ] **Step 4: Confirm nothing references the deleted surface** + +Run: `grep -rE "cloudflare:workers|from 'lexicon|spacedust|constellation|slingshot|index-event|cold-start" packages/www/src` +Expected: empty output. + +- [ ] **Step 5: Commit** + +```bash +git add -A packages/www +git commit -m "chore(www): delete legacy microcosm + cloudflare machinery" +``` + +--- + +## Task 2: Remove the `lexicon` codegen package + +The `st.itch.discussion.repo` claim is gone and `@rfd/core` ships its own types, so the `lexicon` workspace package has no consumers. + +- [ ] **Step 1: Confirm no consumers remain** + +Run: `grep -rE "from 'lexicon|\"lexicon\"|workspace:.*lexicon|lexicon/types" packages --include=*.ts --include=*.astro --include=package.json` +Expected: matches ONLY inside `packages/lexicon/` itself (its own files). If anything under `packages/www` or `packages/core` matches, STOP and report — a consumer still exists. + +- [ ] **Step 2: Remove the dependency from `packages/www/package.json`** — delete the `"lexicon": "workspace:*"` line from `dependencies`. + +- [ ] **Step 3: Delete the package** + +```bash +git rm -r packages/lexicon +``` + +- [ ] **Step 4: Reinstall + verify** + +Run: +```bash +pnpm install +RFD_OWNER=example.com pnpm --filter www build +pnpm --filter @rfd/core test +``` +Expected: install succeeds (lockfile updates to drop `lexicon`); `www` build succeeds; core tests still pass. If `pnpm install` errors about a missing `lexicon` workspace reference, some `package.json` still lists it — remove that reference. + +- [ ] **Step 5: Commit** + +```bash +git add -A +git commit -m "chore: remove lexicon codegen package (superseded by @rfd/core types)" +``` + +--- + +## Task 3: Dockerfile + .dockerignore + +**Files:** +- Create: `Dockerfile` (repo root) +- Create: `.dockerignore` (repo root) + +- [ ] **Step 1: Create `Dockerfile`** at the repo root + +```dockerfile +# syntax=docker/dockerfile:1 + +FROM node:24-slim AS base +ENV PNPM_HOME=/pnpm PATH=/pnpm:$PATH +RUN corepack enable +WORKDIR /app + +# --- build stage: install the workspace and build the www server --- +FROM base AS build +COPY pnpm-workspace.yaml pnpm-lock.yaml package.json tsconfig.json ./ +COPY packages/core/package.json ./packages/core/package.json +COPY packages/www/package.json ./packages/www/package.json +RUN pnpm install --frozen-lockfile +COPY packages ./packages +RUN pnpm --filter www build + +# --- runtime stage: node server --- +FROM base AS runtime +ENV NODE_ENV=production +# Bind to all interfaces so Docker/Railway can route to it; honor $PORT if set. +ENV HOST=0.0.0.0 +ENV PORT=4321 +COPY --from=build /app /app +WORKDIR /app/packages/www +EXPOSE 4321 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \ + CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||4321)+'/api/v0/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" +CMD ["node", "./dist/server/entry.mjs"] +``` + +Note: `RFD_OWNER` (and optionally `BOBBIN_URL`, `RFD_REPO_NAME`, `RFD_CACHE_TTL`, `PUBLIC_ORIGIN`) are provided at `docker run`/Railway time, not baked in. + +- [ ] **Step 2: Create `.dockerignore`** at the repo root + +``` +**/node_modules +**/dist +.git +.github +docs +**/*.test.ts +.DS_Store +``` + +- [ ] **Step 3: (Optional) local image build if Docker is available** + +Run: `docker build -t rfd:local . || echo "docker unavailable — skipping (Dockerfile runs the already-verified 'pnpm --filter www build')"` +Expected: either the image builds, or a clean skip. Do NOT `docker push`. + +- [ ] **Step 4: Commit** + +```bash +git add Dockerfile .dockerignore +git commit -m "feat: add Dockerfile for self-hosting" +``` + +--- + +## Task 4: GitHub Actions publish workflow (authored, not run) + +**Files:** +- Create: `.github/workflows/docker-publish.yml` + +- [ ] **Step 1: Create `.github/workflows/docker-publish.yml`** + +```yaml +name: Publish Docker image + +on: + push: + tags: ['v*'] + workflow_dispatch: + +jobs: + publish: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Derive tags + id: meta + uses: docker/metadata-action@v5 + with: + images: natemoo-re/rfd + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} +``` + +Note: requires repo secrets `DOCKERHUB_USERNAME` and `DOCKERHUB_TOKEN`. The image name `natemoo-re/rfd` is a placeholder — adjust to the chosen Docker Hub namespace. This workflow only runs on a pushed `v*` tag or manual dispatch; authoring it does not publish anything. + +- [ ] **Step 2: Commit** + +```bash +git add .github/workflows/docker-publish.yml +git commit -m "ci: add Docker Hub publish workflow (tag-triggered)" +``` + +--- + +## Task 5: Railway config, `.env.example`, and self-host README + +**Files:** +- Create: `railway.json` (repo root) +- Create: `.env.example` (repo root) +- Modify: `README.md` + +- [ ] **Step 1: Create `railway.json`** + +```json +{ + "$schema": "https://railway.app/railway.schema.json", + "build": { "builder": "DOCKERFILE", "dockerfilePath": "Dockerfile" }, + "deploy": { + "healthcheckPath": "/api/v0/healthz", + "healthcheckTimeout": 30, + "restartPolicyType": "ON_FAILURE" + } +} +``` + +- [ ] **Step 2: Create `.env.example`** + +```bash +# Required: the handle or DID whose `rfd` repo this instance serves. +RFD_OWNER=you.example.com + +# Optional (defaults shown). +RFD_REPO_NAME=rfd +BOBBIN_URL=https://api.tangled.org +RFD_CACHE_TTL=60 +# PUBLIC_ORIGIN=https://rfd.example.com +# PORT is provided by the host (Railway/Docker); the server honors it. +``` + +- [ ] **Step 3: Rewrite `README.md`** with self-host docs. Replace the file contents with: + +```markdown +# rfd + +An atproto-powered request-for-discussion (RFD) platform. A thin, single-tenant, +self-hostable client over [tangled](https://tangled.org)'s **bobbin** appview — no custom +indexing infrastructure required. + +## How it works + +- Proposals are numbered Markdown files (`NNNN-slug.md`) in a tangled git repo named `rfd`. +- Discussion happens through tangled pulls, issues, and comments. +- This app reads everything from a **bobbin** appview (default: `https://api.tangled.org`) + and writes go browser-side directly to the author's PDS via OAuth. + +## Packages + +- `packages/core` (`@rfd/core`) — headless, transport-agnostic library over bobbin. +- `packages/www` — Astro (Node) server that renders one owner's `rfd` repo. + +## Self-hosting + +The app is single-tenant: one instance serves one owner's `rfd` repo. + +### Docker + +```bash +docker run -p 4321:4321 -e RFD_OWNER=you.example.com natemoo-re/rfd +``` + +### Railway + +Deploy this repo; Railway builds the `Dockerfile` and injects `PORT`. Set `RFD_OWNER` +(and any optional vars below) in the service settings. + +### Configuration + +| Var | Default | Purpose | +|---|---|---| +| `RFD_OWNER` | — (required) | Handle or DID of the repo owner | +| `RFD_REPO_NAME` | `rfd` | Canonical repo name to serve | +| `BOBBIN_URL` | `https://api.tangled.org` | Comma-separated, preference-ordered bobbin pool | +| `RFD_CACHE_TTL` | `60` | Seconds to cache known-content responses | +| `PUBLIC_ORIGIN` | request-derived | Origin for OAuth client metadata | +| `PORT` | host-provided | HTTP listen port | + +## Development + +```bash +pnpm install +RFD_OWNER=you.example.com pnpm --filter www dev +pnpm --filter @rfd/core test +``` +``` + +- [ ] **Step 4: Verify** + +Run: `RFD_OWNER=example.com pnpm --filter www build` +Expected: succeeds (docs/config changes don't affect the build). + +- [ ] **Step 5: Commit** + +```bash +git add railway.json .env.example README.md +git commit -m "docs: add Railway config, .env.example, and self-host README" +``` + +--- + +## Self-Review Notes (for the implementer) + +- **Spec coverage:** legacy microcosm/CF + lexicon deleted (Tasks 1–2); Dockerfile → Docker Hub (Tasks 3–4); Railway config + env docs (Task 5). Nothing is published or deployed — artifacts only. +- **Gate progression:** after Task 1, `astro check` should hit 0 errors; after Task 2, `pnpm install` + build clean with no `lexicon`; the www test suite is reduced to `draft` + `cache`. +- **Do NOT:** push, publish an image, deploy, or open a PR. The image name `natemoo-re/rfd` is a placeholder to confirm with the owner. +- **Follow-ups (out of scope, note in final report):** browser QA of OAuth/PDS-write flows; handle resolution for comment author DIDs; threading the live default branch into `new.astro`. +``` diff --git a/docs/superpowers/plans/2026-07-30-rfd-www-rewrite.md b/docs/superpowers/plans/2026-07-30-rfd-www-rewrite.md new file mode 100644 index 0000000..3eba847 --- /dev/null +++ b/docs/superpowers/plans/2026-07-30-rfd-www-rewrite.md @@ -0,0 +1,1099 @@ +# www Thin Rewrite Implementation Plan (Plan 3 of 4) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans. Steps use checkbox (`- [ ]`) syntax. + +**Goal:** Rewrite the `www` Astro app as a single-tenant, server-first Node server that renders one owner's RFD repo entirely from `@rfd/core`, with a short-TTL SSR cache, server-island discussion, and vanilla web components for the browser-side OAuth + PDS writes. + +**Architecture:** Swap the Cloudflare adapter for `@astrojs/node` (standalone). Replace the Cloudflare Hono custom entry (`app.ts` + `astro/hono`) and `cloudflare:workers` env access with standard Astro API routes and `process.env`. A memoized `getRfd()` builds one `createRfd()` from env. Pages are thin: they call core, wrapped in an in-memory short-TTL cache for "known content"; live discussion renders as an Astro server island (`server:defer`). Client interactivity (login, draft submit, comment submit) moves into custom elements that reuse the existing `lib/oauth.ts` + `lib/draft.ts`. Single-tenant means routes drop the `[handle]` segment; the claim flow is deleted. + +**Tech Stack:** Astro 6 (`output: 'server'`, `@astrojs/node` standalone), TypeScript, `@rfd/core` (workspace), `@atcute/oauth-browser-client` (client OAuth), Vitest. + +**Prereqs:** Plans 1 & 2 complete — `@rfd/core` exposes `createRfd({config})` → `{ getContext, getRepo, listProposals, getProposal, listPulls, getPull, listIssues, getIssue, getDiscussion }`, plus `parseConfig(env)`, `NoRfdRepoError`, and record types. + +**Spec:** `docs/superpowers/specs/2026-07-30-rfd-bobbin-thin-client-design.md` + +**Deferred-item carried from Plan 2:** discussion comment pagination — `getProposal`/`getDiscussion` return the first page only; the Discussion island (Task 9) must page through the cursor. + +--- + +## Current-state facts (verified) + +- Pages currently read `env` from `cloudflare:workers` and pass `env.db` (D1) into `listProposals`/`getProposal`. Multi-tenant via a `[handle]` route param resolved by `getDiscussionRepo(handle)` (reads the `st.itch.discussion.repo` claim). All of this is replaced. +- `middleware.ts` already rewrites `/` → `/${RFD_DEFAULT_OWNER}` and `/${slug}` → `/${owner}/${slug}` for single-tenant. With `[handle]` gone, this middleware is deleted. +- `src/lib/oauth.ts` (client OAuth wrapper) and `src/lib/draft.ts` (pure client patch builder: `slugify`, `buildPatch`, `gzipString`) are **retained** — they run in the browser and have no server/CF deps. +- The legacy `app.ts`, `src/api/*.ts` (Hono), `src/lib/proposal.ts`, `discussion.ts`, `pull.ts`, and the microcosm/CF libs stay on disk until Plan 4 deletes them; this plan stops importing them. + +--- + +## File Structure + +``` +packages/www/ + astro.config.ts # MODIFY: node adapter, drop cloudflare + auxiliaryWorkers + package.json # MODIFY: deps (add @astrojs/node, @rfd/core; drop CF/wrangler) + src/ + config.ts # NEW: getRfd() memoized singleton from process.env + lib/cache.ts # NEW: in-memory short-TTL cache + styles/tokens.css # NEW: design tokens + layouts/Base.astro # NEW: html shell + tokens + components/ + Discussion.astro # NEW: server island (server:defer) for live comments + rfd-login.ts # NEW: custom element + rfd-oauth-callback.ts # NEW: + rfd-draft-editor.ts # NEW: + rfd-comment-form.ts # NEW: + pages/ + index.astro # REWRITE (was [handle].astro): proposal list + [slug].astro # NEW (was [handle]/[slug].astro): proposal detail + new.astro # NEW (was [handle]/new.astro): + pulls/[rkey].astro # NEW (was [handle]/pulls/[rkey].astro) + settings/login.astro # REWRITE: + settings/oauth/callback.astro # REWRITE: , redirect to / + oauth/client-metadata.json.ts # KEEP (already origin-derived) + api/v0/healthz.ts # NEW + api/v0/proposals.ts # NEW: list + api/v0/proposals/[slug].ts# NEW: detail + test/ + cache.test.ts # NEW +``` + +**Deleted in this plan:** `src/app.ts`, `src/api/*.ts` (old Hono), `src/middleware.ts`, `src/pages/[handle].astro`, `src/pages/[handle]/` (whole dir), `src/pages/settings/claim.astro`. **Retained:** `src/lib/oauth.ts`, `src/lib/draft.ts`, `src/components/Link.astro`. + +--- + +## Task 1: Swap adapter + wire `getRfd()` + boot + +**Files:** +- Modify: `packages/www/package.json` +- Modify: `packages/www/astro.config.ts` +- Create: `packages/www/src/config.ts` +- Delete: `packages/www/src/middleware.ts`, `packages/www/src/app.ts`, `packages/www/src/api/admin.ts`, `discussion.ts`, `proposals.ts`, `pulls.ts`, `healthz.ts` +- Create: `packages/www/src/pages/api/v0/healthz.ts` +- Temporary: `packages/www/src/pages/index.astro` (minimal boot page — replaced in Task 5) + +- [ ] **Step 1: Update dependencies** + +Run: +```bash +pnpm --filter www remove @astrojs/cloudflare wrangler @cloudflare/workers-types +pnpm --filter www add @astrojs/node +pnpm --filter www add @rfd/core@workspace:* +``` +Then edit `packages/www/package.json` scripts: remove `"preview": "wrangler dev"` and `"generate-types": "wrangler types"`; set `"preview": "node ./dist/server/entry.mjs"` and `"start": "node ./dist/server/entry.mjs"`. Keep `"dev"`, `"build"`, `"test"`. + +- [ ] **Step 2: Rewrite `packages/www/astro.config.ts`** + +```ts +import node from '@astrojs/node'; +import { defineConfig } from 'astro/config'; + +// https://astro.build/config +export default defineConfig({ + output: 'server', + adapter: node({ mode: 'standalone' }), + experimental: { + rustCompiler: true, + }, +}); +``` + +- [ ] **Step 3: Create `packages/www/src/config.ts`** — the server-side singleton + +```ts +import { createRfd, parseConfig, type Rfd } from '@rfd/core'; + +let instance: Rfd | null = null; + +/** The single-tenant RFD client, built once from process.env. */ +export function getRfd(): Rfd { + if (!instance) { + instance = createRfd({ config: parseConfig(process.env) }); + } + return instance; +} +``` + +- [ ] **Step 4: Delete the Cloudflare entry + legacy Hono API + middleware** + +```bash +git rm packages/www/src/app.ts packages/www/src/middleware.ts \ + packages/www/src/api/admin.ts packages/www/src/api/discussion.ts \ + packages/www/src/api/proposals.ts packages/www/src/api/pulls.ts \ + packages/www/src/api/healthz.ts +``` + +- [ ] **Step 5: Create `packages/www/src/pages/api/v0/healthz.ts`** (Astro API route) + +```ts +import type { APIRoute } from 'astro'; + +export const prerender = false; + +export const GET: APIRoute = () => + new Response(JSON.stringify({ ok: true }), { + headers: { 'content-type': 'application/json' }, + }); +``` + +- [ ] **Step 6: Replace `packages/www/src/pages/index.astro` and `[handle].astro` with a temporary boot page** + +```bash +git rm packages/www/src/pages/[handle].astro +``` +Then write a minimal `packages/www/src/pages/index.astro`: +```astro +--- +export const prerender = false; +--- + +rfd +

rfd boot ok

+``` + +- [ ] **Step 7: Verify the app builds on Node** + +Run: `RFD_OWNER=example.com pnpm --filter www build` +Expected: build succeeds and emits `packages/www/dist/server/entry.mjs`. (Setting `RFD_OWNER` is harmless here; config is only read at request time.) If `astro` complains about leftover `cloudflare:workers` imports, some legacy page still imports it — confirm only the temporary `index.astro`, `oauth/client-metadata.json.ts`, and untouched `[handle]/*` pages remain; the `[handle]/*` pages are deleted in Task 10, so for THIS task also delete them if they block the build: +```bash +git rm -r packages/www/src/pages/[handle] +``` + +- [ ] **Step 8: Commit** + +```bash +git add -A packages/www +git commit -m "feat(www): switch to @astrojs/node, add getRfd(), drop cloudflare entry" +``` + +--- + +## Task 2: In-memory short-TTL cache + +**Files:** +- Create: `packages/www/src/lib/cache.ts` +- Create: `packages/www/test/cache.test.ts` + +- [ ] **Step 1: Write the failing test** — `packages/www/test/cache.test.ts` + +```ts +import { expect, test, vi } from 'vitest'; +import { createCache } from '../src/lib/cache.ts'; + +test('caches within the TTL and refetches after expiry', async () => { + let now = 1000; + const cache = createCache({ nowMs: () => now }); + const fn = vi.fn(async () => ({ n: fn.mock.calls.length })); + + const a = await cache.wrap('k', 60, fn); + const b = await cache.wrap('k', 60, fn); + expect(a).toBe(b); // same cached value + expect(fn).toHaveBeenCalledTimes(1); + + now += 61_000; // past TTL + const c = await cache.wrap('k', 60, fn); + expect(fn).toHaveBeenCalledTimes(2); + expect(c).not.toBe(a); +}); + +test('different keys are independent', async () => { + const cache = createCache({ nowMs: () => 0 }); + const fn = vi.fn(async (k: string) => k.toUpperCase()); + expect(await cache.wrap('a', 60, () => fn('a'))).toBe('A'); + expect(await cache.wrap('b', 60, () => fn('b'))).toBe('B'); + expect(fn).toHaveBeenCalledTimes(2); +}); + +test('a rejected fn is not cached', async () => { + const cache = createCache({ nowMs: () => 0 }); + let calls = 0; + const fn = async () => { + calls++; + if (calls === 1) throw new Error('boom'); + return 'ok'; + }; + await expect(cache.wrap('k', 60, fn)).rejects.toThrow('boom'); + expect(await cache.wrap('k', 60, fn)).toBe('ok'); +}); +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `pnpm --filter www test cache` +Expected: FAIL — cannot find `../src/lib/cache.ts`. + +- [ ] **Step 3: Implement `packages/www/src/lib/cache.ts`** + +```ts +interface Entry { + value: unknown; + expiresAtMs: number; +} + +export interface CacheOptions { + nowMs?: () => number; +} + +export function createCache(options: CacheOptions = {}) { + const nowMs = options.nowMs ?? (() => Date.now()); + const store = new Map(); + + return { + /** Return the cached value for `key`, or run `fn`, cache it for `ttlSeconds`, and return it. */ + async wrap(key: string, ttlSeconds: number, fn: () => Promise): Promise { + const hit = store.get(key); + if (hit && hit.expiresAtMs > nowMs()) { + return hit.value as T; + } + const value = await fn(); + store.set(key, { value, expiresAtMs: nowMs() + ttlSeconds * 1000 }); + return value; + }, + clear(): void { + store.clear(); + }, + }; +} + +export type Cache = ReturnType; + +/** Process-wide cache shared by all requests. */ +export const cache: Cache = createCache(); +``` + +- [ ] **Step 4: Verify** + +Run: `pnpm --filter www test cache` +Expected: 3 passing tests. + +Note: `packages/www/package.json` already has a `"test": "vitest run"` script and `vitest` devDependency from the pre-rewrite setup. If `pnpm --filter www test` errors that vitest is missing, run `pnpm --filter www add -D vitest` first. + +- [ ] **Step 5: Commit** + +```bash +git add packages/www/src/lib/cache.ts packages/www/test/cache.test.ts +git commit -m "feat(www): add in-memory short-TTL cache" +``` + +--- + +## Task 3: Design tokens + Base layout + +**Files:** +- Create: `packages/www/src/styles/tokens.css` +- Create: `packages/www/src/layouts/Base.astro` + +- [ ] **Step 1: Create `packages/www/src/styles/tokens.css`** — a minimal, neutral token set (refine later) + +```css +:root { + --font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --font-mono: ui-monospace, "SF Mono", "Cascadia Code", Menlo, monospace; + + --color-bg: #ffffff; + --color-fg: #1a1a1a; + --color-muted: #6b7280; + --color-border: #e5e7eb; + --color-accent: #2563eb; + --color-surface: #f9fafb; + + --space-1: 0.25rem; + --space-2: 0.5rem; + --space-3: 1rem; + --space-4: 1.5rem; + --space-5: 2.5rem; + + --radius: 0.5rem; + --measure: 42rem; + + --text-sm: 0.875rem; + --text-base: 1rem; + --text-lg: 1.25rem; + --text-xl: 1.75rem; +} + +@media (prefers-color-scheme: dark) { + :root { + --color-bg: #0d0d0f; + --color-fg: #ededed; + --color-muted: #9ca3af; + --color-border: #26262b; + --color-accent: #60a5fa; + --color-surface: #16161a; + } +} + +* { box-sizing: border-box; } +body { + margin: 0; + font-family: var(--font-sans); + color: var(--color-fg); + background: var(--color-bg); + line-height: 1.55; +} +main { max-width: var(--measure); margin: 0 auto; padding: var(--space-4) var(--space-3); } +a { color: var(--color-accent); } +code, pre { font-family: var(--font-mono); font-size: var(--text-sm); } +pre { + background: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius); + padding: var(--space-3); + overflow: auto; + white-space: pre-wrap; +} +``` + +- [ ] **Step 2: Create `packages/www/src/layouts/Base.astro`** + +```astro +--- +import '../styles/tokens.css'; +import Link from '../components/Link.astro'; + +interface Props { title: string; } +const { title } = Astro.props; +--- + + + + + + {title} + + +
+ +
+
+ +
+ + +``` + +Note: `Link.astro` currently reads `env.RFD_DEFAULT_OWNER` from `cloudflare:workers` to strip an owner prefix. In single-tenant mode there is no prefix to strip. Simplify `Link.astro` to a plain pass-through: replace its frontmatter's env logic so it just renders `` with the `href` unchanged. Full replacement for `packages/www/src/components/Link.astro`: + +```astro +--- +import type { HTMLAttributes } from 'astro/types'; +type Props = HTMLAttributes<'a'>; +const props = Astro.props; +--- + +``` + +- [ ] **Step 3: Verify build** + +Run: `RFD_OWNER=example.com pnpm --filter www build` +Expected: build succeeds (tokens + layout compile; nothing renders them yet). + +- [ ] **Step 4: Commit** + +```bash +git add packages/www/src/styles/tokens.css packages/www/src/layouts/Base.astro packages/www/src/components/Link.astro +git commit -m "feat(www): add design tokens, Base layout, simplify Link" +``` + +--- + +## Task 4: Cached read helpers + +**Files:** +- Modify: `packages/www/src/config.ts` + +Add cached wrappers so pages don't repeat cache wiring. `RFD_CACHE_TTL` already parsed into `config.cacheTtlSeconds` by core; expose it. + +- [ ] **Step 1: Extend `packages/www/src/config.ts`** + +```ts +import { createRfd, parseConfig, type Rfd, type RfdConfig } from '@rfd/core'; +import { cache } from './lib/cache.ts'; + +let instance: Rfd | null = null; +let cfg: RfdConfig | null = null; + +function config(): RfdConfig { + cfg ??= parseConfig(process.env); + return cfg; +} + +/** The single-tenant RFD client, built once from process.env. */ +export function getRfd(): Rfd { + if (!instance) { + instance = createRfd({ config: config() }); + } + return instance; +} + +/** Cached proposal list (known content — short TTL). */ +export function listProposalsCached() { + return cache.wrap('proposals', config().cacheTtlSeconds, () => getRfd().listProposals()); +} + +/** Cached proposal detail (known content — short TTL). */ +export function getProposalCached(slug: string) { + return cache.wrap(`proposal:${slug}`, config().cacheTtlSeconds, () => getRfd().getProposal(slug)); +} +``` + +- [ ] **Step 2: Verify build** + +Run: `RFD_OWNER=example.com pnpm --filter www build` +Expected: succeeds. + +- [ ] **Step 3: Commit** + +```bash +git add packages/www/src/config.ts +git commit -m "feat(www): add cached read helpers" +``` + +--- + +## Task 5: Index page (proposal list) + +**Files:** +- Rewrite: `packages/www/src/pages/index.astro` + +- [ ] **Step 1: Rewrite `packages/www/src/pages/index.astro`** + +```astro +--- +import Base from '../layouts/Base.astro'; +import Link from '../components/Link.astro'; +import { getRfd, listProposalsCached } from '../config.ts'; + +export const prerender = false; + +let proposals: Awaited> = []; +let repoName = 'rfd'; +let error: string | null = null; +try { + const [list, repo] = await Promise.all([listProposalsCached(), getRfd().getRepo()]); + proposals = list; + repoName = repo.value.name; +} catch (err) { + Astro.response.status = 500; + error = err instanceof Error ? err.message : String(err); +} +--- + +

{repoName}

+ {error &&

{error}

} + {!error && proposals.length === 0 &&

No proposals yet. Draft one →

} +
    + {proposals.map((p) => ( +
  • + {p.slug} + {p.status} +
  • + ))} +
+ +``` + +- [ ] **Step 2: Verify build + types** + +Run: `RFD_OWNER=example.com pnpm --filter www build && pnpm --filter www exec astro check` +Expected: build succeeds; `astro check` reports 0 errors (warnings acceptable). + +- [ ] **Step 3: Commit** + +```bash +git add packages/www/src/pages/index.astro +git commit -m "feat(www): proposal list page reading @rfd/core" +``` + +--- + +## Task 6: Discussion server island + +**Files:** +- Create: `packages/www/src/components/Discussion.astro` + +The island fetches live comments for the proposal's pull URIs, paging through the cursor (closes the Plan 2 pagination gap). It runs deferred per request, uncached. + +- [ ] **Step 1: Create `packages/www/src/components/Discussion.astro`** + +```astro +--- +import { getRfd } from '../config.ts'; +import { parseAtUri } from '@rfd/core'; + +interface Props { pullUris: string[]; } +const { pullUris } = Astro.props; + +interface Entry { authorDid: string; body: string; createdAt: string; } +const rfd = getRfd(); +const entries: Entry[] = []; +for (const uri of pullUris) { + let cursor: string | undefined; + do { + const page = await rfd.getDiscussion(uri, cursor); + for (const c of page.items) { + entries.push({ + authorDid: parseAtUri(c.uri)?.did ?? '', + body: c.value.body.original, + createdAt: c.value.createdAt, + }); + } + cursor = page.cursor ?? undefined; + } while (cursor); +} +entries.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); +--- +
+

Discussion ({entries.length})

+ {entries.length === 0 &&

No comments yet.

} +
    + {entries.map((c) => ( +
  • +

    + {c.authorDid} · +

    +
    {c.body}
    +
  • + ))} +
+
+``` + +- [ ] **Step 2: Verify build** + +Run: `RFD_OWNER=example.com pnpm --filter www build` +Expected: succeeds. (`parseAtUri` must be exported from `@rfd/core` — it is, via `export * from './at-uri.ts'`? Confirm: if `astro check` reports `parseAtUri` is not exported, add `export { parseAtUri } from './at-uri.ts';` to `packages/core/src/index.ts`, rebuild core, and re-run. Commit that core change separately with message `feat(core): export parseAtUri`.) + +- [ ] **Step 3: Commit** + +```bash +git add packages/www/src/components/Discussion.astro +git commit -m "feat(www): live discussion server island with comment pagination" +``` + +--- + +## Task 7: Proposal detail page + +**Files:** +- Create: `packages/www/src/pages/[slug].astro` + +- [ ] **Step 1: Create `packages/www/src/pages/[slug].astro`** + +```astro +--- +import Base from '../layouts/Base.astro'; +import Discussion from '../components/Discussion.astro'; +import { getProposalCached } from '../config.ts'; +import '../components/rfd-comment-form.ts'; + +export const prerender = false; + +const { slug } = Astro.params; +let detail: Awaited> = null; +let error: string | null = null; +try { + detail = await getProposalCached(slug as string); + if (!detail) { + Astro.response.status = 404; + error = `proposal not found: ${slug}`; + } +} catch (err) { + Astro.response.status = 500; + error = err instanceof Error ? err.message : String(err); +} + +const pullUris = detail ? detail.pulls.map((p) => p.uri) : []; +--- + + {error &&

{error}

} + {detail && ( +
+

{detail.slug}

+

Status: {detail.status}

+ + {detail.content ? ( +
{detail.content.text}
+ ) : ( +

No committed content yet — see the open pull below.

+ )} + +
+

Pulls ({detail.pulls.length})

+
    + {detail.pulls.map((p) => ( +
  • + {p.state} · {p.value.title} + {' · '}{p.commentCount} comments +
  • + ))} +
+
+ + +

Loading discussion…

+
+ + {pullUris.length > 0 && ( + +
+ + + +
+
+ )} +
+ )} + +``` + +- [ ] **Step 2: Verify build + types** + +Run: `RFD_OWNER=example.com pnpm --filter www build && pnpm --filter www exec astro check` +Expected: build succeeds. `astro check` may warn about the unknown custom element `` — that is acceptable (custom elements aren't in the JSX intrinsic set); it must not be a hard error. The import of `rfd-comment-form.ts` is created in Task 8; if this task runs before Task 8, create a stub `packages/www/src/components/rfd-comment-form.ts` with `customElements.define('rfd-comment-form', class extends HTMLElement {});` and expand it in Task 8. + +- [ ] **Step 3: Commit** + +```bash +git add packages/www/src/pages/[slug].astro +git commit -m "feat(www): proposal detail page with discussion island + comment form" +``` + +--- + +## Task 8: Web components (login, callback, draft editor, comment form) + +**Files:** +- Create: `packages/www/src/components/rfd-login.ts` +- Create: `packages/www/src/components/rfd-oauth-callback.ts` +- Create: `packages/www/src/components/rfd-draft-editor.ts` +- Create: `packages/www/src/components/rfd-comment-form.ts` + +These reuse `../lib/oauth.ts` and `../lib/draft.ts`. They progressively enhance server-rendered markup (the `
` is in the light DOM; the element wires it up on connect). + +- [ ] **Step 1: `rfd-login.ts`** + +```ts +import { configure, startLogin } from '../lib/oauth.ts'; + +class RfdLogin extends HTMLElement { + connectedCallback() { + const form = this.querySelector('form'); + const input = this.querySelector('input[name="handle"]'); + if (!form || !input) return; + form.addEventListener('submit', async (e) => { + e.preventDefault(); + const handle = input.value.trim(); + if (!handle) return; + configure(); + await startLogin(handle); + }); + } +} +customElements.define('rfd-login', RfdLogin); +``` + +- [ ] **Step 2: `rfd-oauth-callback.ts`** + +```ts +import { configure, finishLogin } from '../lib/oauth.ts'; + +class RfdOauthCallback extends HTMLElement { + async connectedCallback() { + const status = this.querySelector('[data-status]'); + try { + configure(); + const session = await finishLogin(); + sessionStorage.setItem('rfd:did', session.info.sub); + location.assign('/'); + } catch (err) { + if (status) status.textContent = err instanceof Error ? err.message : String(err); + } + } +} +customElements.define('rfd-oauth-callback', RfdOauthCallback); +``` + +Note: `finishLogin()` returns the `Session`; the DID is `session.info.sub` (matching the legacy callback). If the installed `@atcute/oauth-browser-client` types name it differently, adjust to the field the legacy `settings/oauth/callback.astro` used (`session.info.sub`). + +- [ ] **Step 3: `rfd-draft-editor.ts`** — ports the legacy `new.astro` script + +```ts +import { configure, resumeAgent } from '../lib/oauth.ts'; +import { buildPatch, gzipString, slugify } from '../lib/draft.ts'; + +class RfdDraftEditor extends HTMLElement { + connectedCallback() { + const repoTarget = this.dataset.repoTarget!; + const defaultBranch = this.dataset.defaultBranch!; + const form = this.querySelector('form'); + const signin = this.querySelector('[data-signin]'); + const preview = this.querySelector('[data-filename]'); + const status = this.querySelector('[data-status]'); + const errorEl = this.querySelector('[data-error]'); + if (!form) return; + + const did = sessionStorage.getItem('rfd:did'); + if (!did) { if (signin) signin.hidden = false; form.hidden = true; return; } + + const titleInput = form.elements.namedItem('title') as HTMLInputElement; + const bodyInput = form.elements.namedItem('body') as HTMLTextAreaElement; + const setStatus = (t: string) => { if (status) status.textContent = t; }; + const showError = (m: string) => { if (errorEl) { errorEl.textContent = m; errorEl.hidden = false; } setStatus(''); }; + const updatePreview = () => { const s = slugify(titleInput.value); if (preview) preview.textContent = s ? `0000-${s}.md` : '0000-….md'; }; + titleInput.addEventListener('input', updatePreview); + updatePreview(); + + form.addEventListener('submit', async (e) => { + e.preventDefault(); + if (errorEl) errorEl.hidden = true; + const title = titleInput.value.trim(); + const body = bodyInput.value; + const slug = slugify(title); + if (!title || !slug) return showError('Title must contain at least one alphanumeric character.'); + if (!body.trim()) return showError('Body cannot be empty.'); + const fileName = `0000-${slug}.md`; + try { + setStatus('Preparing patch…'); + configure(); + const { rpc } = await resumeAgent(did); + const patch = await buildPatch({ title, body, fileName, authorName: did }); + const compressed = await gzipString(patch); + setStatus('Uploading patch…'); + const blobRes = await rpc.call('com.atproto.repo.uploadBlob', { + data: compressed as unknown as Blob, + headers: { 'content-type': 'application/gzip' }, + }); + const patchBlob = (blobRes.data as { blob: unknown }).blob; + setStatus('Creating pull…'); + const now = new Date().toISOString(); + await rpc.call('com.atproto.repo.createRecord', { + data: { + repo: did, + collection: 'sh.tangled.repo.pull', + record: { + $type: 'sh.tangled.repo.pull', + title, + createdAt: now, + target: { repo: repoTarget, branch: defaultBranch }, + source: { branch: `proposal/${Date.now().toString(36)}` }, + rounds: [{ createdAt: now, patchBlob }], + }, + }, + }); + setStatus('Done. Redirecting…'); + location.assign(`/0000-${slug}`); + } catch (err) { + showError(err instanceof Error ? err.message : String(err)); + } + }); + } +} +customElements.define('rfd-draft-editor', RfdDraftEditor); +``` + +- [ ] **Step 4: `rfd-comment-form.ts`** — writes a `sh.tangled.feed.comment` to the user's PDS + +```ts +import { configure, resumeAgent } from '../lib/oauth.ts'; + +class RfdCommentForm extends HTMLElement { + connectedCallback() { + const subject = this.dataset.subject!; + const form = this.querySelector('form'); + const status = this.querySelector('[data-status]'); + if (!form) return; + const setStatus = (t: string) => { if (status) status.textContent = t; }; + + form.addEventListener('submit', async (e) => { + e.preventDefault(); + const did = sessionStorage.getItem('rfd:did'); + if (!did) return setStatus('Sign in to comment.'); + const bodyEl = form.elements.namedItem('body') as HTMLTextAreaElement; + const body = bodyEl.value.trim(); + if (!body) return; + try { + setStatus('Posting…'); + configure(); + const { rpc } = await resumeAgent(did); + const now = new Date().toISOString(); + await rpc.call('com.atproto.repo.createRecord', { + data: { + repo: did, + collection: 'sh.tangled.feed.comment', + record: { + $type: 'sh.tangled.feed.comment', + subject, + body: { original: body }, + createdAt: now, + }, + }, + }); + setStatus('Posted. Reload to see it.'); + bodyEl.value = ''; + } catch (err) { + setStatus(err instanceof Error ? err.message : String(err)); + } + }); + } +} +customElements.define('rfd-comment-form', RfdCommentForm); +``` + +Note on the `feed.comment` write shape: `{ subject, body: { original }, createdAt }` mirrors the read shape confirmed live in the Plan-2 spike. If tangled's write validation rejects it (extra required fields like `references`), this is the one spot to adjust — it does not affect any other code. + +- [ ] **Step 5: Verify build** + +Run: `RFD_OWNER=example.com pnpm --filter www build` +Expected: succeeds (the components are bundled when imported by pages in Tasks 7 & 9). + +- [ ] **Step 6: Commit** + +```bash +git add packages/www/src/components/rfd-login.ts packages/www/src/components/rfd-oauth-callback.ts packages/www/src/components/rfd-draft-editor.ts packages/www/src/components/rfd-comment-form.ts +git commit -m "feat(www): web components for login, callback, draft, comment" +``` + +--- + +## Task 9: Auth + draft pages + +**Files:** +- Rewrite: `packages/www/src/pages/settings/login.astro` +- Rewrite: `packages/www/src/pages/settings/oauth/callback.astro` +- Create: `packages/www/src/pages/new.astro` + +- [ ] **Step 1: `settings/login.astro`** + +```astro +--- +import Base from '../../layouts/Base.astro'; +import '../../components/rfd-login.ts'; +export const prerender = false; +--- + +

Sign in

+ + + +

+ +
+ +``` + +- [ ] **Step 2: `settings/oauth/callback.astro`** + +```astro +--- +import Base from '../../../layouts/Base.astro'; +import '../../../components/rfd-oauth-callback.ts'; +export const prerender = false; +--- + + +

Completing sign-in…

+
+ +``` + +- [ ] **Step 3: `new.astro`** — server resolves target metadata from core; the component does the write + +```astro +--- +import Base from '../layouts/Base.astro'; +import Link from '../components/Link.astro'; +import { getRfd } from '../config.ts'; +import '../components/rfd-draft-editor.ts'; + +export const prerender = false; + +let repoTarget = ''; +let defaultBranch = 'main'; +let repoName = 'rfd'; +let error: string | null = null; +try { + const [ctx, repo] = await Promise.all([getRfd().getContext(), getRfd().getRepo()]); + // tangled writes target.repo as the repo's own DID (repoDid), not the at-uri. + repoTarget = ctx.repoDid; + repoName = repo.value.name; + const branch = await getRfd().getRepo().then(() => ctx); // defaultBranch lives on ctx if present + defaultBranch = (ctx as { defaultBranch?: string }).defaultBranch ?? 'main'; +} catch (err) { + Astro.response.status = 500; + error = err instanceof Error ? err.message : String(err); +} +--- + +

New draft proposal

+ {error &&

{error}

} + {!error && ( + + +
+

+

+

Will create 0000-….md

+

+ +
+
+ )} + +``` + +Note: `defaultBranch` — the `RepoContext` from `getContext()` does not currently carry the default branch (Plan 1 `resolve.ts` returns `{ownerDid, repoUri, repoDid, knot, name}`). Simplify the frontmatter: drop the `branch`/`defaultBranch`-from-ctx line and instead fetch it via the git client. Since `www` shouldn't reach into core internals, add a `getDefaultBranch()` method to the core factory in a tiny core change, OR default to `'main'`. For this plan, **default to `'main'`** (tangled's pulls target the default branch, and the appview resolves it) — replace the two `branch`/`defaultBranch` lines in the frontmatter with `defaultBranch = 'main';`. Keep it simple; a follow-up can thread the real branch. + +Corrected frontmatter block (use this): +```ts +let repoTarget = ''; +let defaultBranch = 'main'; +let repoName = 'rfd'; +let error: string | null = null; +try { + const [ctx, repo] = await Promise.all([getRfd().getContext(), getRfd().getRepo()]); + repoTarget = ctx.repoDid; + repoName = repo.value.name; +} catch (err) { + Astro.response.status = 500; + error = err instanceof Error ? err.message : String(err); +} +``` + +- [ ] **Step 4: Verify build + types** + +Run: `RFD_OWNER=example.com pnpm --filter www build && pnpm --filter www exec astro check` +Expected: build succeeds; `astro check` 0 errors (custom-element warnings OK). + +- [ ] **Step 5: Commit** + +```bash +git add packages/www/src/pages/settings/login.astro packages/www/src/pages/settings/oauth/callback.astro packages/www/src/pages/new.astro +git commit -m "feat(www): login, callback, and draft pages via web components" +``` + +--- + +## Task 10: Pull page, API routes, and cleanup of legacy pages + +**Files:** +- Create: `packages/www/src/pages/pulls/[rkey].astro` +- Create: `packages/www/src/pages/api/v0/proposals.ts` +- Create: `packages/www/src/pages/api/v0/proposals/[slug].ts` +- Delete: `packages/www/src/pages/settings/claim.astro` (and any remaining `[handle]/*`) + +- [ ] **Step 1: `pulls/[rkey].astro`** — single pull via core + +The pull's AT-URI is `at:///sh.tangled.repo.pull/`. Resolve the owner DID from context, then `getPull`. + +```astro +--- +import Base from '../../layouts/Base.astro'; +import { getRfd } from '../../config.ts'; + +export const prerender = false; + +const { rkey } = Astro.params; +let pull: Awaited['getPull']>> | null = null; +let error: string | null = null; +try { + const ctx = await getRfd().getContext(); + const uri = `at://${ctx.ownerDid}/sh.tangled.repo.pull/${rkey}`; + pull = await getRfd().getPull(uri); +} catch (err) { + Astro.response.status = 500; + error = err instanceof Error ? err.message : String(err); +} +--- + + {error &&

{error}

} + {pull && ( +
+

{pull.value.title}

+ {pull.value.body &&
{pull.value.body}
} +
+ )} + +``` + +Note: this pull's author here is assumed to be the repo owner (single-tenant list-owner pulls). Cross-author pulls have a different DID in their URI; a fuller pull route would carry the full URI. For this plan, owner-authored pulls are the target; if `getPull` 404s, the page shows the error. Acceptable for the prototype. + +- [ ] **Step 2: `api/v0/proposals.ts`** + +```ts +import type { APIRoute } from 'astro'; +import { listProposalsCached } from '../../../config.ts'; + +export const prerender = false; + +export const GET: APIRoute = async () => { + try { + const proposals = await listProposalsCached(); + return new Response(JSON.stringify({ proposals }), { headers: { 'content-type': 'application/json' } }); + } catch (err) { + return new Response(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }), { + status: 500, headers: { 'content-type': 'application/json' }, + }); + } +}; +``` + +- [ ] **Step 3: `api/v0/proposals/[slug].ts`** + +```ts +import type { APIRoute } from 'astro'; +import { getProposalCached } from '../../../../config.ts'; + +export const prerender = false; + +export const GET: APIRoute = async ({ params }) => { + try { + const proposal = await getProposalCached(params.slug as string); + if (!proposal) { + return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } }); + } + return new Response(JSON.stringify({ proposal }), { headers: { 'content-type': 'application/json' } }); + } catch (err) { + return new Response(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }), { + status: 500, headers: { 'content-type': 'application/json' }, + }); + } +}; +``` + +- [ ] **Step 4: Delete the claim flow and any remaining `[handle]` pages** + +```bash +git rm packages/www/src/pages/settings/claim.astro +# remove the [handle] directory if it still exists (Task 1 may have already): +git rm -r "packages/www/src/pages/[handle]" 2>/dev/null || true +``` + +- [ ] **Step 5: Verify the whole app builds + type-checks** + +Run: `RFD_OWNER=example.com pnpm --filter www build && pnpm --filter www exec astro check && pnpm --filter www test` +Expected: build succeeds; `astro check` 0 errors; cache test passes. Confirm no source file still imports `cloudflare:workers`, `../lib/proposal.ts`, `../lib/discussion.ts`, `../lib/pull.ts`, or `lexicon` (grep: `grep -rE "cloudflare:workers|lib/(proposal|discussion|pull)\.ts|from 'lexicon" packages/www/src` should return nothing). + +- [ ] **Step 6: Commit** + +```bash +git add -A packages/www +git commit -m "feat(www): pull page, /api/v0 routes, remove claim + [handle] pages" +``` + +--- + +## Self-Review Notes (for the implementer) + +- **Spec coverage:** node adapter + single-tenant (`getRfd` from env, no `[handle]`, claim deleted) — Tasks 1, 10; SSR short-TTL cache — Tasks 2, 4; server-island discussion with pagination — Tasks 6, 7 (closes the Plan 2 gap); web components + tokens — Tasks 3, 8, 9; thin `/api/v0` via Astro routes — Task 10. +- **Cannot be verified headlessly:** the OAuth + PDS-write flows (login, draft submit, comment submit) require a real browser + atproto account. The build/type-check gates confirm they compile and bundle; a human must QA the live flows. Note this in the final report. +- **Known simplifications (intentional):** `new.astro` targets the default branch as `'main'` rather than threading the live default branch; the pull route assumes owner-authored pulls. Both are acceptable prototype scope and flagged for follow-up. +- **Consistency:** pages call `getRfd()`/`listProposalsCached()`/`getProposalCached()` from `src/config.ts`; the cache key scheme is `proposals` and `proposal:`; `parseAtUri` and record types come from `@rfd/core`. +``` diff --git a/docs/superpowers/specs/2026-07-30-rfd-bobbin-thin-client-design.md b/docs/superpowers/specs/2026-07-30-rfd-bobbin-thin-client-design.md new file mode 100644 index 0000000..09ae106 --- /dev/null +++ b/docs/superpowers/specs/2026-07-30-rfd-bobbin-thin-client-design.md @@ -0,0 +1,285 @@ +# RFD Platform — Bobbin Thin-Client Redesign + +**Date:** 2026-07-30 +**Status:** Approved design, ready for implementation planning + +## Context + +The RFD platform is an atproto-powered "request for discussion" app. Proposals are +numbered Markdown files (`NNNN[-slug].md`) living in a Tangled git repo; discussion +happens through Tangled pulls, issues, and comments. The current prototype builds its +own atproto read infrastructure on the **microcosm** stack — a Spacedust firehose +subscriber on a Cloudflare Durable Object, Constellation backfill, Slingshot hydration, +and a D1 index — and deploys to Cloudflare. + +Tangled has since released **bobbin**: a read-only, self-hostable appview that serves +the read side of the `sh.tangled.*` lexicons over XRPC. A public instance runs at +`https://api.tangled.org`. Bobbin makes all of the app's custom indexing machinery +redundant. + +This redesign rebuilds the platform as a thin, single-tenant, self-deployable client +over bobbin, and moves off Cloudflare to a plain Node server on Railway (plus a Docker +image for community self-hosting). + +## Goals + +- Delete the entire custom atproto data layer; read everything from bobbin. +- Single-tenant: one deployment serves one owner's canonical `rfd` repo. +- Headless, transport-agnostic core library reusable by the web app and a future CLI. +- Server-first Astro frontend: vanilla web components + a simple CSS design-token system. +- Self-deployable: Docker image + env-only configuration. +- Resilient to bobbin instance outages via a failover pool. + +## Non-Goals + +- Multi-tenant / multi-repo hosting (deliberate constraint; a later fork if needed). +- A persistent local index or database in the baseline. A small in-memory, + short-TTL response cache *is* baseline (it is the content-freshness mechanism, see + Rendering Strategy). A persistent read-through store (Railway Postgres/Redis) for scale + or read-your-writes remains a deferred optimization. +- Owning a firehose subscription — bobbin's Hydrant-backed freshness (~90s) is the live + path now. +- Writes through bobbin — bobbin is read-only; writes stay browser-side to the user's PDS. + +## Spike Findings (validated against `api.tangled.org`) + +These facts are confirmed against the live hosted instance and anchor the design: + +- **Repo scoping key is the repo's `repoDid`** — the knot-assigned DID on the + `sh.tangled.repo` record — passed as `subject`. NOT the owner DID or the repo AT-URI. + - `sh.tangled.repo.countIssues?subject=` → `{count, distinctAuthors}` + - `sh.tangled.repo.listPulls?subject=&limit=&cursor=` → paginated, repo-scoped +- **`listPulls` items are pre-aggregated** with `state` (open/closed/merged) and + `commentCount` — no local status indexing needed. +- **Comments use the modern unified `sh.tangled.feed.comment`** collection, listed via + `sh.tangled.feed.listComments?subject=&limit=&cursor=`. The vendored + `repo.pull.comment` / `repo.issue.comment` types are obsolete. +- **Single-record detail:** `repo.getRepo(repo=)`, `repo.getPull(pull=)`, + `repo.getIssue(issue=)`, `actor.getProfile(actor=)`. +- **Git data** (tree/blob/diff/log/archive) is proxied by bobbin via + `sh.tangled.repo.tree` / `.blob` / `.getDefaultBranch` — replaces direct knot calls. + (Repo-param form — AT-URI vs `did/name` — to reconfirm at implementation time; methods + exist on bobbin, confirmed by schema-validation errors rather than 404s.) +- **Health:** `sh.tangled.bobbin.getCoverage` → `{ready, eventsProcessed, lastCursor}`. +- **Search:** `sh.tangled.search.query?q=`. + +## Architecture + +### Monorepo layout + +``` +packages/ + core/ @rfd/core — headless, transport-agnostic RFD library (incl. record types) + www/ Astro Node server: thin pages → core, web components, design tokens + (future) cli/ — another @rfd/core consumer +``` + +The previous `packages/lexicon` codegen package is removed. Under bobbin we run no local +lexicon validation or CBOR decoding (reads are hydrated JSON; writes construct plain +record objects through the OAuth client), and we no longer author any custom lexicon +(`st.itch.discussion.repo` is gone). The only remaining value is TypeScript types, which +live as a hand-authored `types.ts` in `@rfd/core` covering just the fields we read/write +(repo, pull, issue, `feed.comment`). + +### `@rfd/core` — headless library + +Pure TypeScript. No Astro, Hono, or DOM dependencies. A factory resolves identity once +and returns plain-data methods: + +```ts +const rfd = createRfd({ bobbinUrls, owner, repoName }); // owner → did → repoDid (cached) + +rfd.listProposals(): Promise +rfd.getProposal(slug): Promise // content + pulls + discussion +rfd.listPulls() / rfd.getPull(uri) +rfd.listIssues() / rfd.getIssue(uri) +rfd.getDiscussion(subjectUri) // feed.listComments +rfd.getRepo() / rfd.getProfile(did) +rfd.search(q) +``` + +Internal modules: + +- `bobbin.ts` — XRPC fetch client + failover pool (below). +- `proposal.ts` — proposal domain model and **pure** status derivation. +- `patch.ts` — **pure** patch/diff parsing (which `.md` files a pull touches). +- `resolve.ts` — owner handle/DID → `sh.tangled.repo` record → `repoDid`. +- `config.ts` — config parsing/validation. +- `types.ts` — hand-authored TypeScript types for the records we read/write + (`repo`, `pull`, `issue`, `feed.comment`). Replaces the removed lexicon codegen package. + +A future CLI imports these methods directly — no HTTP hop required. + +### Repo discovery (single-tenant, canonical name) + +The owner is fixed by `RFD_OWNER` (handle or DID), resolved at boot. Discovery: + +1. Resolve `RFD_OWNER` → owner DID. +2. `sh.tangled.repo.listRepos?subject=`; select the repo whose + `name === RFD_REPO_NAME` (default `rfd`). +3. Read its `repoDid` (scoping key), `knot`, and default branch. + +No `st.itch.discussion.repo` claim record and no claim flow. If no repo named `rfd` +exists, the app surfaces a `NoRfdRepoError` (404). + +### Bobbin failover pool + +Resilience against instance outages (more public instances are expected over time). Lives +in `@rfd/core` so every consumer benefits. + +- `BOBBIN_URL` is a comma-separated, preference-ordered list (default + `https://api.tangled.org`). New instances are added via env, no code change. +- Every read tries instances in order with a short per-request timeout; on network error, + 5xx, or timeout, fail over to the next. Error surfaces only when all are exhausted. + Safe because every bobbin call is an idempotent GET. +- **Sticky primary:** remember the last instance that succeeded (in-process) and start + there next time; periodically reset to preference order so a recovered primary is + reused. +- **Health gate:** before adopting a *new* instance, check + `sh.tangled.bobbin.getCoverage` and skip if `ready !== true`; cache that result briefly. +- **Caveat:** instances differ in freshness/coverage, so failover can momentarily serve + slightly staler data. Acceptable for reads; read-your-writes belongs to the deferred + cache. + +### Read surface (bobbin method map) + +| Need | Method | Key | +|---|---|---| +| Discover repo | `repo.listRepos` | `subject=ownerDid`, filter `name` | +| Repo meta / repoDid | `repo.getRepo` | `repo=uri` | +| Pulls (w/ `state`, `commentCount`) | `repo.listPulls` | `subject=repoDid` | +| Issues | `repo.listIssues` | `subject=repoDid` | +| Pull / issue detail | `repo.getPull` / `repo.getIssue` | `pull=` / `issue=` | +| Discussion thread | `feed.listComments` | `subject=pull|issueUri` | +| Proposal files / content / diff | `repo.tree` / `.blob` / `.getDefaultBranch` | `repo=uri` | +| Author profiles | `actor.getProfile` | `actor=did` | +| Search | `search.query` | `q=` | + +### Proposal domain model + +An RFD is a numbered `NNNN[-slug].md` file, either committed on the default branch or +living inside an open pull's patch. Status derives from pull states + default-branch +presence: + +- `discussion` — an open pull touches the file +- `published` — on default branch and a pull merged +- `committed` — on default branch, no relevant merged pull +- `abandoned` — all touching pulls closed, not on default branch +- `unknown` — otherwise + +The current `fallbackOwner*` PDS-walkers and every `env.DB` branch are **deleted** — +`listPulls?subject=repoDid` already returns all pulls across authors, which is exactly +the cross-author gap those fallbacks patched. `patch.ts` stays but fetches diffs via +bobbin. + +### `www` — thin Astro Node server + +- Adapter `@astrojs/node` (`mode: 'standalone'`), `output: 'server'`. Boots as a plain + Node HTTP server. +- Single-tenant routes (no `[handle]` segment): + - `/` — proposal list + - `/[slug]` — proposal detail + discussion + - `/new` — draft a proposal + - `/pulls/[rkey]` — pull view + - `/settings/login`, `/oauth/*` — auth + - **Deleted:** `/settings/claim`, all `/[handle]*` routes +- Pages are thin: they call `@rfd/core` and render. No business logic in `.astro` files. +- `/api/v0` (Hono) is retained but only delegates to core — it serves the web components' + client-side reads and is itself a remote integration surface. + +### Rendering strategy + +Three layers, ordered by the priority stack (static shell → known content → dynamic +content). There is no build-time prerender: on plain Node there is no ISR, and build-time +static generation would go stale until redeploy — the wrong fit for deploy-and-forget +self-hosting. + +1. **Static shell** — layout, nav, design tokens, chrome. Static/near-static, effectively + free to serve on every response. +2. **Known content** — the proposal list and proposal document bodies. Rendered on demand + via SSR, wrapped in a small **in-memory, short-TTL response cache** in `@rfd/core` + (default TTL `RFD_CACHE_TTL`, e.g. 60s) that revalidates from the bobbin pool on + expiry. Always fresh within a TTL window, no rebuild, no external store. +3. **Dynamic content** — discussion threads and live pull/issue state. Rendered as Astro + **server islands** (`server:defer`) inside the SSR page, fetched from bobbin per + request and **not** cached, so threads reflect the latest state on every load. + +The in-memory cache is the baseline freshness mechanism only; a persistent read-through +store (Postgres/Redis) for scale or read-your-writes stays deferred and would slot behind +the same `@rfd/core` seam. + +### Frontend: server-first + web components + tokens + +- Server-rendered HTML by default; no hydration for static content. +- Vanilla web components (`customElements.define`) only for interactive islands that need + browser-side OAuth + PDS writes: ``, ``, + ``. +- A single `tokens.css` of CSS custom properties (color, space, type scale, radius, + motion) consumed by component styles. No framework, no build step. + +### Writes (unchanged) + +OAuth stays fully browser-side (`@atcute/oauth-browser-client`); sessions live in the +browser. Users write pull, issue, and `feed.comment` records directly to their own PDS. +The draft flow is unchanged except the comment record type. + +## Distribution & Deployment + +- **Dockerfile:** multi-stage (pnpm build → slim non-root Node runtime), `EXPOSE $PORT`, + healthcheck on `/api/v0/healthz`. +- **CI:** a GitHub Action builds and pushes to **Docker Hub** (`natemoo-re/rfd`, + configurable) on release tags. +- **Railway:** runs the image alongside Cooper. +- **Self-host:** set `RFD_OWNER`, optionally point `BOBBIN_URL` at your own bobbin, + `docker run`. + +### Configuration (all env) + +| Var | Default | Purpose | +|---|---|---| +| `RFD_OWNER` | — (required) | Handle or DID of the instance's repo owner | +| `RFD_REPO_NAME` | `rfd` | Canonical repo name to discover | +| `BOBBIN_URL` | `https://api.tangled.org` | Comma-separated, preference-ordered bobbin pool | +| `RFD_CACHE_TTL` | `60` | Seconds to cache known-content SSR responses in memory | +| `PUBLIC_ORIGIN` | derived from request | Origin for OAuth `client_id` / `redirect_uri` | +| `RFD_ADMIN_TOKEN` | — | Admin API auth | +| `PORT` | Railway-provided | HTTP listen port | + +## Record types (no lexicon package) + +The `packages/lexicon` codegen package is removed (see Monorepo layout). Record shapes we +depend on live as hand-authored types in `@rfd/core/types.ts`: + +- **Read/write:** `sh.tangled.repo`, `sh.tangled.repo.pull`, `sh.tangled.repo.issue`, + `sh.tangled.feed.comment` (the current unified comment model — confirmed against the live + API; supersedes the stale `repo.pull.comment` / `repo.issue.comment`). +- **Removed entirely:** `st.itch.discussion.repo` (claim removed). +- The `feed.comment` **write** body shape (nested `body.original` plus references/mentions) + is to be confirmed at implementation time. + +## Deletions + +Everything Cloudflare + microcosm + codegen: `spacedust*`, `constellation`, `slingshot`, +`cold-start`, `backfill`, `index-event`, `db`, `knot`, `migrations/`, `workers/`, +`wrangler.jsonc`, `@astrojs/cloudflare` + `wrangler` + `@cloudflare/workers-types`, D1 +bindings, the `SPACEDUST` service binding, the `packages/lexicon` codegen package + its +`lex.config.ts` pipeline, the claim page/flow, and all `[handle]` routes. Roughly ~1,500 +LOC plus an entire aux Worker. + +## Testing + +- `@rfd/core` unit-tested against real bobbin response fixtures captured during the spike. +- Pure status-derivation and patch-parsing logic get table tests. +- A couple of Astro page smoke tests. +- No wrangler/D1 test harness. + +## Risks & Open Items + +- **Single upstream dependency.** If all pooled bobbin instances are down or cold (≤20 min + worst-case warmup), the app degrades. Mitigations: the failover pool, a deferred Railway + Postgres/Redis read-through cache, and self-hostable bobbin via `BOBBIN_URL`. +- **Git-proxy repo-param form** (AT-URI vs `did/name`) to reconfirm at implementation + time — a quick check, not an architectural risk. +- **`feed.comment` write body shape** to confirm before building ``. +- **Freshness on failover** — pooled instances may differ in coverage; acceptable for + reads. diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 0000000..0edd992 --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,25 @@ +{ + "name": "@rfd/core", + "type": "module", + "version": "0.0.1", + "devEngines": { + "node": ">=24.15.0" + }, + "main": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./package.json": "./package.json" + }, + "scripts": { + "test": "vitest run", + "test:watch": "vitest", + "check": "tsc --noEmit -p tsconfig.json" + }, + "dependencies": { + "@atcute/identity-resolver": "^2.0.0" + }, + "devDependencies": { + "@types/node": "^26.1.2", + "vitest": "^4.0.0" + } +} diff --git a/packages/core/src/assembly.ts b/packages/core/src/assembly.ts new file mode 100644 index 0000000..f0f4472 --- /dev/null +++ b/packages/core/src/assembly.ts @@ -0,0 +1,155 @@ +import { parseAtUri } from './at-uri.ts'; +import { deriveStatus, fileNameToSlug, isProposalFile, type ProposalStatus } from './proposal.ts'; +import type { Git } from './git.ts'; +import type { PullPatchDeps } from './patch-fetch.ts'; +import { pullMarkdownPaths as defaultPullMarkdownPaths } from './patch-fetch.ts'; +import type { CommentListItem, ListResponse, PullListItem, PullState } from './types.ts'; + +export interface ProposalSummary { + slug: string; + status: ProposalStatus; +} + +export interface DiscussionEntry { + source: 'pull' | 'issue'; + uri: string; + authorDid: string; + body: string; + createdAt: string; +} + +export interface ProposalDetail { + slug: string; + status: ProposalStatus; + content: { source: 'default' | 'pull'; text: string } | null; + pulls: PullListItem[]; + discussion: DiscussionEntry[]; +} + +export interface AssemblyDeps { + repoUri: string; + repoDid: string; + git: Pick; + reads: { + listPulls: (repoDid: string, cursor?: string) => Promise>; + getDiscussion: (subjectUri: string, cursor?: string) => Promise>; + }; + /** Override for tests; defaults to the real PDS patch fetch. */ + pullMarkdownPaths?: (uri: string, pull: PullListItem['value'], deps: PullPatchDeps) => Promise; + /** Passed through to the default pullMarkdownPaths. */ + patchDeps?: PullPatchDeps; +} + +async function defaultBranchName(deps: AssemblyDeps): Promise { + try { + return (await deps.git.getDefaultBranch()).name || 'main'; + } catch { + return 'main'; + } +} + +async function committedSlugs(deps: AssemblyDeps, ref: string): Promise> { + const slugs = new Set(); + try { + const tree = await deps.git.listTree(ref); + for (const f of tree.files) { + if (isProposalFile(f.name)) { + const slug = fileNameToSlug(f.name); + if (slug) slugs.add(slug); + } + } + } catch { + // empty repo / knot unreachable — no committed proposals + } + return slugs; +} + +/** Map every pull to the proposal slugs its latest patch touches. */ +async function pullsBySlug(deps: AssemblyDeps): Promise> { + const resolvePaths = + deps.pullMarkdownPaths ?? + ((uri, pull, d) => defaultPullMarkdownPaths(uri, pull, d)); + const patchDeps = deps.patchDeps ?? { resolvePds: async () => '' }; + const bySlug = new Map(); + + let cursor: string | undefined; + do { + const page = await deps.reads.listPulls(deps.repoDid, cursor); + for (const item of page.items) { + const paths = await resolvePaths(item.uri, item.value, patchDeps); + for (const path of paths) { + const slug = fileNameToSlug(path); + if (!slug) continue; + const arr = bySlug.get(slug) ?? []; + arr.push(item); + bySlug.set(slug, arr); + } + } + cursor = page.cursor ?? undefined; + } while (cursor); + + return bySlug; +} + +export async function listProposals(deps: AssemblyDeps): Promise { + const ref = await defaultBranchName(deps); + const committed = await committedSlugs(deps, ref); + const byslug = await pullsBySlug(deps); + + const slugs = new Set([...committed, ...byslug.keys()]); + const summaries: ProposalSummary[] = []; + for (const slug of slugs) { + const pulls = byslug.get(slug) ?? []; + const status = deriveStatus({ + onDefaultBranch: committed.has(slug), + pulls: pulls.map((p) => ({ state: p.state as PullState })), + }); + summaries.push({ slug, status }); + } + summaries.sort((a, b) => a.slug.localeCompare(b.slug)); + return summaries; +} + +export async function getProposal(deps: AssemblyDeps, slug: string): Promise { + const ref = await defaultBranchName(deps); + const filename = `${slug}.md`; + + const fromDefault = await deps.git.getBlob(ref, filename); + const onDefaultBranch = fromDefault !== null; + + const byslug = await pullsBySlug(deps); + const pulls = byslug.get(slug) ?? []; + + if (!onDefaultBranch && pulls.length === 0) return null; + + let content: ProposalDetail['content'] = null; + if (fromDefault !== null) { + content = { source: 'default', text: fromDefault }; + } + // (Reading proposal body from an open pull's patch is left to the www layer, + // which has the author PDS wiring the www page will own; here we surface + // pulls + default content.) + + const status = deriveStatus({ + onDefaultBranch, + pulls: pulls.map((p) => ({ state: p.state as PullState })), + }); + + const discussion: DiscussionEntry[] = []; + for (const pull of pulls) { + const comments = await deps.reads.getDiscussion(pull.uri); + for (const c of comments.items) { + const parsed = parseAtUri(c.uri); + discussion.push({ + source: 'pull', + uri: c.uri, + authorDid: parsed?.did ?? '', + body: c.value.body.original, + createdAt: c.value.createdAt, + }); + } + } + discussion.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + + return { slug, status, content, pulls, discussion }; +} diff --git a/packages/core/src/at-uri.ts b/packages/core/src/at-uri.ts new file mode 100644 index 0000000..61a83a0 --- /dev/null +++ b/packages/core/src/at-uri.ts @@ -0,0 +1,15 @@ +export interface ParsedAtUri { + did: string; + collection: string; + rkey: string; +} + +export function parseAtUri(uri: string): ParsedAtUri | null { + if (!uri.startsWith('at://')) return null; + const rest = uri.slice('at://'.length); + const parts = rest.split('/'); + if (parts.length < 3) return null; + const [did, collection, ...rkeyParts] = parts; + if (!did || !collection || rkeyParts.length === 0) return null; + return { did, collection, rkey: rkeyParts.join('/') }; +} diff --git a/packages/core/src/bobbin.ts b/packages/core/src/bobbin.ts new file mode 100644 index 0000000..07818df --- /dev/null +++ b/packages/core/src/bobbin.ts @@ -0,0 +1,111 @@ +import type { Coverage } from './types.ts'; + +export type FetchImpl = (input: string | URL, init?: RequestInit) => Promise; + +export interface BobbinPoolOptions { + urls: string[]; + fetchImpl?: FetchImpl; + /** Per-request timeout in ms. */ + timeoutMs?: number; + /** How long a health-check result is trusted, in ms. */ + healthTtlMs?: number; + /** Injectable clock for tests. */ + nowMs?: () => number; +} + +export interface BobbinPool { + get(method: string, params?: Record): Promise; +} + +interface HealthEntry { + ready: boolean; + checkedAtMs: number; +} + +/** A 4xx request-level error — surfaced to the caller rather than triggering failover. */ +export class XrpcRequestError extends Error { + constructor(readonly status: number, message: string) { + super(message); + this.name = 'XrpcRequestError'; + } +} + +function buildUrl(base: string, method: string, params: Record): string { + const url = new URL(`/xrpc/${method}`, base); + for (const [key, value] of Object.entries(params)) { + if (value !== undefined) url.searchParams.set(key, String(value)); + } + return url.toString(); +} + +export function createBobbinPool(options: BobbinPoolOptions): BobbinPool { + const { + urls, + fetchImpl = fetch, + timeoutMs = 10_000, + healthTtlMs = 30_000, + nowMs = () => Date.now(), + } = options; + + if (urls.length === 0) throw new Error('createBobbinPool requires at least one URL'); + + let stickyIndex = 0; + const health = new Map(); + + async function rawGet(base: string, method: string, params: Record): Promise { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + try { + return await fetchImpl(buildUrl(base, method, params), { signal: controller.signal }); + } finally { + clearTimeout(timer); + } + } + + async function isReady(base: string): Promise { + const cached = health.get(base); + if (cached && nowMs() - cached.checkedAtMs < healthTtlMs) return cached.ready; + let ready = false; + try { + const res = await rawGet(base, 'sh.tangled.bobbin.getCoverage', {}); + if (res.ok) ready = ((await res.json()) as Coverage).ready === true; + } catch { + ready = false; + } + health.set(base, { ready, checkedAtMs: nowMs() }); + return ready; + } + + async function get(method: string, params: Record = {}): Promise { + // Ordered candidate list beginning at the sticky instance. + const order = urls.map((_, i) => (stickyIndex + i) % urls.length); + let lastError: unknown; + + for (let pos = 0; pos < order.length; pos++) { + const idx = order[pos]!; + const base = urls[idx]!; + // The sticky primary (pos 0) is used directly; failover targets are health-gated. + if (pos > 0 && !(await isReady(base))) continue; + try { + const res = await rawGet(base, method, params); + if (res.status >= 500) { + lastError = new Error(`${base} ${method} -> ${res.status}`); + continue; + } + if (!res.ok) { + // 4xx is a request-level error, not an instance failure — surface it. + throw new XrpcRequestError(res.status, `${base} ${method} -> ${res.status} ${await res.text()}`); + } + stickyIndex = idx; + return (await res.json()) as T; + } catch (err) { + if (err instanceof XrpcRequestError) throw err; + lastError = err; + } + } + + throw new Error(`all bobbin instances failed for ${method}: ${String(lastError)}`); + } + + return { get }; +} diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts new file mode 100644 index 0000000..c3c72ab --- /dev/null +++ b/packages/core/src/config.ts @@ -0,0 +1,38 @@ +export interface RfdConfig { + owner: string; + repoName: string; + bobbinUrls: string[]; + cacheTtlSeconds: number; +} + +export type Env = Record; + +const DEFAULT_BOBBIN = 'https://api.tangled.org'; + +export function parseConfig(env: Env): RfdConfig { + const owner = env.RFD_OWNER?.trim(); + if (!owner) { + throw new Error('RFD_OWNER is required (the handle or DID of the RFD repo owner)'); + } + + const bobbinUrls = (env.BOBBIN_URL ?? DEFAULT_BOBBIN) + .split(',') + .map((u) => u.trim()) + .filter((u) => u.length > 0); + if (bobbinUrls.length === 0) { + throw new Error('BOBBIN_URL must contain at least one URL'); + } + + const ttlRaw = env.RFD_CACHE_TTL ?? '60'; + const cacheTtlSeconds = Number(ttlRaw); + if (!Number.isFinite(cacheTtlSeconds) || cacheTtlSeconds < 0) { + throw new Error(`RFD_CACHE_TTL must be a non-negative number, got: ${ttlRaw}`); + } + + return { + owner, + repoName: env.RFD_REPO_NAME?.trim() || 'rfd', + bobbinUrls, + cacheTtlSeconds, + }; +} diff --git a/packages/core/src/git.ts b/packages/core/src/git.ts new file mode 100644 index 0000000..f6734a4 --- /dev/null +++ b/packages/core/src/git.ts @@ -0,0 +1,60 @@ +import { XrpcRequestError } from './bobbin.ts'; +import type { Getter } from './reads.ts'; + +export interface DefaultBranch { + name: string; + hash: string; + when: string; +} + +export interface TreeFile { + name: string; + mode: string; + size: number; +} + +export interface TreeResponse { + ref: string; + files: TreeFile[]; +} + +export interface BlobResponse { + content: string; + encoding: 'utf-8' | 'base64'; + size: number; + isBinary?: boolean; +} + +export function createGit(pool: Getter, repoUri: string) { + return { + getDefaultBranch(): Promise { + return pool.get('sh.tangled.repo.getDefaultBranch', { repo: repoUri }); + }, + listTree(ref: string): Promise { + return pool.get('sh.tangled.repo.tree', { repo: repoUri, ref }); + }, + async getBlob(ref: string, path: string): Promise { + let data: BlobResponse; + try { + data = await pool.get('sh.tangled.repo.blob', { repo: repoUri, ref, path }); + } catch (err) { + // A 4xx means the path/ref doesn't exist — treat as absent. Anything + // else (pool exhaustion, 5xx) is a real failure and propagates. + if (err instanceof XrpcRequestError) return null; + throw err; + } + if (data.isBinary) return null; + return data.encoding === 'base64' ? decodeBase64Utf8(data.content) : data.content; + }, + }; +} + +/** Decode base64 as UTF-8 (atob alone yields Latin-1, mangling non-ASCII text). */ +function decodeBase64Utf8(b64: string): string { + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + return new TextDecoder().decode(bytes); +} + +export type Git = ReturnType; diff --git a/packages/core/src/identity.ts b/packages/core/src/identity.ts new file mode 100644 index 0000000..9f23e11 --- /dev/null +++ b/packages/core/src/identity.ts @@ -0,0 +1,49 @@ +import { + CompositeDidDocumentResolver, + CompositeHandleResolver, + DohJsonHandleResolver, + LocalActorResolver, + PlcDidDocumentResolver, + WebDidDocumentResolver, + WellKnownHandleResolver, +} from '@atcute/identity-resolver'; +import type { Identity } from './resolve.ts'; + +export interface ActorResolver { + resolve(actor: string): Promise<{ did: string; handle: string; pds: string }>; +} + +/** Build an Identity from any actor resolver (injectable for tests). */ +export function createIdentityFrom(resolver: ActorResolver): Identity { + return { + async resolveDid(handle: string): Promise { + const r = await resolver.resolve(handle); + return r.did; + }, + async resolvePds(actor: string): Promise { + const r = await resolver.resolve(actor); + return r.pds; + }, + }; +} + +/** Real identity adapter backed by @atcute/identity-resolver. */ +export function createIdentity(): Identity { + const handleResolver = new CompositeHandleResolver({ + strategy: 'race', + methods: { + dns: new DohJsonHandleResolver({ dohUrl: 'https://mozilla.cloudflare-dns.com/dns-query' }), + http: new WellKnownHandleResolver(), + }, + }); + const didDocumentResolver = new CompositeDidDocumentResolver({ + methods: { plc: new PlcDidDocumentResolver(), web: new WebDidDocumentResolver() }, + }); + const local = new LocalActorResolver({ handleResolver, didDocumentResolver }); + return createIdentityFrom({ + async resolve(actor: string) { + const r = await local.resolve(actor as never); + return { did: r.did, handle: r.handle, pds: r.pds }; + }, + }); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 0000000..334994c --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,102 @@ +import { createBobbinPool } from './bobbin.ts'; +import type { RfdConfig } from './config.ts'; +import { createIdentity } from './identity.ts'; +import { createReads } from './reads.ts'; +import type { Getter } from './reads.ts'; +import type { Identity, RepoContext } from './resolve.ts'; +import { resolveRepoContext } from './resolve.ts'; +import { createGit } from './git.ts'; +import { listProposals as assembleList, getProposal as assembleGet } from './assembly.ts'; + +export { parseConfig } from './config.ts'; +export type { RfdConfig } from './config.ts'; +export { parseAtUri } from './at-uri.ts'; +export type { ParsedAtUri } from './at-uri.ts'; +export { NoRfdRepoError } from './resolve.ts'; +export { XrpcRequestError } from './bobbin.ts'; +export * from './types.ts'; +export { + deriveStatus, + fileNameToSlug, + isProposalFile, + type ProposalStatus, +} from './proposal.ts'; +export * from './git.ts'; +export type { ProposalSummary, ProposalDetail, DiscussionEntry } from './assembly.ts'; + +export interface CreateRfdArgs { + config: RfdConfig; + /** Override the transport (tests). Defaults to a BobbinPool over config.bobbinUrls. */ + pool?: Getter; + /** Override identity resolution (tests). Defaults to the @atcute adapter. */ + identity?: Identity; +} + +export function createRfd(args: CreateRfdArgs) { + const { config } = args; + const pool = args.pool ?? createBobbinPool({ urls: config.bobbinUrls }); + const identity = args.identity ?? createIdentity(); + const reads = createReads(pool); + + let contextPromise: Promise | null = null; + function context(): Promise { + contextPromise ??= resolveRepoContext({ + reads, + identity, + owner: config.owner, + repoName: config.repoName, + }); + return contextPromise; + } + + return { + getContext: context, + async getRepo() { + const ctx = await context(); + return reads.getRepo(ctx.repoUri); + }, + async listPulls(cursor?: string) { + const ctx = await context(); + return reads.listPulls(ctx.repoDid, cursor); + }, + async listIssues(cursor?: string) { + const ctx = await context(); + return reads.listIssues(ctx.repoDid, cursor); + }, + getPull(pullUri: string) { + return reads.getPull(pullUri); + }, + getIssue(issueUri: string) { + return reads.getIssue(issueUri); + }, + getDiscussion(subjectUri: string, cursor?: string) { + return reads.getDiscussion(subjectUri, cursor); + }, + async listProposals() { + const ctx = await context(); + const git = createGit(pool, ctx.repoUri); + return assembleList({ + repoUri: ctx.repoUri, + repoDid: ctx.repoDid, + git, + reads: { listPulls: (d, c) => reads.listPulls(d, c), getDiscussion: (u, c) => reads.getDiscussion(u, c) }, + patchDeps: { resolvePds: (did) => identity.resolvePds(did) }, + }); + }, + async getProposal(slug: string) { + const ctx = await context(); + const git = createGit(pool, ctx.repoUri); + return assembleGet({ + repoUri: ctx.repoUri, + repoDid: ctx.repoDid, + git, + reads: { listPulls: (d, c) => reads.listPulls(d, c), getDiscussion: (u, c) => reads.getDiscussion(u, c) }, + patchDeps: { resolvePds: (did) => identity.resolvePds(did) }, + }, slug); + }, + }; +} + +export type Rfd = ReturnType; + +export const RFD_CORE_VERSION = '0.0.1'; diff --git a/packages/core/src/patch-fetch.ts b/packages/core/src/patch-fetch.ts new file mode 100644 index 0000000..ad2f9ec --- /dev/null +++ b/packages/core/src/patch-fetch.ts @@ -0,0 +1,56 @@ +import { parseAtUri } from './at-uri.ts'; +import { gunzipToString, listMarkdownFilesInDiff } from './patch.ts'; +import type { PullRecord } from './types.ts'; + +export type FetchImpl = (input: string | URL, init?: RequestInit) => Promise; + +export function latestPatchCid(pull: PullRecord): string | null { + const rounds = pull.rounds ?? []; + const latest = rounds[rounds.length - 1]; + return latest?.patchBlob?.ref?.$link ?? null; +} + +/** Fetch and gunzip a patch blob from the author's PDS. Returns null on any failure. */ +export async function fetchPatchText( + pds: string, + authorDid: string, + patchCid: string, + fetchImpl: FetchImpl = fetch, +): Promise { + const url = new URL('/xrpc/com.atproto.sync.getBlob', pds); + url.searchParams.set('did', authorDid); + url.searchParams.set('cid', patchCid); + const res = await fetchImpl(url); + if (!res.ok) return null; + const bytes = new Uint8Array(await res.arrayBuffer()); + try { + return await gunzipToString(bytes); + } catch { + return null; + } +} + +export interface PullPatchDeps { + resolvePds: (did: string) => Promise; + fetchImpl?: FetchImpl; +} + +/** Resolve the pull author's PDS, fetch the latest patch, and return the `.md` paths it touches. */ +export async function pullMarkdownPaths( + pullUri: string, + pull: PullRecord, + deps: PullPatchDeps, +): Promise { + const cid = latestPatchCid(pull); + const parsed = parseAtUri(pullUri); + if (!cid || !parsed) return []; + let pds: string; + try { + pds = await deps.resolvePds(parsed.did); + } catch { + return []; + } + const text = await fetchPatchText(pds, parsed.did, cid, deps.fetchImpl); + if (!text) return []; + return listMarkdownFilesInDiff(text).map((entry) => entry.path); +} diff --git a/packages/www/src/lib/patch.ts b/packages/core/src/patch.ts similarity index 97% rename from packages/www/src/lib/patch.ts rename to packages/core/src/patch.ts index 21fcfb6..b86c69a 100644 --- a/packages/www/src/lib/patch.ts +++ b/packages/core/src/patch.ts @@ -11,7 +11,7 @@ export interface MarkdownFileEntry { } export async function gunzipToString(gz: Uint8Array): Promise { - const stream = new Response(gz).body!.pipeThrough(new DecompressionStream('gzip')); + const stream = new Response(gz as BodyInit).body!.pipeThrough(new DecompressionStream('gzip')); const buf = await new Response(stream).arrayBuffer(); return new TextDecoder().decode(buf); } diff --git a/packages/core/src/proposal.ts b/packages/core/src/proposal.ts new file mode 100644 index 0000000..68cc545 --- /dev/null +++ b/packages/core/src/proposal.ts @@ -0,0 +1,35 @@ +import type { PullState } from './types.ts'; + +export type ProposalStatus = + | 'discussion' + | 'abandoned' + | 'published' + | 'committed' + | 'unknown'; + +const PROPOSAL_FILE_RE = /^\d{4}(?:-[a-z0-9][a-z0-9-]*)?\.md$/; + +export function isProposalFile(name: string): boolean { + return PROPOSAL_FILE_RE.test(name); +} + +export function fileNameToSlug(name: string): string | null { + if (!isProposalFile(name)) return null; + return name.slice(0, -'.md'.length); +} + +export function deriveStatus(opts: { + onDefaultBranch: boolean; + pulls: { state: PullState }[]; +}): ProposalStatus { + const { onDefaultBranch, pulls } = opts; + const hasOpen = pulls.some((p) => p.state === 'open'); + const hasMerged = pulls.some((p) => p.state === 'merged'); + const allClosed = pulls.length > 0 && pulls.every((p) => p.state === 'closed'); + + if (hasOpen) return 'discussion'; + if (onDefaultBranch && hasMerged) return 'published'; + if (onDefaultBranch) return 'committed'; + if (allClosed) return 'abandoned'; + return 'unknown'; +} diff --git a/packages/core/src/reads.ts b/packages/core/src/reads.ts new file mode 100644 index 0000000..44f4ed7 --- /dev/null +++ b/packages/core/src/reads.ts @@ -0,0 +1,61 @@ +import type { + CommentListItem, + IssueListItem, + IssueRecord, + ListResponse, + PullListItem, + PullRecord, + RecordEnvelope, + RepoListItem, + RepoRecord, +} from './types.ts'; + +export interface Getter { + get(method: string, params?: Record): Promise; +} + +const PAGE = 100; + +export function createReads(pool: Getter) { + return { + listRepos(ownerDid: string, cursor?: string) { + return pool.get>('sh.tangled.repo.listRepos', { + subject: ownerDid, + limit: PAGE, + cursor, + }); + }, + getRepo(repoUri: string) { + return pool.get>('sh.tangled.repo.getRepo', { repo: repoUri }); + }, + listPulls(repoDid: string, cursor?: string) { + return pool.get>('sh.tangled.repo.listPulls', { + subject: repoDid, + limit: PAGE, + cursor, + }); + }, + listIssues(repoDid: string, cursor?: string) { + return pool.get>('sh.tangled.repo.listIssues', { + subject: repoDid, + limit: PAGE, + cursor, + }); + }, + getPull(pullUri: string) { + return pool.get>('sh.tangled.repo.getPull', { pull: pullUri }); + }, + getIssue(issueUri: string) { + return pool.get>('sh.tangled.repo.getIssue', { issue: issueUri }); + }, + getDiscussion(subjectUri: string, cursor?: string) { + return pool.get>('sh.tangled.feed.listComments', { + subject: subjectUri, + limit: PAGE, + cursor, + }); + }, + }; +} + +export type Reads = ReturnType; diff --git a/packages/core/src/resolve.ts b/packages/core/src/resolve.ts new file mode 100644 index 0000000..f4ea2d5 --- /dev/null +++ b/packages/core/src/resolve.ts @@ -0,0 +1,62 @@ +import type { Reads } from './reads.ts'; + +export interface Identity { + /** Resolve a handle to a DID. */ + resolveDid(handle: string): Promise; + /** Resolve a DID (or handle) to its PDS service URL. */ + resolvePds(actor: string): Promise; +} + +export interface RepoContext { + ownerDid: string; + repoUri: string; + repoDid: string; + knot: string; + name: string; +} + +export class NoRfdRepoError extends Error { + override name = 'NoRfdRepoError'; + constructor(owner: string, repoName: string) { + super(`no repo named "${repoName}" found for ${owner}`); + } +} + +export interface ResolveArgs { + reads: Pick; + identity: Identity; + owner: string; + repoName: string; +} + +function isDid(value: string): boolean { + return value.startsWith('did:'); +} + +export async function resolveRepoContext(args: ResolveArgs): Promise { + const { reads, identity, owner, repoName } = args; + const ownerDid = isDid(owner) ? owner : await identity.resolveDid(owner); + + let cursor: string | undefined; + do { + const page = await reads.listRepos(ownerDid, cursor); + for (const item of page.items) { + if (item.value.name === repoName) { + const repoDid = item.value.repoDid; + if (!repoDid) { + throw new Error(`repo "${repoName}" has no repoDid; cannot scope reads`); + } + return { + ownerDid, + repoUri: item.uri, + repoDid, + knot: item.value.knot, + name: item.value.name, + }; + } + } + cursor = page.cursor ?? undefined; + } while (cursor); + + throw new NoRfdRepoError(owner, repoName); +} diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts new file mode 100644 index 0000000..ed44c36 --- /dev/null +++ b/packages/core/src/types.ts @@ -0,0 +1,76 @@ +/** Envelope bobbin returns for a single record. */ +export interface RecordEnvelope { + uri: string; + cid: string; + value: T; +} + +/** Paginated list response shape used across list* methods. */ +export interface ListResponse { + items: T[]; + cursor: string | null; +} + +export type PullState = 'open' | 'closed' | 'merged'; + +/** sh.tangled.repo */ +export interface RepoRecord { + $type: 'sh.tangled.repo'; + name: string; + knot: string; + description?: string; + createdAt: string; + /** Knot-assigned DID for the repo; the scoping key for issues/pulls. */ + repoDid?: string; + labels?: string[]; +} + +/** One patch round on a pull. */ +export interface PullRound { + createdAt: string; + patchBlob?: { ref?: { $link?: string } }; +} + +/** sh.tangled.repo.pull */ +export interface PullRecord { + $type: 'sh.tangled.repo.pull'; + title: string; + body?: string; + target: { repo: string; branch: string }; + source?: { repo?: string; branch?: string }; + rounds?: PullRound[]; + createdAt: string; +} + +/** sh.tangled.repo.issue */ +export interface IssueRecord { + $type: 'sh.tangled.repo.issue'; + title: string; + body?: string; + repo: string; + createdAt: string; +} + +/** sh.tangled.feed.comment — the current unified comment model. */ +export interface CommentRecord { + $type: 'sh.tangled.feed.comment'; + subject: string; + body: { original: string }; + createdAt: string; +} + +/** Item shape from sh.tangled.repo.listPulls (aggregated fields alongside the record). */ +export interface PullListItem extends RecordEnvelope { + state: PullState; + commentCount: number; +} + +export type IssueListItem = RecordEnvelope; +export type CommentListItem = RecordEnvelope; +export type RepoListItem = RecordEnvelope; + +export interface Coverage { + ready: boolean; + eventsProcessed: number; + lastCursor: number; +} diff --git a/packages/core/test/assembly.test.ts b/packages/core/test/assembly.test.ts new file mode 100644 index 0000000..7386bf4 --- /dev/null +++ b/packages/core/test/assembly.test.ts @@ -0,0 +1,106 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { listProposals, getProposal } from '../src/assembly.ts'; +import type { AssemblyDeps } from '../src/assembly.ts'; + +const tree = JSON.parse(readFileSync(fileURLToPath(new URL('./fixtures/tree.json', import.meta.url)), 'utf8')); + +// A pull that introduces 0007-caching.md (open) and one that introduced 0002 (merged). +const pulls = [ + { + uri: 'at://did:plc:a/sh.tangled.repo.pull/open7', + cid: 'c1', + state: 'open', + commentCount: 1, + value: { + $type: 'sh.tangled.repo.pull', title: 'caching', + target: { repo: 'did:plc:repo', branch: 'main' }, createdAt: '2026-06-01T00:00:00Z', + rounds: [{ createdAt: '2026-06-01T00:00:00Z', patchBlob: { ref: { $link: 'cid7' } } }], + }, + }, + { + uri: 'at://did:plc:b/sh.tangled.repo.pull/merged2', + cid: 'c2', + state: 'merged', + commentCount: 0, + value: { + $type: 'sh.tangled.repo.pull', title: 'governance', + target: { repo: 'did:plc:repo', branch: 'main' }, createdAt: '2026-05-01T00:00:00Z', + rounds: [{ createdAt: '2026-05-01T00:00:00Z', patchBlob: { ref: { $link: 'cid2' } } }], + }, + }, +]; + +// Map each pull URI to the .md paths it touches (bypasses real patch fetching in these tests). +const pathsByPull: Record = { + 'at://did:plc:a/sh.tangled.repo.pull/open7': ['0007-caching.md'], + 'at://did:plc:b/sh.tangled.repo.pull/merged2': ['0002-governance.md'], +}; + +function deps(overrides: Partial = {}): AssemblyDeps { + return { + repoUri: 'at://did:plc:owner/sh.tangled.repo/rfd', + repoDid: 'did:plc:repo', + git: { + getDefaultBranch: vi.fn().mockResolvedValue({ name: 'main', hash: '', when: '' }), + listTree: vi.fn().mockResolvedValue(tree), + getBlob: vi.fn().mockResolvedValue(null), + }, + reads: { + listPulls: vi.fn().mockResolvedValue({ items: pulls, cursor: null }), + getDiscussion: vi.fn().mockResolvedValue({ items: [], cursor: null }), + }, + pullMarkdownPaths: vi.fn(async (uri: string) => pathsByPull[uri] ?? []), + ...overrides, + } as AssemblyDeps; +} + +test('listProposals merges committed tree files with in-discussion pulls', async () => { + const out = await listProposals(deps()); + const bySlug = Object.fromEntries(out.map((p) => [p.slug, p.status])); + // committed on the default branch (no open pull touching them) + expect(bySlug['0001-charter']).toBe('committed'); + // 0002 is on the default branch AND has a merged pull -> published + expect(bySlug['0002-governance']).toBe('published'); + // 0007 exists only in an open pull -> discussion + expect(bySlug['0007-caching']).toBe('discussion'); + // README.md is not a proposal file + expect(bySlug['README']).toBeUndefined(); + // sorted by slug + expect(out.map((p) => p.slug)).toEqual(['0001-charter', '0002-governance', '0007-caching']); +}); + +test('getProposal returns committed content from the default branch + derived status', async () => { + const d = deps({ + git: { + getDefaultBranch: vi.fn().mockResolvedValue({ name: 'main', hash: '', when: '' }), + listTree: vi.fn().mockResolvedValue(tree), + getBlob: vi.fn(async (_ref: string, path: string) => + path === '0002-governance.md' ? '# Governance\n' : null), + } as never, + }); + const detail = await getProposal(d, '0002-governance'); + expect(detail).not.toBeNull(); + expect(detail!.content).toEqual({ source: 'default', text: '# Governance\n' }); + expect(detail!.status).toBe('published'); + expect(detail!.pulls.map((p) => p.uri)).toContain('at://did:plc:b/sh.tangled.repo.pull/merged2'); +}); + +test('getProposal returns null for an unknown slug with no pulls', async () => { + expect(await getProposal(deps(), '9999-nope')).toBeNull(); +}); + +test('getProposal collects discussion comments for the proposal pulls', async () => { + const getDiscussion = vi.fn().mockResolvedValue({ + items: [ + { uri: 'at://did:plc:c/sh.tangled.feed.comment/1', cid: 'x', value: { $type: 'sh.tangled.feed.comment', subject: 'at://did:plc:a/sh.tangled.repo.pull/open7', body: { original: 'nice' }, createdAt: '2026-06-02T00:00:00Z' } }, + ], + cursor: null, + }); + const d = deps({ reads: { listPulls: vi.fn().mockResolvedValue({ items: pulls, cursor: null }), getDiscussion } as never }); + const detail = await getProposal(d, '0007-caching'); + expect(detail!.discussion).toHaveLength(1); + expect(detail!.discussion[0]).toMatchObject({ body: 'nice', authorDid: 'did:plc:c', source: 'pull' }); + expect(getDiscussion).toHaveBeenCalledWith('at://did:plc:a/sh.tangled.repo.pull/open7'); +}); diff --git a/packages/core/test/at-uri.test.ts b/packages/core/test/at-uri.test.ts new file mode 100644 index 0000000..e895ca8 --- /dev/null +++ b/packages/core/test/at-uri.test.ts @@ -0,0 +1,19 @@ +import { expect, test } from 'vitest'; +import { parseAtUri } from '../src/at-uri.ts'; + +test('parses a well-formed at-uri', () => { + expect(parseAtUri('at://did:plc:abc/sh.tangled.repo.pull/3lz')).toEqual({ + did: 'did:plc:abc', + collection: 'sh.tangled.repo.pull', + rkey: '3lz', + }); +}); + +test('supports multi-segment rkeys', () => { + expect(parseAtUri('at://did:plc:abc/coll/a/b')?.rkey).toBe('a/b'); +}); + +test('returns null for non-at-uris and short uris', () => { + expect(parseAtUri('https://example.com')).toBeNull(); + expect(parseAtUri('at://did:plc:abc')).toBeNull(); +}); diff --git a/packages/core/test/bobbin.test.ts b/packages/core/test/bobbin.test.ts new file mode 100644 index 0000000..82ff3f2 --- /dev/null +++ b/packages/core/test/bobbin.test.ts @@ -0,0 +1,107 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test } from 'vitest'; +import { createBobbinPool } from '../src/bobbin.ts'; + +const coverage = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/getCoverage.json', import.meta.url)), 'utf8'), +); +const repo = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/getRepo.json', import.meta.url)), 'utf8'), +); + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' }, + }); +} + +/** Build a fetch stub keyed by "|". */ +function stubFetch(routes: Record Promise | Response>) { + const calls: string[] = []; + const fetchImpl = async (input: string | URL): Promise => { + const url = new URL(String(input)); + const nsid = url.pathname.replace('/xrpc/', ''); + const key = `${url.origin}|${nsid}`; + calls.push(key); + const handler = routes[key]; + if (!handler) throw new TypeError(`no route for ${key}`); + return handler(); + }; + return { fetchImpl, calls }; +} + +test('returns data from the primary without health-checking it', async () => { + const { fetchImpl, calls } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse(repo), + }); + const pool = createBobbinPool({ urls: ['https://a.test'], fetchImpl }); + const out = await pool.get('sh.tangled.repo.getRepo', { repo: 'at://x' }); + expect(out).toEqual(repo); + // Primary is used directly — no coverage probe. + expect(calls).toEqual(['https://a.test|sh.tangled.repo.getRepo']); +}); + +test('fails over to a healthy secondary when the primary errors', async () => { + const { fetchImpl, calls } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse({ error: 'boom' }, 500), + 'https://b.test|sh.tangled.bobbin.getCoverage': () => jsonResponse(coverage), + 'https://b.test|sh.tangled.repo.getRepo': () => jsonResponse(repo), + }); + const pool = createBobbinPool({ urls: ['https://a.test', 'https://b.test'], fetchImpl }); + const out = await pool.get('sh.tangled.repo.getRepo', { repo: 'at://x' }); + expect(out).toEqual(repo); + // Secondary was health-gated before use. + expect(calls).toContain('https://b.test|sh.tangled.bobbin.getCoverage'); +}); + +test('skips a secondary that reports not-ready', async () => { + const { fetchImpl } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse({ error: 'boom' }, 500), + 'https://b.test|sh.tangled.bobbin.getCoverage': () => jsonResponse({ ready: false }), + 'https://c.test|sh.tangled.bobbin.getCoverage': () => jsonResponse(coverage), + 'https://c.test|sh.tangled.repo.getRepo': () => jsonResponse(repo), + }); + const pool = createBobbinPool({ + urls: ['https://a.test', 'https://b.test', 'https://c.test'], + fetchImpl, + }); + expect(await pool.get('sh.tangled.repo.getRepo', { repo: 'at://x' })).toEqual(repo); +}); + +test('throws when every instance is exhausted', async () => { + const { fetchImpl } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse({ error: 'boom' }, 500), + 'https://b.test|sh.tangled.bobbin.getCoverage': () => jsonResponse({ ready: false }), + }); + const pool = createBobbinPool({ urls: ['https://a.test', 'https://b.test'], fetchImpl }); + await expect(pool.get('sh.tangled.repo.getRepo', { repo: 'at://x' })).rejects.toThrow( + /all bobbin instances failed/i, + ); +}); + +test('makes the last successful instance sticky', async () => { + const { fetchImpl, calls } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse({ error: 'boom' }, 500), + 'https://b.test|sh.tangled.bobbin.getCoverage': () => jsonResponse(coverage), + 'https://b.test|sh.tangled.repo.getRepo': () => jsonResponse(repo), + }); + const pool = createBobbinPool({ urls: ['https://a.test', 'https://b.test'], fetchImpl }); + await pool.get('sh.tangled.repo.getRepo', {}); // fails over to b, b becomes sticky + calls.length = 0; + await pool.get('sh.tangled.repo.getRepo', {}); // should start at b now + expect(calls[0]).toBe('https://b.test|sh.tangled.repo.getRepo'); +}); + +test('surfaces a 4xx from the primary instead of failing over', async () => { + const { fetchImpl, calls } = stubFetch({ + 'https://a.test|sh.tangled.repo.getRepo': () => jsonResponse({ error: 'bad request' }, 400), + 'https://b.test|sh.tangled.bobbin.getCoverage': () => jsonResponse(coverage), + 'https://b.test|sh.tangled.repo.getRepo': () => jsonResponse(repo), + }); + const pool = createBobbinPool({ urls: ['https://a.test', 'https://b.test'], fetchImpl }); + await expect(pool.get('sh.tangled.repo.getRepo', { repo: 'at://x' })).rejects.toThrow(/-> 400/); + // A 4xx is a request error, so the pool must NOT fail over to b. + expect(calls).not.toContain('https://b.test|sh.tangled.repo.getRepo'); +}); diff --git a/packages/core/test/config.test.ts b/packages/core/test/config.test.ts new file mode 100644 index 0000000..b900970 --- /dev/null +++ b/packages/core/test/config.test.ts @@ -0,0 +1,34 @@ +import { expect, test } from 'vitest'; +import { parseConfig } from '../src/config.ts'; + +test('applies defaults with only RFD_OWNER set', () => { + const cfg = parseConfig({ RFD_OWNER: 'natemoo.re' }); + expect(cfg).toEqual({ + owner: 'natemoo.re', + repoName: 'rfd', + bobbinUrls: ['https://api.tangled.org'], + cacheTtlSeconds: 60, + }); +}); + +test('parses a comma-separated, preference-ordered bobbin pool', () => { + const cfg = parseConfig({ + RFD_OWNER: 'did:plc:abc', + BOBBIN_URL: 'https://a.example , https://b.example', + }); + expect(cfg.bobbinUrls).toEqual(['https://a.example', 'https://b.example']); +}); + +test('coerces RFD_CACHE_TTL and RFD_REPO_NAME', () => { + const cfg = parseConfig({ RFD_OWNER: 'x', RFD_REPO_NAME: 'rfc', RFD_CACHE_TTL: '15' }); + expect(cfg.repoName).toBe('rfc'); + expect(cfg.cacheTtlSeconds).toBe(15); +}); + +test('throws when RFD_OWNER is missing', () => { + expect(() => parseConfig({})).toThrow(/RFD_OWNER/); +}); + +test('throws on a non-numeric RFD_CACHE_TTL', () => { + expect(() => parseConfig({ RFD_OWNER: 'x', RFD_CACHE_TTL: 'soon' })).toThrow(/RFD_CACHE_TTL/); +}); diff --git a/packages/core/test/factory-assembly.test.ts b/packages/core/test/factory-assembly.test.ts new file mode 100644 index 0000000..5e7be2c --- /dev/null +++ b/packages/core/test/factory-assembly.test.ts @@ -0,0 +1,22 @@ +import { expect, test, vi } from 'vitest'; +import { createRfd } from '../src/index.ts'; + +const repos = { items: [{ uri: 'at://did:plc:owner/sh.tangled.repo/rfd', value: { name: 'rfd', knot: 'knot1', repoDid: 'did:plc:repo' } }], cursor: null }; + +test('createRfd exposes listProposals scoped to the resolved repo', async () => { + const get = vi.fn(async (method: string, params?: Record) => { + if (method === 'sh.tangled.repo.listRepos') return repos; + if (method === 'sh.tangled.repo.getDefaultBranch') return { name: 'main', hash: '', when: '' }; + if (method === 'sh.tangled.repo.tree') return { ref: 'main', files: [{ name: '0001-charter.md', mode: '0100644', size: 1 }] }; + if (method === 'sh.tangled.repo.listPulls') return { items: [], cursor: null }; + throw new Error(`unexpected ${method} ${JSON.stringify(params)}`); + }); + const identity = { resolveDid: vi.fn().mockResolvedValue('did:plc:owner'), resolvePds: vi.fn() }; + const rfd = createRfd({ + config: { owner: 'natemoo.re', repoName: 'rfd', bobbinUrls: ['https://a.test'], cacheTtlSeconds: 60 }, + pool: { get } as never, + identity, + }); + const proposals = await rfd.listProposals(); + expect(proposals).toEqual([{ slug: '0001-charter', status: 'committed' }]); +}); diff --git a/packages/core/test/fixtures/blob.json b/packages/core/test/fixtures/blob.json new file mode 100644 index 0000000..3147c0e --- /dev/null +++ b/packages/core/test/fixtures/blob.json @@ -0,0 +1 @@ +{ "content": "# Charter\n\nThe founding proposal.\n", "encoding": "utf-8", "size": 30 } diff --git a/packages/core/test/fixtures/getCoverage.json b/packages/core/test/fixtures/getCoverage.json new file mode 100644 index 0000000..d49fc65 --- /dev/null +++ b/packages/core/test/fixtures/getCoverage.json @@ -0,0 +1 @@ +{ "ready": true, "eventsProcessed": 135389, "lastCursor": 158872 } diff --git a/packages/core/test/fixtures/getRepo.json b/packages/core/test/fixtures/getRepo.json new file mode 100644 index 0000000..97e2fd1 --- /dev/null +++ b/packages/core/test/fixtures/getRepo.json @@ -0,0 +1,12 @@ +{ + "cid": "bafyreidehocneckziff4uffajjqyhqgwxxze364qhcaxtfvv46t4avdqku", + "uri": "at://did:plc:wshs7t2adsemcrrd4snkeqli/sh.tangled.repo/core", + "value": { + "$type": "sh.tangled.repo", + "createdAt": "2025-02-23T18:43:18Z", + "description": "Monorepo for Tangled", + "knot": "knot1.tangled.sh", + "name": "core", + "repoDid": "did:plc:j5hmlfdrwkvtxm7cjmu7j2is" + } +} diff --git a/packages/core/test/fixtures/listComments.json b/packages/core/test/fixtures/listComments.json new file mode 100644 index 0000000..7894f29 --- /dev/null +++ b/packages/core/test/fixtures/listComments.json @@ -0,0 +1,15 @@ +{ + "items": [ + { + "uri": "at://did:plc:qfpnj4og54vl56wngdriaxug/sh.tangled.feed.comment/3mrp4r3uhpa22", + "cid": "bafyreiabuj5zezrksmkt5vhhrntpzy6crgwiggtnni2wchn6zyw6ovueju", + "value": { + "$type": "sh.tangled.feed.comment", + "subject": "at://did:plc:kic7mqihegzbj2ojesltkvho/sh.tangled.repo.pull/3mrn7dysfp522", + "body": { "original": "yes that is correct!" }, + "createdAt": "2026-06-01T11:00:00Z" + } + } + ], + "cursor": null +} diff --git a/packages/core/test/fixtures/listPulls.json b/packages/core/test/fixtures/listPulls.json new file mode 100644 index 0000000..1f89723 --- /dev/null +++ b/packages/core/test/fixtures/listPulls.json @@ -0,0 +1,36 @@ +{ + "items": [ + { + "uri": "at://did:plc:kic7mqihegzbj2ojesltkvho/sh.tangled.repo.pull/3mrn7dysfp522", + "cid": "bafyreici556u3cnkdqcim4wsydvjnrwvzavrdr4qt4achgtkgn5g3eim34", + "state": "open", + "commentCount": 2, + "value": { + "$type": "sh.tangled.repo.pull", + "title": "improve repo index performance", + "body": "exploratory work", + "createdAt": "2026-06-01T10:00:00Z", + "target": { "repo": "did:plc:j5hmlfdrwkvtxm7cjmu7j2is", "branch": "master" }, + "rounds": [ + { "createdAt": "2026-06-01T10:00:00Z", "patchBlob": { "ref": { "$link": "bafypatch1" } } } + ] + } + }, + { + "uri": "at://did:plc:kic7mqihegzbj2ojesltkvho/sh.tangled.repo.pull/3mrn7dysfp600", + "cid": "bafyreicid600", + "state": "merged", + "commentCount": 0, + "value": { + "$type": "sh.tangled.repo.pull", + "title": "0002 add governance doc", + "createdAt": "2026-05-01T10:00:00Z", + "target": { "repo": "did:plc:j5hmlfdrwkvtxm7cjmu7j2is", "branch": "master" }, + "rounds": [ + { "createdAt": "2026-05-01T10:00:00Z", "patchBlob": { "ref": { "$link": "bafypatch2" } } } + ] + } + } + ], + "cursor": null +} diff --git a/packages/core/test/fixtures/patch.diff b/packages/core/test/fixtures/patch.diff new file mode 100644 index 0000000..0a25e1b --- /dev/null +++ b/packages/core/test/fixtures/patch.diff @@ -0,0 +1,9 @@ +diff --git a/0007-caching.md b/0007-caching.md +new file mode 100644 +index 0000000..1111111 +--- /dev/null ++++ b/0007-caching.md +@@ -0,0 +1,3 @@ ++# Caching ++ ++Add a read-through cache. diff --git a/packages/core/test/fixtures/tree.json b/packages/core/test/fixtures/tree.json new file mode 100644 index 0000000..cd73297 --- /dev/null +++ b/packages/core/test/fixtures/tree.json @@ -0,0 +1,8 @@ +{ + "ref": "main", + "files": [ + { "name": "0001-charter.md", "mode": "0100644", "size": 1200 }, + { "name": "0002-governance.md", "mode": "0100644", "size": 800 }, + { "name": "README.md", "mode": "0100644", "size": 300 } + ] +} diff --git a/packages/core/test/git.test.ts b/packages/core/test/git.test.ts new file mode 100644 index 0000000..d5cb2dc --- /dev/null +++ b/packages/core/test/git.test.ts @@ -0,0 +1,58 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { createGit } from '../src/git.ts'; +import { XrpcRequestError } from '../src/bobbin.ts'; + +const tree = JSON.parse(readFileSync(fileURLToPath(new URL('./fixtures/tree.json', import.meta.url)), 'utf8')); +const blob = JSON.parse(readFileSync(fileURLToPath(new URL('./fixtures/blob.json', import.meta.url)), 'utf8')); +const REPO = 'at://did:plc:owner/sh.tangled.repo/rfd'; + +test('getDefaultBranch passes the repo AT-URI', async () => { + const get = vi.fn().mockResolvedValue({ name: 'main', hash: 'abc', when: '2026-01-01T00:00:00Z' }); + const git = createGit({ get }, REPO); + expect((await git.getDefaultBranch()).name).toBe('main'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.getDefaultBranch', { repo: REPO }); +}); + +test('listTree passes repo + ref', async () => { + const get = vi.fn().mockResolvedValue(tree); + const git = createGit({ get }, REPO); + const out = await git.listTree('main'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.tree', { repo: REPO, ref: 'main' }); + expect(out.files).toHaveLength(3); +}); + +test('getBlob returns decoded utf-8 content', async () => { + const get = vi.fn().mockResolvedValue(blob); + const git = createGit({ get }, REPO); + expect(await git.getBlob('main', '0001-charter.md')).toBe('# Charter\n\nThe founding proposal.\n'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.blob', { repo: REPO, ref: 'main', path: '0001-charter.md' }); +}); + +test('getBlob decodes base64 content', async () => { + const get = vi.fn().mockResolvedValue({ content: btoa('hello'), encoding: 'base64', size: 5 }); + const git = createGit({ get }, REPO); + expect(await git.getBlob('main', 'x.md')).toBe('hello'); +}); + +test('getBlob decodes base64 as UTF-8 (not Latin-1)', async () => { + // A proposal with an em-dash + accented text — must not mojibake. + const text = 'café — résumé'; + const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(text))); + const get = vi.fn().mockResolvedValue({ content: b64, encoding: 'base64', size: b64.length }); + expect(await createGit({ get }, REPO).getBlob('main', 'x.md')).toBe(text); +}); + +test('getBlob returns null for a missing path (4xx), rethrows other errors', async () => { + const missing = vi.fn().mockRejectedValue(new XrpcRequestError(404, 'not found')); + expect(await createGit({ get: missing }, REPO).getBlob('main', 'nope.md')).toBeNull(); + + const boom = vi.fn().mockRejectedValue(new Error('all bobbin instances failed')); + await expect(createGit({ get: boom }, REPO).getBlob('main', 'x.md')).rejects.toThrow(/all bobbin/); +}); + +test('getBlob returns null for binary blobs', async () => { + const get = vi.fn().mockResolvedValue({ content: 'AAAA', encoding: 'base64', size: 3, isBinary: true }); + expect(await createGit({ get }, REPO).getBlob('main', 'logo.png')).toBeNull(); +}); diff --git a/packages/core/test/identity.test.ts b/packages/core/test/identity.test.ts new file mode 100644 index 0000000..fdaeaf4 --- /dev/null +++ b/packages/core/test/identity.test.ts @@ -0,0 +1,9 @@ +import { expect, test, vi } from 'vitest'; +import { createIdentityFrom } from '../src/identity.ts'; + +test('resolvePds returns the PDS from the resolver', async () => { + const resolver = { resolve: vi.fn().mockResolvedValue({ did: 'did:plc:x', handle: 'a.b', pds: 'https://pds.example' }) }; + const identity = createIdentityFrom(resolver as never); + expect(await identity.resolvePds('did:plc:x')).toBe('https://pds.example'); + expect(await identity.resolveDid('a.b')).toBe('did:plc:x'); +}); diff --git a/packages/core/test/index.test.ts b/packages/core/test/index.test.ts new file mode 100644 index 0000000..25adc0c --- /dev/null +++ b/packages/core/test/index.test.ts @@ -0,0 +1,40 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { createRfd } from '../src/index.ts'; + +const repos = { + items: [ + { uri: 'at://did:plc:owner/sh.tangled.repo/rfd', value: { name: 'rfd', knot: 'knot1', repoDid: 'did:plc:repo' } }, + ], + cursor: null, +}; +const listPulls = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/listPulls.json', import.meta.url)), 'utf8'), +); + +test('createRfd resolves once, then scopes listPulls by repoDid', async () => { + const get = vi.fn(async (method: string) => { + if (method === 'sh.tangled.repo.listRepos') return repos; + if (method === 'sh.tangled.repo.listPulls') return listPulls; + throw new Error(`unexpected ${method}`); + }); + const identity = { resolveDid: vi.fn().mockResolvedValue('did:plc:owner'), resolvePds: vi.fn() }; + const rfd = createRfd({ + config: { owner: 'natemoo.re', repoName: 'rfd', bobbinUrls: ['https://a.test'], cacheTtlSeconds: 60 }, + pool: { get }, + identity, + }); + + const a = await rfd.listPulls(); + const b = await rfd.listPulls(); + expect(a.items[0].state).toBe('open'); + // Resolution happened exactly once across both calls. + expect(get.mock.calls.filter(([m]) => m === 'sh.tangled.repo.listRepos')).toHaveLength(1); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.listPulls', { + subject: 'did:plc:repo', + limit: 100, + cursor: undefined, + }); + expect(b.items).toHaveLength(2); +}); diff --git a/packages/core/test/patch-fetch.test.ts b/packages/core/test/patch-fetch.test.ts new file mode 100644 index 0000000..d42c0d7 --- /dev/null +++ b/packages/core/test/patch-fetch.test.ts @@ -0,0 +1,58 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { latestPatchCid, fetchPatchText, pullMarkdownPaths } from '../src/patch-fetch.ts'; +import type { PullRecord } from '../src/types.ts'; + +const diff = readFileSync(fileURLToPath(new URL('./fixtures/patch.diff', import.meta.url)), 'utf8'); + +function gzip(text: string): Promise { + const encoded = new TextEncoder().encode(text); + const stream = new Response(encoded).body!.pipeThrough(new CompressionStream('gzip')); + return new Response(stream).arrayBuffer().then((b) => new Uint8Array(b)); +} + +const pull: PullRecord = { + $type: 'sh.tangled.repo.pull', + title: 'add caching', + target: { repo: 'did:plc:repo', branch: 'main' }, + createdAt: '2026-06-01T00:00:00Z', + rounds: [ + { createdAt: '2026-06-01T00:00:00Z', patchBlob: { ref: { $link: 'bafyOLD' } } }, + { createdAt: '2026-06-02T00:00:00Z', patchBlob: { ref: { $link: 'bafyNEW' } } }, + ], +}; + +test('latestPatchCid returns the last round patch cid', () => { + expect(latestPatchCid(pull)).toBe('bafyNEW'); + expect(latestPatchCid({ ...pull, rounds: [] })).toBeNull(); +}); + +test('fetchPatchText gunzips a getBlob response from the author PDS', async () => { + const gz = await gzip(diff); + const fetchImpl = vi.fn(async (input: string | URL) => { + const url = new URL(String(input)); + expect(url.pathname).toBe('/xrpc/com.atproto.sync.getBlob'); + expect(url.searchParams.get('did')).toBe('did:plc:author'); + expect(url.searchParams.get('cid')).toBe('bafyNEW'); + return new Response(gz as any, { status: 200 }); + }); + const text = await fetchPatchText('https://pds.example', 'did:plc:author', 'bafyNEW', fetchImpl as never); + expect(text).toContain('0007-caching.md'); +}); + +test('fetchPatchText returns null on a non-ok response', async () => { + const fetchImpl = vi.fn(async () => new Response('nope', { status: 404 })); + expect(await fetchPatchText('https://pds.example', 'did:plc:author', 'x', fetchImpl as never)).toBeNull(); +}); + +test('pullMarkdownPaths returns the .md paths the latest patch touches', async () => { + const gz = await gzip(diff); + const deps = { + resolvePds: vi.fn().mockResolvedValue('https://pds.example'), + fetchImpl: vi.fn(async () => new Response(gz as any, { status: 200 })), + }; + const paths = await pullMarkdownPaths('at://did:plc:author/sh.tangled.repo.pull/1', pull, deps as never); + expect(paths).toEqual(['0007-caching.md']); + expect(deps.resolvePds).toHaveBeenCalledWith('did:plc:author'); +}); diff --git a/packages/www/test/patch.test.ts b/packages/core/test/patch.test.ts similarity index 90% rename from packages/www/test/patch.test.ts rename to packages/core/test/patch.test.ts index 8043ccc..2345c32 100644 --- a/packages/www/test/patch.test.ts +++ b/packages/core/test/patch.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from 'vitest'; -import { extractMarkdownFromDiff, gunzipToString, listMarkdownFilesInDiff } from '../src/lib/patch.ts'; +import { + extractMarkdownFileFromDiff, + extractMarkdownFromDiff, + listMarkdownFilesInDiff, +} from '../src/patch.ts'; const ADD_MD_PATCH = `From abc123 Mon Sep 17 00:00:00 2001 From: Jane Doe @@ -196,15 +200,3 @@ index 1234567..0000000 expect(entries[0]!.content).toBe(''); }); }); - -describe('gunzipToString', () => { - it('round-trips a gzipped string', async () => { - const text = '# hello\nworld'; - const encoded = new TextEncoder().encode(text); - const compressed = await new Response( - new Response(encoded).body!.pipeThrough(new CompressionStream('gzip')), - ).arrayBuffer(); - const out = await gunzipToString(new Uint8Array(compressed)); - expect(out).toBe(text); - }); -}); diff --git a/packages/core/test/proposal.test.ts b/packages/core/test/proposal.test.ts new file mode 100644 index 0000000..7bf7919 --- /dev/null +++ b/packages/core/test/proposal.test.ts @@ -0,0 +1,34 @@ +import { expect, test } from 'vitest'; +import { deriveStatus, fileNameToSlug, isProposalFile } from '../src/proposal.ts'; + +test('recognises numbered proposal filenames', () => { + expect(isProposalFile('0001.md')).toBe(true); + expect(isProposalFile('0002-governance.md')).toBe(true); + expect(isProposalFile('README.md')).toBe(false); + expect(isProposalFile('0001.txt')).toBe(false); +}); + +test('derives slug from filename', () => { + expect(fileNameToSlug('0002-governance.md')).toBe('0002-governance'); + expect(fileNameToSlug('notes.txt')).toBeNull(); +}); + +test('an open pull means discussion', () => { + expect(deriveStatus({ onDefaultBranch: false, pulls: [{ state: 'open' }] })).toBe('discussion'); +}); + +test('default branch + a merged pull means published', () => { + expect(deriveStatus({ onDefaultBranch: true, pulls: [{ state: 'merged' }] })).toBe('published'); +}); + +test('default branch with no relevant merged pull means committed', () => { + expect(deriveStatus({ onDefaultBranch: true, pulls: [] })).toBe('committed'); +}); + +test('all pulls closed off the default branch means abandoned', () => { + expect(deriveStatus({ onDefaultBranch: false, pulls: [{ state: 'closed' }] })).toBe('abandoned'); +}); + +test('nothing known means unknown', () => { + expect(deriveStatus({ onDefaultBranch: false, pulls: [] })).toBe('unknown'); +}); diff --git a/packages/core/test/reads.test.ts b/packages/core/test/reads.test.ts new file mode 100644 index 0000000..35570f0 --- /dev/null +++ b/packages/core/test/reads.test.ts @@ -0,0 +1,45 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { createReads } from '../src/reads.ts'; + +const listPulls = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/listPulls.json', import.meta.url)), 'utf8'), +); +const listComments = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/listComments.json', import.meta.url)), 'utf8'), +); + +test('listPulls passes repoDid as subject and returns typed items', async () => { + const get = vi.fn().mockResolvedValue(listPulls); + const reads = createReads({ get }); + const out = await reads.listPulls('did:plc:repo'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.listPulls', { + subject: 'did:plc:repo', + limit: 100, + cursor: undefined, + }); + expect(out.items[0].state).toBe('open'); + expect(out.items[0].commentCount).toBe(2); +}); + +test('getDiscussion lists feed comments by subject uri', async () => { + const get = vi.fn().mockResolvedValue(listComments); + const reads = createReads({ get }); + const out = await reads.getDiscussion('at://did:plc:x/sh.tangled.repo.pull/1'); + expect(get).toHaveBeenCalledWith('sh.tangled.feed.listComments', { + subject: 'at://did:plc:x/sh.tangled.repo.pull/1', + limit: 100, + cursor: undefined, + }); + expect(out.items[0].value.body.original).toBe('yes that is correct!'); +}); + +test('getPull fetches a single record by uri', async () => { + const get = vi.fn().mockResolvedValue(listPulls.items[0]); + const reads = createReads({ get }); + await reads.getPull('at://did:plc:x/sh.tangled.repo.pull/1'); + expect(get).toHaveBeenCalledWith('sh.tangled.repo.getPull', { + pull: 'at://did:plc:x/sh.tangled.repo.pull/1', + }); +}); diff --git a/packages/core/test/resolve.test.ts b/packages/core/test/resolve.test.ts new file mode 100644 index 0000000..759afab --- /dev/null +++ b/packages/core/test/resolve.test.ts @@ -0,0 +1,50 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { expect, test, vi } from 'vitest'; +import { NoRfdRepoError, resolveRepoContext } from '../src/resolve.ts'; + +const repo = JSON.parse( + readFileSync(fileURLToPath(new URL('./fixtures/getRepo.json', import.meta.url)), 'utf8'), +); + +function readsStub(repos: unknown[]) { + return { + listRepos: vi.fn().mockResolvedValue({ items: repos, cursor: null }), + } as any; +} + +test('resolves a handle to did, then finds the named repo', async () => { + const identity = { resolveDid: vi.fn().mockResolvedValue('did:plc:owner'), resolvePds: vi.fn() }; + const reads = readsStub([ + { uri: 'at://did:plc:owner/sh.tangled.repo/other', value: { name: 'other', knot: 'k', repoDid: 'did:plc:x' } }, + { uri: 'at://did:plc:owner/sh.tangled.repo/rfd', value: { name: 'rfd', knot: 'knot1', repoDid: 'did:plc:repo' } }, + ]); + const ctx = await resolveRepoContext({ reads, identity, owner: 'natemoo.re', repoName: 'rfd' }); + expect(identity.resolveDid).toHaveBeenCalledWith('natemoo.re'); + expect(reads.listRepos).toHaveBeenCalledWith('did:plc:owner', undefined); + expect(ctx).toEqual({ + ownerDid: 'did:plc:owner', + repoUri: 'at://did:plc:owner/sh.tangled.repo/rfd', + repoDid: 'did:plc:repo', + knot: 'knot1', + name: 'rfd', + }); +}); + +test('accepts a DID owner without identity resolution', async () => { + const identity = { resolveDid: vi.fn(), resolvePds: vi.fn() }; + const reads = readsStub([repo]); // fixture name is "core" + const ctx = await resolveRepoContext({ reads, identity, owner: 'did:plc:wshs7t2adsemcrrd4snkeqli', repoName: 'core' }); + expect(identity.resolveDid).not.toHaveBeenCalled(); + expect(ctx.repoDid).toBe('did:plc:j5hmlfdrwkvtxm7cjmu7j2is'); +}); + +test('throws NoRfdRepoError when no repo matches the name', async () => { + const identity = { resolveDid: vi.fn().mockResolvedValue('did:plc:owner'), resolvePds: vi.fn() }; + const reads = readsStub([ + { uri: 'at://x', value: { name: 'notrfd', knot: 'k', repoDid: 'did:plc:x' } }, + ]); + await expect( + resolveRepoContext({ reads, identity, owner: 'x', repoName: 'rfd' }), + ).rejects.toBeInstanceOf(NoRfdRepoError); +}); diff --git a/packages/core/test/smoke.test.ts b/packages/core/test/smoke.test.ts new file mode 100644 index 0000000..af0a93f --- /dev/null +++ b/packages/core/test/smoke.test.ts @@ -0,0 +1,6 @@ +import { expect, test } from 'vitest'; +import { RFD_CORE_VERSION } from '../src/index.ts'; + +test('package is importable', () => { + expect(RFD_CORE_VERSION).toBe('0.0.1'); +}); diff --git a/packages/core/test/types.test.ts b/packages/core/test/types.test.ts new file mode 100644 index 0000000..c7d6378 --- /dev/null +++ b/packages/core/test/types.test.ts @@ -0,0 +1,26 @@ +import { expectTypeOf, test } from 'vitest'; +import type { + CommentRecord, + PullListItem, + PullState, + RecordEnvelope, + RepoRecord, +} from '../src/types.ts'; + +test('PullListItem carries aggregated state + commentCount', () => { + expectTypeOf().toExtend<{ + uri: string; + state: PullState; + commentCount: number; + }>(); +}); + +test('RepoRecord exposes repoDid and knot', () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); +}); + +test('a comment envelope wraps a CommentRecord', () => { + expectTypeOf['value']['body']['original']>() + .toEqualTypeOf(); +}); diff --git a/packages/core/test/xrpc-error.test.ts b/packages/core/test/xrpc-error.test.ts new file mode 100644 index 0000000..de3c6b5 --- /dev/null +++ b/packages/core/test/xrpc-error.test.ts @@ -0,0 +1,9 @@ +import { expect, test } from 'vitest'; +import { XrpcRequestError } from '../src/bobbin.ts'; + +test('XrpcRequestError carries the HTTP status', () => { + const err = new XrpcRequestError(404, 'x -> 404 not found'); + expect(err).toBeInstanceOf(Error); + expect(err.status).toBe(404); + expect(err.name).toBe('XrpcRequestError'); +}); diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 0000000..9a8a30a --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + // "DOM" supplies types for the WHATWG globals we use on Node 24+ (fetch, + // Response, BodyInit, DecompressionStream, TextDecoder, AbortController) — + // it does NOT make this a browser library; there are no DOM runtime deps. + // "types": ["node"] covers node: imports (fs/url) used in tests. + "lib": ["ES2022", "DOM"], + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "noEmit": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "types": ["node"], + "strict": true, + "esModuleInterop": true, + "isolatedModules": true + }, + "include": ["src", "test"] +} diff --git a/packages/lexicon/lex.config.ts b/packages/lexicon/lex.config.ts deleted file mode 100644 index e5e121d..0000000 --- a/packages/lexicon/lex.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { defineLexiconConfig } from '@atcute/lex-cli'; - -export default defineLexiconConfig({ - generate: { - files: ['lexicons/**/*.json'], - outdir: 'src/lexicons/', - modules: { importSuffix: '.ts' }, - imports: ['@atcute/atproto'], - clean: true, - }, -}); diff --git a/packages/lexicon/lexicons/issue/comment.json b/packages/lexicon/lexicons/issue/comment.json deleted file mode 100644 index 1bccebb..0000000 --- a/packages/lexicon/lexicons/issue/comment.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.issue.comment", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "record", - "key": "tid", - "record": { - "type": "object", - "required": [ - "issue", - "body", - "createdAt" - ], - "properties": { - "issue": { - "type": "string", - "format": "at-uri" - }, - "body": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "datetime" - }, - "replyTo": { - "type": "string", - "format": "at-uri" - }, - "mentions": { - "type": "array", - "items": { - "type": "string", - "format": "did" - } - }, - "references": { - "type": "array", - "items": { - "type": "string", - "format": "at-uri" - } - } - } - } - } - } -} diff --git a/packages/lexicon/lexicons/issue/issue.json b/packages/lexicon/lexicons/issue/issue.json deleted file mode 100644 index d20ed79..0000000 --- a/packages/lexicon/lexicons/issue/issue.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.issue", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "record", - "key": "tid", - "record": { - "type": "object", - "required": ["title", "createdAt"], - "properties": { - "repo": { - "type": "string", - "format": "at-uri" - }, - "repoDid": { - "type": "string", - "format": "did" - }, - "title": { - "type": "string" - }, - "body": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "datetime" - }, - "mentions": { - "type": "array", - "items": { - "type": "string", - "format": "did" - } - }, - "references": { - "type": "array", - "items": { - "type": "string", - "format": "at-uri" - } - } - } - } - } - } -} diff --git a/packages/lexicon/lexicons/pulls/closed.json b/packages/lexicon/lexicons/pulls/closed.json deleted file mode 100644 index 5881581..0000000 --- a/packages/lexicon/lexicons/pulls/closed.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.pull.status.closed", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "token", - "description": "closed pull request" - } - } -} diff --git a/packages/lexicon/lexicons/pulls/comment.json b/packages/lexicon/lexicons/pulls/comment.json deleted file mode 100644 index c830443..0000000 --- a/packages/lexicon/lexicons/pulls/comment.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.pull.comment", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "record", - "key": "tid", - "record": { - "type": "object", - "required": [ - "pull", - "body", - "createdAt" - ], - "properties": { - "pull": { - "type": "string", - "format": "at-uri" - }, - "body": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "datetime" - }, - "mentions": { - "type": "array", - "items": { - "type": "string", - "format": "did" - } - }, - "references": { - "type": "array", - "items": { - "type": "string", - "format": "at-uri" - } - } - } - } - } - } -} diff --git a/packages/lexicon/lexicons/pulls/merged.json b/packages/lexicon/lexicons/pulls/merged.json deleted file mode 100644 index 87606a9..0000000 --- a/packages/lexicon/lexicons/pulls/merged.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.pull.status.merged", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "token", - "description": "merged pull request" - } - } -} diff --git a/packages/lexicon/lexicons/pulls/open.json b/packages/lexicon/lexicons/pulls/open.json deleted file mode 100644 index 9cf554e..0000000 --- a/packages/lexicon/lexicons/pulls/open.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.pull.status.open", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "token", - "description": "open pull request" - } - } -} diff --git a/packages/lexicon/lexicons/pulls/pull.json b/packages/lexicon/lexicons/pulls/pull.json deleted file mode 100644 index f1fa03e..0000000 --- a/packages/lexicon/lexicons/pulls/pull.json +++ /dev/null @@ -1,124 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.pull", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "record", - "key": "tid", - "record": { - "type": "object", - "required": [ - "target", - "title", - "createdAt", - "rounds" - ], - "properties": { - "title": { - "type": "string" - }, - "body": { - "type": "string" - }, - "rounds": { - "type": "array", - "items": { - "type": "ref", - "ref": "#round" - } - }, - "source": { - "type": "ref", - "ref": "#source" - }, - "target": { - "type": "ref", - "ref": "#target" - }, - "createdAt": { - "type": "string", - "format": "datetime" - }, - "mentions": { - "type": "array", - "items": { - "type": "string", - "format": "did" - } - }, - "references": { - "type": "array", - "items": { - "type": "string", - "format": "at-uri" - } - }, - "dependentOn": { - "type": "string", - "format": "at-uri" - } - } - } - }, - "target": { - "type": "object", - "required": [ - "branch" - ], - "properties": { - "repo": { - "type": "string", - "format": "at-uri" - }, - "repoDid": { - "type": "string", - "format": "did" - }, - "branch": { - "type": "string" - } - } - }, - "source": { - "type": "object", - "required": [ - "branch" - ], - "properties": { - "branch": { - "type": "string" - }, - "repo": { - "type": "string", - "format": "at-uri" - }, - "repoDid": { - "type": "string", - "format": "did" - } - } - }, - "round": { - "type": "object", - "required": [ - "patchBlob", - "createdAt" - ], - "description": "revisions of this pull request, newer rounds are appended to this array. appviews may reject records do not treat this field as append-only. the blob format is gzipped text-based git-format-patches.", - "properties": { - "createdAt": { - "type": "string", - "format": "datetime" - }, - "patchBlob": { - "type": "blob", - "accept": [ - "application/gzip" - ] - } - } - } - } -} diff --git a/packages/lexicon/lexicons/pulls/state.json b/packages/lexicon/lexicons/pulls/state.json deleted file mode 100644 index d33422f..0000000 --- a/packages/lexicon/lexicons/pulls/state.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.pull.status", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "record", - "key": "tid", - "record": { - "type": "object", - "required": [ - "pull", - "status" - ], - "properties": { - "pull": { - "type": "string", - "format": "at-uri" - }, - "status": { - "type": "string", - "description": "status of the pull request", - "knownValues": [ - "sh.tangled.repo.pull.status.open", - "sh.tangled.repo.pull.status.closed", - "sh.tangled.repo.pull.status.merged" - ], - "default": "sh.tangled.repo.pull.status.open" - } - } - } - } - } -} diff --git a/packages/lexicon/lexicons/repo/blob.json b/packages/lexicon/lexicons/repo/blob.json deleted file mode 100644 index 4a6012f..0000000 --- a/packages/lexicon/lexicons/repo/blob.json +++ /dev/null @@ -1,181 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.blob", - "defs": { - "main": { - "type": "query", - "parameters": { - "type": "params", - "required": [ - "repo", - "ref", - "path" - ], - "properties": { - "repo": { - "type": "string", - "description": "Repository identifier in format 'did:plc:.../repoName'" - }, - "ref": { - "type": "string", - "description": "Git reference (branch, tag, or commit SHA)" - }, - "path": { - "type": "string", - "description": "Path to the file within the repository" - }, - "raw": { - "type": "boolean", - "description": "Return raw file content instead of JSON response", - "default": false - } - } - }, - "output": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": [ - "ref", - "path" - ], - "properties": { - "ref": { - "type": "string", - "description": "The git reference used" - }, - "path": { - "type": "string", - "description": "The file path" - }, - "content": { - "type": "string", - "description": "File content (base64 encoded for binary files)" - }, - "encoding": { - "type": "string", - "description": "Content encoding", - "enum": [ - "utf-8", - "base64" - ] - }, - "size": { - "type": "integer", - "description": "File size in bytes" - }, - "isBinary": { - "type": "boolean", - "description": "Whether the file is binary" - }, - "mimeType": { - "type": "string", - "description": "MIME type of the file" - }, - "submodule": { - "type": "ref", - "ref": "#submodule", - "description": "Submodule information if path is a submodule" - }, - "lastCommit": { - "type": "ref", - "ref": "#lastCommit" - }, - "fileTooLarge": { - "type": "boolean" - } - } - } - }, - "errors": [ - { - "name": "RepoNotFound", - "description": "Repository not found or access denied" - }, - { - "name": "RefNotFound", - "description": "Git reference not found" - }, - { - "name": "FileNotFound", - "description": "File not found at the specified path" - }, - { - "name": "InvalidRequest", - "description": "Invalid request parameters" - } - ] - }, - "lastCommit": { - "type": "object", - "required": [ - "hash", - "message", - "when" - ], - "properties": { - "hash": { - "type": "string", - "description": "Commit hash" - }, - "message": { - "type": "string", - "description": "Commit message" - }, - "author": { - "type": "ref", - "ref": "#signature" - }, - "when": { - "type": "string", - "format": "datetime", - "description": "Commit timestamp" - } - } - }, - "signature": { - "type": "object", - "required": [ - "name", - "email", - "when" - ], - "properties": { - "name": { - "type": "string", - "description": "Author name" - }, - "email": { - "type": "string", - "description": "Author email" - }, - "when": { - "type": "string", - "format": "datetime", - "description": "Author timestamp" - } - } - }, - "submodule": { - "type": "object", - "required": [ - "name", - "url" - ], - "properties": { - "name": { - "type": "string", - "description": "Submodule name" - }, - "url": { - "type": "string", - "description": "Submodule repository URL" - }, - "branch": { - "type": "string", - "description": "Branch to track in the submodule" - } - } - } - } -} diff --git a/packages/lexicon/lexicons/repo/getDefaultBranch.json b/packages/lexicon/lexicons/repo/getDefaultBranch.json deleted file mode 100644 index 08d3231..0000000 --- a/packages/lexicon/lexicons/repo/getDefaultBranch.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.getDefaultBranch", - "defs": { - "main": { - "type": "query", - "parameters": { - "type": "params", - "required": ["repo"], - "properties": { - "repo": { - "type": "string", - "description": "Repository identifier in format 'did:plc:.../repoName'" - } - } - }, - "output": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["name", "hash", "when"], - "properties": { - "name": { - "type": "string", - "description": "Default branch name" - }, - "hash": { - "type": "string", - "description": "Latest commit hash on default branch" - }, - "shortHash": { - "type": "string", - "description": "Short commit hash" - }, - "when": { - "type": "string", - "format": "datetime", - "description": "Timestamp of latest commit" - }, - "message": { - "type": "string", - "description": "Latest commit message" - }, - "author": { - "type": "ref", - "ref": "#signature" - } - } - } - }, - "errors": [ - { - "name": "RepoNotFound", - "description": "Repository not found or access denied" - }, - { - "name": "InvalidRequest", - "description": "Invalid request parameters" - } - ] - }, - "signature": { - "type": "object", - "required": ["name", "email", "when"], - "properties": { - "name": { - "type": "string", - "description": "Author name" - }, - "email": { - "type": "string", - "description": "Author email" - }, - "when": { - "type": "string", - "format": "datetime", - "description": "Author timestamp" - } - } - } - } -} diff --git a/packages/lexicon/lexicons/repo/repo.json b/packages/lexicon/lexicons/repo/repo.json deleted file mode 100644 index f520ba4..0000000 --- a/packages/lexicon/lexicons/repo/repo.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "record", - "key": "tid", - "record": { - "type": "object", - "required": [ - "name", - "knot", - "createdAt" - ], - "properties": { - "name": { - "type": "string", - "description": "name of the repo" - }, - "knot": { - "type": "string", - "description": "knot where the repo was created" - }, - "spindle": { - "type": "string", - "description": "CI runner to send jobs to and receive results from" - }, - "description": { - "type": "string", - "minGraphemes": 1, - "maxGraphemes": 140 - }, - "website": { - "type": "string", - "format": "uri", - "description": "Any URI related to the repo" - }, - "topics": { - "type": "array", - "description": "Topics related to the repo", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 50 - }, - "maxLength": 50 - }, - "source": { - "type": "string", - "format": "uri", - "description": "source of the repo" - }, - "labels": { - "type": "array", - "description": "List of labels that this repo subscribes to", - "items": { - "type": "string", - "format": "at-uri" - } - }, - "repoDid": { - "type": "string", - "format": "did", - "description": "DID of the repo itself, if assigned" - }, - "createdAt": { - "type": "string", - "format": "datetime" - } - } - } - } - } -} diff --git a/packages/lexicon/lexicons/repo/tree.json b/packages/lexicon/lexicons/repo/tree.json deleted file mode 100644 index dee90dc..0000000 --- a/packages/lexicon/lexicons/repo/tree.json +++ /dev/null @@ -1,182 +0,0 @@ -{ - "lexicon": 1, - "id": "sh.tangled.repo.tree", - "defs": { - "main": { - "type": "query", - "parameters": { - "type": "params", - "required": [ - "repo", - "ref" - ], - "properties": { - "repo": { - "type": "string", - "description": "Repository identifier in format 'did:plc:.../repoName'" - }, - "ref": { - "type": "string", - "description": "Git reference (branch, tag, or commit SHA)" - }, - "path": { - "type": "string", - "description": "Path within the repository tree", - "default": "" - } - } - }, - "output": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": [ - "ref", - "files" - ], - "properties": { - "ref": { - "type": "string", - "description": "The git reference used" - }, - "parent": { - "type": "string", - "description": "The parent path in the tree" - }, - "dotdot": { - "type": "string", - "description": "Parent directory path" - }, - "readme": { - "type": "ref", - "ref": "#readme", - "description": "Readme for this file tree" - }, - "lastCommit": { - "type": "ref", - "ref": "#lastCommit" - }, - "files": { - "type": "array", - "items": { - "type": "ref", - "ref": "#treeEntry" - } - } - } - } - }, - "errors": [ - { - "name": "RepoNotFound", - "description": "Repository not found or access denied" - }, - { - "name": "RefNotFound", - "description": "Git reference not found" - }, - { - "name": "PathNotFound", - "description": "Path not found in repository tree" - }, - { - "name": "InvalidRequest", - "description": "Invalid request parameters" - } - ] - }, - "readme": { - "type": "object", - "required": [ - "filename", - "contents" - ], - "properties": { - "filename": { - "type": "string", - "description": "Name of the readme file" - }, - "contents": { - "type": "string", - "description": "Contents of the readme file" - } - } - }, - "treeEntry": { - "type": "object", - "required": [ - "name", - "mode", - "size" - ], - "properties": { - "name": { - "type": "string", - "description": "Relative file or directory name" - }, - "mode": { - "type": "string", - "description": "File mode" - }, - "size": { - "type": "integer", - "description": "File size in bytes" - }, - "last_commit": { - "type": "ref", - "ref": "#lastCommit" - } - } - }, - "lastCommit": { - "type": "object", - "required": [ - "hash", - "message", - "when" - ], - "properties": { - "hash": { - "type": "string", - "description": "Commit hash" - }, - "message": { - "type": "string", - "description": "Commit message" - }, - "author": { - "type": "ref", - "ref": "#signature" - }, - "when": { - "type": "string", - "format": "datetime", - "description": "Commit timestamp" - } - } - }, - "signature": { - "type": "object", - "required": [ - "name", - "email", - "when" - ], - "properties": { - "name": { - "type": "string", - "description": "Author name" - }, - "email": { - "type": "string", - "description": "Author email" - }, - "when": { - "type": "string", - "format": "datetime", - "description": "Author timestamp" - } - } - } - } -} diff --git a/packages/lexicon/lexicons/st/itch/discussion/repo.json b/packages/lexicon/lexicons/st/itch/discussion/repo.json deleted file mode 100644 index 1af4553..0000000 --- a/packages/lexicon/lexicons/st/itch/discussion/repo.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "lexicon": 1, - "id": "st.itch.discussion.repo", - "needsCbor": true, - "needsType": true, - "defs": { - "main": { - "type": "record", - "key": "literal:self", - "record": { - "type": "object", - "required": ["repo", "createdAt"], - "properties": { - "repo": { - "type": "string", - "format": "at-uri", - "description": "AT-URI of the sh.tangled.repo record this user is claiming as their RFD discussion repo." - }, - "createdAt": { - "type": "string", - "format": "datetime" - } - } - } - } - } -} diff --git a/packages/lexicon/package.json b/packages/lexicon/package.json deleted file mode 100644 index 17af2c9..0000000 --- a/packages/lexicon/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "lexicon", - "type": "module", - "version": "0.0.1", - "devEngines": { - "node": ">=24.15.0" - }, - "main": "./src/lexicons/index.ts", - "exports": { - ".": "./src/lexicons/index.ts", - "./types/*": "./src/lexicons/types/*.ts", - "./lexicons/*": "./lexicons/*.json", - "./package.json": "./package.json" - }, - "atcute:lexicons": { - "mappings": { - "sh.tangled.*": { - "type": "namespace", - "path": "./types/sh/tangled/{{nsid_remainder}}" - }, - "st.itch.*": { - "type": "namespace", - "path": "./types/st/itch/{{nsid_remainder}}" - } - } - }, - "scripts": { - "build": "lex-cli generate", - "dev": "lex-cli generate --watch" - }, - "dependencies": { - "@atcute/lexicons": "^2.0.0" - }, - "devDependencies": { - "@atcute/atproto": "^4.0.0", - "@atcute/lex-cli": "^3.0.0" - } -} diff --git a/packages/lexicon/src/lexicons/index.ts b/packages/lexicon/src/lexicons/index.ts deleted file mode 100644 index 5b6acdb..0000000 --- a/packages/lexicon/src/lexicons/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -export * as ShTangledRepo from "./types/sh/tangled/repo.ts"; -export * as ShTangledRepoBlob from "./types/sh/tangled/repo/blob.ts"; -export * as ShTangledRepoGetDefaultBranch from "./types/sh/tangled/repo/getDefaultBranch.ts"; -export * as ShTangledRepoIssue from "./types/sh/tangled/repo/issue.ts"; -export * as ShTangledRepoIssueComment from "./types/sh/tangled/repo/issue/comment.ts"; -export * as ShTangledRepoPull from "./types/sh/tangled/repo/pull.ts"; -export * as ShTangledRepoPullComment from "./types/sh/tangled/repo/pull/comment.ts"; -export * as ShTangledRepoPullStatus from "./types/sh/tangled/repo/pull/status.ts"; -export * as ShTangledRepoPullStatusClosed from "./types/sh/tangled/repo/pull/status/closed.ts"; -export * as ShTangledRepoPullStatusMerged from "./types/sh/tangled/repo/pull/status/merged.ts"; -export * as ShTangledRepoPullStatusOpen from "./types/sh/tangled/repo/pull/status/open.ts"; -export * as ShTangledRepoTree from "./types/sh/tangled/repo/tree.ts"; -export * as StItchDiscussionRepo from "./types/st/itch/discussion/repo.ts"; diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo.ts deleted file mode 100644 index d240629..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo.ts +++ /dev/null @@ -1,78 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _mainSchema = /*#__PURE__*/ v.record( - /*#__PURE__*/ v.tidString(), - /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.literal("sh.tangled.repo"), - createdAt: /*#__PURE__*/ v.datetimeString(), - /** - * @minGraphemes 1 - * @maxGraphemes 140 - */ - description: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.constrain(/*#__PURE__*/ v.string(), [ - /*#__PURE__*/ v.stringGraphemes(1, 140), - ]), - ), - /** - * knot where the repo was created - */ - knot: /*#__PURE__*/ v.string(), - /** - * List of labels that this repo subscribes to - */ - labels: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.array(/*#__PURE__*/ v.resourceUriString()), - ), - /** - * name of the repo - */ - name: /*#__PURE__*/ v.string(), - /** - * DID of the repo itself, if assigned - */ - repoDid: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.didString()), - /** - * source of the repo - */ - source: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.genericUriString()), - /** - * CI runner to send jobs to and receive results from - */ - spindle: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - /** - * Topics related to the repo - * @maxLength 50 - */ - topics: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.constrain( - /*#__PURE__*/ v.array( - /*#__PURE__*/ v.constrain(/*#__PURE__*/ v.string(), [ - /*#__PURE__*/ v.stringLength(1, 50), - ]), - ), - [/*#__PURE__*/ v.arrayLength(0, 50)], - ), - ), - /** - * Any URI related to the repo - */ - website: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.genericUriString()), - }), -); - -type main$schematype = typeof _mainSchema; - -export interface mainSchema extends main$schematype {} - -export const mainSchema = _mainSchema as mainSchema; - -export interface Main extends v.InferInput {} - -declare module "@atcute/lexicons/ambient" { - interface Records { - "sh.tangled.repo": mainSchema; - } -} diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/blob.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/blob.ts deleted file mode 100644 index ecbe2db..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/blob.ts +++ /dev/null @@ -1,152 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _lastCommitSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.blob#lastCommit"), - ), - get author() { - return /*#__PURE__*/ v.optional(signatureSchema); - }, - /** - * Commit hash - */ - hash: /*#__PURE__*/ v.string(), - /** - * Commit message - */ - message: /*#__PURE__*/ v.string(), - /** - * Commit timestamp - */ - when: /*#__PURE__*/ v.datetimeString(), -}); -const _mainSchema = /*#__PURE__*/ v.query("sh.tangled.repo.blob", { - params: /*#__PURE__*/ v.object({ - /** - * Path to the file within the repository - */ - path: /*#__PURE__*/ v.string(), - /** - * Return raw file content instead of JSON response - * @default false - */ - raw: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.boolean(), false), - /** - * Git reference (branch, tag, or commit SHA) - */ - ref: /*#__PURE__*/ v.string(), - /** - * Repository identifier in format 'did:plc:.../repoName' - */ - repo: /*#__PURE__*/ v.string(), - }), - output: { - type: "lex", - schema: /*#__PURE__*/ v.object({ - /** - * File content (base64 encoded for binary files) - */ - content: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - /** - * Content encoding - */ - encoding: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literalEnum(["base64", "utf-8"]), - ), - fileTooLarge: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.boolean()), - /** - * Whether the file is binary - */ - isBinary: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.boolean()), - get lastCommit() { - return /*#__PURE__*/ v.optional(lastCommitSchema); - }, - /** - * MIME type of the file - */ - mimeType: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - /** - * The file path - */ - path: /*#__PURE__*/ v.string(), - /** - * The git reference used - */ - ref: /*#__PURE__*/ v.string(), - /** - * File size in bytes - */ - size: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.integer()), - /** - * Submodule information if path is a submodule - */ - get submodule() { - return /*#__PURE__*/ v.optional(submoduleSchema); - }, - }), - }, -}); -const _signatureSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.blob#signature"), - ), - /** - * Author email - */ - email: /*#__PURE__*/ v.string(), - /** - * Author name - */ - name: /*#__PURE__*/ v.string(), - /** - * Author timestamp - */ - when: /*#__PURE__*/ v.datetimeString(), -}); -const _submoduleSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.blob#submodule"), - ), - /** - * Branch to track in the submodule - */ - branch: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - /** - * Submodule name - */ - name: /*#__PURE__*/ v.string(), - /** - * Submodule repository URL - */ - url: /*#__PURE__*/ v.string(), -}); - -type lastCommit$schematype = typeof _lastCommitSchema; -type main$schematype = typeof _mainSchema; -type signature$schematype = typeof _signatureSchema; -type submodule$schematype = typeof _submoduleSchema; - -export interface lastCommitSchema extends lastCommit$schematype {} -export interface mainSchema extends main$schematype {} -export interface signatureSchema extends signature$schematype {} -export interface submoduleSchema extends submodule$schematype {} - -export const lastCommitSchema = _lastCommitSchema as lastCommitSchema; -export const mainSchema = _mainSchema as mainSchema; -export const signatureSchema = _signatureSchema as signatureSchema; -export const submoduleSchema = _submoduleSchema as submoduleSchema; - -export interface LastCommit extends v.InferInput {} -export interface Signature extends v.InferInput {} -export interface Submodule extends v.InferInput {} - -export interface $params extends v.InferInput {} -export interface $output extends v.InferXRPCBodyInput {} - -declare module "@atcute/lexicons/ambient" { - interface XRPCQueries { - "sh.tangled.repo.blob": mainSchema; - } -} diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/getDefaultBranch.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/getDefaultBranch.ts deleted file mode 100644 index 5115f56..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/getDefaultBranch.ts +++ /dev/null @@ -1,77 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _mainSchema = /*#__PURE__*/ v.query("sh.tangled.repo.getDefaultBranch", { - params: /*#__PURE__*/ v.object({ - /** - * Repository identifier in format 'did:plc:.../repoName' - */ - repo: /*#__PURE__*/ v.string(), - }), - output: { - type: "lex", - schema: /*#__PURE__*/ v.object({ - get author() { - return /*#__PURE__*/ v.optional(signatureSchema); - }, - /** - * Latest commit hash on default branch - */ - hash: /*#__PURE__*/ v.string(), - /** - * Latest commit message - */ - message: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - /** - * Default branch name - */ - name: /*#__PURE__*/ v.string(), - /** - * Short commit hash - */ - shortHash: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - /** - * Timestamp of latest commit - */ - when: /*#__PURE__*/ v.datetimeString(), - }), - }, -}); -const _signatureSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.getDefaultBranch#signature"), - ), - /** - * Author email - */ - email: /*#__PURE__*/ v.string(), - /** - * Author name - */ - name: /*#__PURE__*/ v.string(), - /** - * Author timestamp - */ - when: /*#__PURE__*/ v.datetimeString(), -}); - -type main$schematype = typeof _mainSchema; -type signature$schematype = typeof _signatureSchema; - -export interface mainSchema extends main$schematype {} -export interface signatureSchema extends signature$schematype {} - -export const mainSchema = _mainSchema as mainSchema; -export const signatureSchema = _signatureSchema as signatureSchema; - -export interface Signature extends v.InferInput {} - -export interface $params extends v.InferInput {} -export interface $output extends v.InferXRPCBodyInput {} - -declare module "@atcute/lexicons/ambient" { - interface XRPCQueries { - "sh.tangled.repo.getDefaultBranch": mainSchema; - } -} diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/issue.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/issue.ts deleted file mode 100644 index e3ca7a4..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/issue.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _mainSchema = /*#__PURE__*/ v.record( - /*#__PURE__*/ v.tidString(), - /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.literal("sh.tangled.repo.issue"), - body: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - createdAt: /*#__PURE__*/ v.datetimeString(), - mentions: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.array(/*#__PURE__*/ v.didString()), - ), - references: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.array(/*#__PURE__*/ v.resourceUriString()), - ), - repo: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.resourceUriString()), - repoDid: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.didString()), - title: /*#__PURE__*/ v.string(), - }), -); - -type main$schematype = typeof _mainSchema; - -export interface mainSchema extends main$schematype {} - -export const mainSchema = _mainSchema as mainSchema; - -export interface Main extends v.InferInput {} - -declare module "@atcute/lexicons/ambient" { - interface Records { - "sh.tangled.repo.issue": mainSchema; - } -} diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/issue/comment.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/issue/comment.ts deleted file mode 100644 index 892efdd..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/issue/comment.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _mainSchema = /*#__PURE__*/ v.record( - /*#__PURE__*/ v.tidString(), - /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.literal("sh.tangled.repo.issue.comment"), - body: /*#__PURE__*/ v.string(), - createdAt: /*#__PURE__*/ v.datetimeString(), - issue: /*#__PURE__*/ v.resourceUriString(), - mentions: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.array(/*#__PURE__*/ v.didString()), - ), - references: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.array(/*#__PURE__*/ v.resourceUriString()), - ), - replyTo: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.resourceUriString()), - }), -); - -type main$schematype = typeof _mainSchema; - -export interface mainSchema extends main$schematype {} - -export const mainSchema = _mainSchema as mainSchema; - -export interface Main extends v.InferInput {} - -declare module "@atcute/lexicons/ambient" { - interface Records { - "sh.tangled.repo.issue.comment": mainSchema; - } -} diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull.ts deleted file mode 100644 index ec8c3fd..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull.ts +++ /dev/null @@ -1,83 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _mainSchema = /*#__PURE__*/ v.record( - /*#__PURE__*/ v.tidString(), - /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.literal("sh.tangled.repo.pull"), - body: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - createdAt: /*#__PURE__*/ v.datetimeString(), - dependentOn: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.resourceUriString()), - mentions: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.array(/*#__PURE__*/ v.didString()), - ), - references: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.array(/*#__PURE__*/ v.resourceUriString()), - ), - get rounds() { - return /*#__PURE__*/ v.array(roundSchema); - }, - get source() { - return /*#__PURE__*/ v.optional(sourceSchema); - }, - get target() { - return targetSchema; - }, - title: /*#__PURE__*/ v.string(), - }), -); -const _roundSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.pull#round"), - ), - createdAt: /*#__PURE__*/ v.datetimeString(), - /** - * @accept application/gzip - */ - patchBlob: /*#__PURE__*/ v.constrain(/*#__PURE__*/ v.blob(), [ - /*#__PURE__*/ v.blobAccept(["application/gzip"]), - ]), -}); -const _sourceSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.pull#source"), - ), - branch: /*#__PURE__*/ v.string(), - repo: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.resourceUriString()), - repoDid: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.didString()), -}); -const _targetSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.pull#target"), - ), - branch: /*#__PURE__*/ v.string(), - repo: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.resourceUriString()), - repoDid: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.didString()), -}); - -type main$schematype = typeof _mainSchema; -type round$schematype = typeof _roundSchema; -type source$schematype = typeof _sourceSchema; -type target$schematype = typeof _targetSchema; - -export interface mainSchema extends main$schematype {} -export interface roundSchema extends round$schematype {} -export interface sourceSchema extends source$schematype {} -export interface targetSchema extends target$schematype {} - -export const mainSchema = _mainSchema as mainSchema; -export const roundSchema = _roundSchema as roundSchema; -export const sourceSchema = _sourceSchema as sourceSchema; -export const targetSchema = _targetSchema as targetSchema; - -export interface Main extends v.InferInput {} -export interface Round extends v.InferInput {} -export interface Source extends v.InferInput {} -export interface Target extends v.InferInput {} - -declare module "@atcute/lexicons/ambient" { - interface Records { - "sh.tangled.repo.pull": mainSchema; - } -} diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/comment.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/comment.ts deleted file mode 100644 index 6fa7ea0..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/comment.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _mainSchema = /*#__PURE__*/ v.record( - /*#__PURE__*/ v.tidString(), - /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.literal("sh.tangled.repo.pull.comment"), - body: /*#__PURE__*/ v.string(), - createdAt: /*#__PURE__*/ v.datetimeString(), - mentions: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.array(/*#__PURE__*/ v.didString()), - ), - pull: /*#__PURE__*/ v.resourceUriString(), - references: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.array(/*#__PURE__*/ v.resourceUriString()), - ), - }), -); - -type main$schematype = typeof _mainSchema; - -export interface mainSchema extends main$schematype {} - -export const mainSchema = _mainSchema as mainSchema; - -export interface Main extends v.InferInput {} - -declare module "@atcute/lexicons/ambient" { - interface Records { - "sh.tangled.repo.pull.comment": mainSchema; - } -} diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status.ts deleted file mode 100644 index 0b53fd6..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _mainSchema = /*#__PURE__*/ v.record( - /*#__PURE__*/ v.tidString(), - /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.literal("sh.tangled.repo.pull.status"), - pull: /*#__PURE__*/ v.resourceUriString(), - /** - * status of the pull request - * @default "sh.tangled.repo.pull.status.open" - */ - status: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.string< - | "sh.tangled.repo.pull.status.closed" - | "sh.tangled.repo.pull.status.merged" - | "sh.tangled.repo.pull.status.open" - | (string & {}) - >(), - "sh.tangled.repo.pull.status.open", - ), - }), -); - -type main$schematype = typeof _mainSchema; - -export interface mainSchema extends main$schematype {} - -export const mainSchema = _mainSchema as mainSchema; - -export interface Main extends v.InferInput {} - -declare module "@atcute/lexicons/ambient" { - interface Records { - "sh.tangled.repo.pull.status": mainSchema; - } -} diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status/closed.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status/closed.ts deleted file mode 100644 index 27f02ad..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status/closed.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; - -const _mainSchema = /*#__PURE__*/ v.literal( - "sh.tangled.repo.pull.status.closed", -); - -type main$schematype = typeof _mainSchema; - -export interface mainSchema extends main$schematype {} - -export const mainSchema = _mainSchema as mainSchema; - -export type Main = v.InferInput; diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status/merged.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status/merged.ts deleted file mode 100644 index 284bbaa..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status/merged.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; - -const _mainSchema = /*#__PURE__*/ v.literal( - "sh.tangled.repo.pull.status.merged", -); - -type main$schematype = typeof _mainSchema; - -export interface mainSchema extends main$schematype {} - -export const mainSchema = _mainSchema as mainSchema; - -export type Main = v.InferInput; diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status/open.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status/open.ts deleted file mode 100644 index 5c94a36..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/pull/status/open.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; - -const _mainSchema = /*#__PURE__*/ v.literal("sh.tangled.repo.pull.status.open"); - -type main$schematype = typeof _mainSchema; - -export interface mainSchema extends main$schematype {} - -export const mainSchema = _mainSchema as mainSchema; - -export type Main = v.InferInput; diff --git a/packages/lexicon/src/lexicons/types/sh/tangled/repo/tree.ts b/packages/lexicon/src/lexicons/types/sh/tangled/repo/tree.ts deleted file mode 100644 index f439367..0000000 --- a/packages/lexicon/src/lexicons/types/sh/tangled/repo/tree.ts +++ /dev/null @@ -1,152 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _lastCommitSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.tree#lastCommit"), - ), - get author() { - return /*#__PURE__*/ v.optional(signatureSchema); - }, - /** - * Commit hash - */ - hash: /*#__PURE__*/ v.string(), - /** - * Commit message - */ - message: /*#__PURE__*/ v.string(), - /** - * Commit timestamp - */ - when: /*#__PURE__*/ v.datetimeString(), -}); -const _mainSchema = /*#__PURE__*/ v.query("sh.tangled.repo.tree", { - params: /*#__PURE__*/ v.object({ - /** - * Path within the repository tree - * @default "" - */ - path: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string(), ""), - /** - * Git reference (branch, tag, or commit SHA) - */ - ref: /*#__PURE__*/ v.string(), - /** - * Repository identifier in format 'did:plc:.../repoName' - */ - repo: /*#__PURE__*/ v.string(), - }), - output: { - type: "lex", - schema: /*#__PURE__*/ v.object({ - /** - * Parent directory path - */ - dotdot: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - get files() { - return /*#__PURE__*/ v.array(treeEntrySchema); - }, - get lastCommit() { - return /*#__PURE__*/ v.optional(lastCommitSchema); - }, - /** - * The parent path in the tree - */ - parent: /*#__PURE__*/ v.optional(/*#__PURE__*/ v.string()), - /** - * Readme for this file tree - */ - get readme() { - return /*#__PURE__*/ v.optional(readmeSchema); - }, - /** - * The git reference used - */ - ref: /*#__PURE__*/ v.string(), - }), - }, -}); -const _readmeSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.tree#readme"), - ), - /** - * Contents of the readme file - */ - contents: /*#__PURE__*/ v.string(), - /** - * Name of the readme file - */ - filename: /*#__PURE__*/ v.string(), -}); -const _signatureSchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.tree#signature"), - ), - /** - * Author email - */ - email: /*#__PURE__*/ v.string(), - /** - * Author name - */ - name: /*#__PURE__*/ v.string(), - /** - * Author timestamp - */ - when: /*#__PURE__*/ v.datetimeString(), -}); -const _treeEntrySchema = /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.optional( - /*#__PURE__*/ v.literal("sh.tangled.repo.tree#treeEntry"), - ), - get last_commit() { - return /*#__PURE__*/ v.optional(lastCommitSchema); - }, - /** - * File mode - */ - mode: /*#__PURE__*/ v.string(), - /** - * Relative file or directory name - */ - name: /*#__PURE__*/ v.string(), - /** - * File size in bytes - */ - size: /*#__PURE__*/ v.integer(), -}); - -type lastCommit$schematype = typeof _lastCommitSchema; -type main$schematype = typeof _mainSchema; -type readme$schematype = typeof _readmeSchema; -type signature$schematype = typeof _signatureSchema; -type treeEntry$schematype = typeof _treeEntrySchema; - -export interface lastCommitSchema extends lastCommit$schematype {} -export interface mainSchema extends main$schematype {} -export interface readmeSchema extends readme$schematype {} -export interface signatureSchema extends signature$schematype {} -export interface treeEntrySchema extends treeEntry$schematype {} - -export const lastCommitSchema = _lastCommitSchema as lastCommitSchema; -export const mainSchema = _mainSchema as mainSchema; -export const readmeSchema = _readmeSchema as readmeSchema; -export const signatureSchema = _signatureSchema as signatureSchema; -export const treeEntrySchema = _treeEntrySchema as treeEntrySchema; - -export interface LastCommit extends v.InferInput {} -export interface Readme extends v.InferInput {} -export interface Signature extends v.InferInput {} -export interface TreeEntry extends v.InferInput {} - -export interface $params extends v.InferInput {} -export interface $output extends v.InferXRPCBodyInput {} - -declare module "@atcute/lexicons/ambient" { - interface XRPCQueries { - "sh.tangled.repo.tree": mainSchema; - } -} diff --git a/packages/lexicon/src/lexicons/types/st/itch/discussion/repo.ts b/packages/lexicon/src/lexicons/types/st/itch/discussion/repo.ts deleted file mode 100644 index 2a15d5b..0000000 --- a/packages/lexicon/src/lexicons/types/st/itch/discussion/repo.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type {} from "@atcute/lexicons"; -import * as v from "@atcute/lexicons/validations"; -import type {} from "@atcute/lexicons/ambient"; - -const _mainSchema = /*#__PURE__*/ v.record( - /*#__PURE__*/ v.literal("self"), - /*#__PURE__*/ v.object({ - $type: /*#__PURE__*/ v.literal("st.itch.discussion.repo"), - createdAt: /*#__PURE__*/ v.datetimeString(), - /** - * AT-URI of the sh.tangled.repo record this user is claiming as their RFD discussion repo. - */ - repo: /*#__PURE__*/ v.resourceUriString(), - }), -); - -type main$schematype = typeof _mainSchema; - -export interface mainSchema extends main$schematype {} - -export const mainSchema = _mainSchema as mainSchema; - -export interface Main extends v.InferInput {} - -declare module "@atcute/lexicons/ambient" { - interface Records { - "st.itch.discussion.repo": mainSchema; - } -} diff --git a/packages/www/astro.config.ts b/packages/www/astro.config.ts index ccb9bee..a9118e0 100644 --- a/packages/www/astro.config.ts +++ b/packages/www/astro.config.ts @@ -1,16 +1,11 @@ +import node from '@astrojs/node'; import { defineConfig } from 'astro/config'; -import cloudflare from '@astrojs/cloudflare'; // https://astro.build/config export default defineConfig({ output: 'server', - adapter: cloudflare({ - auxiliaryWorkers: [ - { configPath: './workers/spacedust.wrangler.jsonc' }, - ], - }), + adapter: node({ mode: 'standalone' }), experimental: { rustCompiler: true, - advancedRouting: true - } + }, }); diff --git a/packages/www/package.json b/packages/www/package.json index 19af650..37b32ce 100644 --- a/packages/www/package.json +++ b/packages/www/package.json @@ -8,28 +8,26 @@ "scripts": { "dev": "astro dev --host 127.0.0.1 --port 4321", "build": "astro build", - "preview": "wrangler dev", + "preview": "node ./dist/server/entry.mjs", + "start": "node ./dist/server/entry.mjs", "astro": "astro", - "test": "vitest run", - "generate-types": "wrangler types" + "test": "vitest run" }, "dependencies": { - "@astrojs/cloudflare": "^13.5.0", + "@astrojs/node": "^10.1.1", "@atcute/atproto": "^4.0.0", "@atcute/client": "^2.0.0", "@atcute/identity": "^2.0.0", "@atcute/identity-resolver": "^2.0.0", "@atcute/lexicons": "^2.0.0", "@atcute/oauth-browser-client": "^4.0.0", + "@rfd/core": "workspace:*", "astro": "^6.3.1", - "hono": "^4.0.0", - "lexicon": "workspace:*", - "wrangler": "^4.90.0" + "hono": "^4.0.0" }, "devDependencies": { "@astrojs/check": "^0.9.9", "@astrojs/compiler-rs": "^0.1.10", - "@cloudflare/workers-types": "^4.0.0", "vitest": "^4.0.0" }, "overrides": { diff --git a/packages/www/src/api/admin.ts b/packages/www/src/api/admin.ts deleted file mode 100644 index 307135d..0000000 --- a/packages/www/src/api/admin.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; -import { env } from 'cloudflare:workers'; -import { Hono } from 'hono'; - -import { backfillOwner } from '../lib/backfill.ts'; - -const app = new Hono(); - -app.use('*', async (c, next) => { - const token = env.RFD_ADMIN_TOKEN; - const auth = c.req.header('authorization'); - if (!token || auth !== `Bearer ${token}`) { - return c.json({ error: 'unauthorized' }, 401); - } - await next(); -}); - -app.post('/reindex', async (c) => { - const owner = env.RFD_DEFAULT_OWNER?.trim(); - if (!owner) { - return c.json({ error: 'RFD_DEFAULT_OWNER not configured' }, 400); - } - if (!env.db) { - return c.json({ error: 'D1 binding `db` not configured' }, 500); - } - const counts = await backfillOwner(env.db, owner as ActorIdentifier); - return c.json({ ok: true, ...counts }); -}); - -async function proxyToSpacedust(path: string, body?: unknown): Promise { - const init: RequestInit = body !== undefined - ? { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) } - : { method: 'POST' }; - return env.SPACEDUST.fetch(new Request(`https://spacedust.internal${path}`, init)); -} - -app.post('/spacedust/start', async (c) => { - const owner = env.RFD_DEFAULT_OWNER?.trim(); - if (!owner) { - return c.json({ error: 'RFD_DEFAULT_OWNER not configured' }, 400); - } - const configureRes = await proxyToSpacedust('/configure', { owner }); - if (!configureRes.ok) { - return c.json({ error: 'configure failed', status: configureRes.status }, 502); - } - const startRes = await proxyToSpacedust('/start'); - return new Response(startRes.body, { status: startRes.status, headers: startRes.headers }); -}); - -app.post('/spacedust/stop', async () => proxyToSpacedust('/stop')); - -app.get('/spacedust/status', async () => proxyToSpacedust('/status')); - -export default app; diff --git a/packages/www/src/api/discussion.ts b/packages/www/src/api/discussion.ts deleted file mode 100644 index cfd4732..0000000 --- a/packages/www/src/api/discussion.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; -import { Hono } from 'hono'; - -import { getDiscussionRepo } from '../lib/discussion.ts'; - -const app = new Hono(); - -app.get('/:handle', async (c) => { - const { handle } = c.req.param(); - return c.json(await getDiscussionRepo(handle as ActorIdentifier)); -}); - -export default app; diff --git a/packages/www/src/api/healthz.ts b/packages/www/src/api/healthz.ts deleted file mode 100644 index 6e60f31..0000000 --- a/packages/www/src/api/healthz.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Hono } from 'hono'; - -const app = new Hono(); - -app.get('/', (c) => c.json({ ok: true })); - -export default app; diff --git a/packages/www/src/api/proposals.ts b/packages/www/src/api/proposals.ts deleted file mode 100644 index 4151492..0000000 --- a/packages/www/src/api/proposals.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; -import { env } from 'cloudflare:workers'; -import { Hono } from 'hono'; - -import { getProposal, listProposals } from '../lib/proposal.ts'; - -const app = new Hono(); - -app.get('/:handle/proposals', async (c) => { - const { handle } = c.req.param(); - const result = await listProposals({ DB: env.db ?? null }, handle as ActorIdentifier); - return c.json(result); -}); - -app.get('/:handle/proposals/:slug', async (c) => { - const { handle, slug } = c.req.param(); - const result = await getProposal({ DB: env.db ?? null }, handle as ActorIdentifier, slug); - if (!result) { - return c.json({ error: `proposal not found: ${slug}` }, 404); - } - return c.json(result); -}); - -export default app; diff --git a/packages/www/src/api/pulls.ts b/packages/www/src/api/pulls.ts deleted file mode 100644 index b1cb391..0000000 --- a/packages/www/src/api/pulls.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; -import { Hono } from 'hono'; - -import { fetchPull } from '../lib/pull.ts'; - -const app = new Hono(); - -app.get('/:handle/pulls/:rkey', async (c) => { - const { handle, rkey } = c.req.param(); - return c.json(await fetchPull({ handle: handle as ActorIdentifier, rkey })); -}); - -export default app; diff --git a/packages/www/src/app.ts b/packages/www/src/app.ts deleted file mode 100644 index 8123a1f..0000000 --- a/packages/www/src/app.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { sessions, actions, middleware, pages } from 'astro/hono'; -import { Hono } from 'hono'; - -import admin from './api/admin.ts'; -import discussion from './api/discussion.ts'; -import healthz from './api/healthz.ts'; -import proposals from './api/proposals.ts'; -import pulls from './api/pulls.ts'; -import { NoDiscussionRepoError } from './lib/discussion.ts'; - -const api = new Hono(); -api.route('/healthz', healthz); -api.route('/admin', admin); -api.route('/', proposals); -api.route('/', discussion); -api.route('/', pulls); -api.onError((err, c) => { - console.error(err); - if (err instanceof NoDiscussionRepoError) { - return c.json({ error: err.message }, 404); - } - return c.json({ error: err.message ?? String(err) }, 500); -}); - -const app = new Hono(); -app.route('/api/v0', api); -app.use(sessions()).use(actions()).use(middleware()).use(pages()); - -export default app; diff --git a/packages/www/src/components/Discussion.astro b/packages/www/src/components/Discussion.astro new file mode 100644 index 0000000..e1e832c --- /dev/null +++ b/packages/www/src/components/Discussion.astro @@ -0,0 +1,40 @@ +--- +import { getRfd } from '../config.ts'; +import { parseAtUri } from '@rfd/core'; + +interface Props { pullUris: string[]; } +const { pullUris } = Astro.props; + +interface Entry { authorDid: string; body: string; createdAt: string; } +const rfd = getRfd(); +const entries: Entry[] = []; +for (const uri of pullUris) { + let cursor: string | undefined; + do { + const page = await rfd.getDiscussion(uri, cursor); + for (const c of page.items) { + entries.push({ + authorDid: parseAtUri(c.uri)?.did ?? '', + body: c.value.body.original, + createdAt: c.value.createdAt, + }); + } + cursor = page.cursor ?? undefined; + } while (cursor); +} +entries.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); +--- +
+

Discussion ({entries.length})

+ {entries.length === 0 &&

No comments yet.

} +
    + {entries.map((c) => ( +
  • +

    + {c.authorDid} · +

    +
    {c.body}
    +
  • + ))} +
+
diff --git a/packages/www/src/components/Link.astro b/packages/www/src/components/Link.astro index ef9b3a7..a40fa1c 100644 --- a/packages/www/src/components/Link.astro +++ b/packages/www/src/components/Link.astro @@ -1,26 +1,6 @@ --- -import { env } from 'cloudflare:workers'; import type { HTMLAttributes } from 'astro/types'; - type Props = HTMLAttributes<'a'>; - -const { href, ...rest } = Astro.props; -const owner = env.RFD_DEFAULT_OWNER?.trim(); - -const normalize = (raw: string | URL | null | undefined): string | undefined => { - if (!raw) return undefined; - const value = typeof raw === 'string' ? raw : raw.href; - if (!owner) return value; - if (!value.startsWith('/') || value.startsWith('//')) return value; - // Parse as relative URL using a throwaway base so we get pathname/search/hash. - const parsed = new URL(value, 'http://x'); - const segments = parsed.pathname.split('/').filter(Boolean); - if (segments[0] !== owner) return value; - const tail = segments.slice(1).join('/'); - parsed.pathname = tail ? `/${tail}` : '/'; - return `${parsed.pathname}${parsed.search}${parsed.hash}`; -}; - -const resolved = normalize(href); +const props = Astro.props; --- - + diff --git a/packages/www/src/components/register.ts b/packages/www/src/components/register.ts new file mode 100644 index 0000000..cbf565b --- /dev/null +++ b/packages/www/src/components/register.ts @@ -0,0 +1,7 @@ +// Client-only entry: registers every custom element exactly once. +// Imported from Base.astro's + + diff --git a/packages/www/src/lib/atproto.ts b/packages/www/src/lib/atproto.ts deleted file mode 100644 index 0d9d101..0000000 --- a/packages/www/src/lib/atproto.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { simpleFetchHandler, XRPC } from '@atcute/client'; -import { - CompositeDidDocumentResolver, - CompositeHandleResolver, - DohJsonHandleResolver, - LocalActorResolver, - PlcDidDocumentResolver, - WebDidDocumentResolver, - WellKnownHandleResolver, -} from '@atcute/identity-resolver'; -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; - -import { resolveActorViaSlingshot } from './slingshot.ts'; - -let lazyLocalResolver: LocalActorResolver | undefined; - -function localResolver(): LocalActorResolver { - if (!lazyLocalResolver) { - const handleResolver = new CompositeHandleResolver({ - strategy: 'race', - methods: { - dns: new DohJsonHandleResolver({ - dohUrl: 'https://mozilla.cloudflare-dns.com/dns-query', - }), - http: new WellKnownHandleResolver(), - }, - }); - const didDocumentResolver = new CompositeDidDocumentResolver({ - methods: { - plc: new PlcDidDocumentResolver(), - web: new WebDidDocumentResolver(), - }, - }); - lazyLocalResolver = new LocalActorResolver({ handleResolver, didDocumentResolver }); - } - return lazyLocalResolver; -} - -export interface ResolvedActor { - did: string; - handle: string; - pds: string; -} - -export async function resolveActor(actor: ActorIdentifier): Promise { - try { - const mini = await resolveActorViaSlingshot(actor); - if (mini) return mini; - } catch (err) { - console.warn('slingshot resolveMiniDoc failed, falling back to local resolver', err); - } - const r = await localResolver().resolve(actor); - return { did: r.did, handle: r.handle, pds: r.pds }; -} - -export function clientFor(pds: string): XRPC { - return new XRPC({ handler: simpleFetchHandler({ service: pds }) }); -} - -export const SLINGSHOT_BASE_URL = 'https://slingshot.microcosm.blue'; - -let slingshotClient: XRPC | undefined; - -export function clientForSlingshot(): XRPC { - if (!slingshotClient) { - slingshotClient = new XRPC({ - handler: simpleFetchHandler({ service: SLINGSHOT_BASE_URL }), - }); - } - return slingshotClient; -} diff --git a/packages/www/src/lib/backfill.ts b/packages/www/src/lib/backfill.ts deleted file mode 100644 index 21c3ef4..0000000 --- a/packages/www/src/lib/backfill.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; - -import { coldStartFromConstellation, type ColdStartCounts } from './cold-start.ts'; - -export type BackfillResult = ColdStartCounts; - -/** - * Cold-start ingestion: drives the indexer from Constellation backlinks against the - * owner's discussion repo, hydrating each record via Slingshot. Used by the admin - * /reindex endpoint and as the recovery path when the Spacedust subscriber boots cold. - */ -export async function backfillOwner( - db: D1Database, - owner: ActorIdentifier, -): Promise { - const result = await coldStartFromConstellation(db, owner); - const { view: _view, ...counts } = result; - return counts; -} diff --git a/packages/www/src/lib/cache.ts b/packages/www/src/lib/cache.ts new file mode 100644 index 0000000..66ae89a --- /dev/null +++ b/packages/www/src/lib/cache.ts @@ -0,0 +1,34 @@ +interface Entry { + value: unknown; + expiresAtMs: number; +} + +export interface CacheOptions { + nowMs?: () => number; +} + +export function createCache(options: CacheOptions = {}) { + const nowMs = options.nowMs ?? (() => Date.now()); + const store = new Map(); + + return { + /** Return the cached value for `key`, or run `fn`, cache it for `ttlSeconds`, and return it. */ + async wrap(key: string, ttlSeconds: number, fn: () => Promise): Promise { + const hit = store.get(key); + if (hit && hit.expiresAtMs > nowMs()) { + return hit.value as T; + } + const value = await fn(); + store.set(key, { value, expiresAtMs: nowMs() + ttlSeconds * 1000 }); + return value; + }, + clear(): void { + store.clear(); + }, + }; +} + +export type Cache = ReturnType; + +/** Process-wide cache shared by all requests. */ +export const cache: Cache = createCache(); diff --git a/packages/www/src/lib/cold-start.ts b/packages/www/src/lib/cold-start.ts deleted file mode 100644 index 71bc7fb..0000000 --- a/packages/www/src/lib/cold-start.ts +++ /dev/null @@ -1,169 +0,0 @@ -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; - -import { resolveActor } from './atproto.ts'; -import { listLinkingRecords } from './constellation.ts'; -import { getDiscussionRepo, type DiscussionRepoView } from './discussion.ts'; -import { - createDbOps, - indexRecord, - parseAtUri, - type IndexerOps, -} from './index-event.ts'; -import { gunzipToString, listMarkdownFilesInDiff } from './patch.ts'; -import { hydrateRecord, type HydratedRecord } from './slingshot.ts'; - -export interface ColdStartCounts { - pulls: number; - comments: number; - statuses: number; - issues: number; - issueComments: number; -} - -export interface ColdStartResult extends ColdStartCounts { - view: DiscussionRepoView; -} - -interface IngestContext { - db: D1Database; - ops: IndexerOps; - ownerRepoUri: string; - pdsByDid: Map; - counts: ColdStartCounts; -} - -async function fetchPatchPaths(pds: string, did: string, cid: string): Promise { - const url = new URL('/xrpc/com.atproto.sync.getBlob', pds); - url.searchParams.set('did', did); - url.searchParams.set('cid', cid); - const res = await fetch(url); - if (!res.ok) return []; - const text = await gunzipToString(new Uint8Array(await res.arrayBuffer())); - return listMarkdownFilesInDiff(text).map((entry) => entry.path); -} - -async function resolvePdsFor(did: string, cache: Map): Promise { - const cached = cache.get(did); - if (cached) return cached; - try { - const r = await resolveActor(did as ActorIdentifier); - cache.set(did, r.pds); - return r.pds; - } catch { - return null; - } -} - -async function ingestRecord( - atUri: string, - collection: string, - ctx: IngestContext, -): Promise { - const hydrated = await hydrateRecord(atUri); - if (!hydrated) return null; - const result = await indexRecord( - { uri: hydrated.uri, cid: hydrated.cid, collection, value: hydrated.value }, - ctx.ops, - ctx.ownerRepoUri, - ); - return result === 'indexed' ? hydrated : null; -} - -async function ingestPullsAndIssues(ctx: IngestContext): Promise<{ - pullUris: string[]; - issueUris: string[]; -}> { - const pullUris: string[] = []; - const issueUris: string[] = []; - - for await (const uri of listLinkingRecords({ - target: ctx.ownerRepoUri, - collection: 'sh.tangled.repo.pull', - path: '.target.repo', - })) { - const hydrated = await ingestRecord(uri, 'sh.tangled.repo.pull', ctx); - if (!hydrated) continue; - ctx.counts.pulls++; - pullUris.push(hydrated.uri); - - const parsed = parseAtUri(hydrated.uri); - const record = hydrated.value as { - rounds?: { patchBlob?: { ref?: { $link?: string } } }[]; - }; - const latest = record.rounds?.[record.rounds.length - 1]; - const patchCid = latest?.patchBlob?.ref?.$link; - if (patchCid && parsed && ctx.ops.replacePullFiles) { - const pds = await resolvePdsFor(parsed.did, ctx.pdsByDid); - const paths = pds ? await fetchPatchPaths(pds, parsed.did, patchCid) : []; - await ctx.ops.replacePullFiles(hydrated.uri, paths); - } - } - - for await (const uri of listLinkingRecords({ - target: ctx.ownerRepoUri, - collection: 'sh.tangled.repo.issue', - path: '.repo', - })) { - const hydrated = await ingestRecord(uri, 'sh.tangled.repo.issue', ctx); - if (!hydrated) continue; - ctx.counts.issues++; - issueUris.push(hydrated.uri); - } - - return { pullUris, issueUris }; -} - -async function ingestPullChildren(pullUris: string[], ctx: IngestContext): Promise { - for (const pullUri of pullUris) { - for await (const uri of listLinkingRecords({ - target: pullUri, - collection: 'sh.tangled.repo.pull.comment', - path: '.pull', - })) { - const hydrated = await ingestRecord(uri, 'sh.tangled.repo.pull.comment', ctx); - if (hydrated) ctx.counts.comments++; - } - for await (const uri of listLinkingRecords({ - target: pullUri, - collection: 'sh.tangled.repo.pull.status', - path: '.pull', - })) { - const hydrated = await ingestRecord(uri, 'sh.tangled.repo.pull.status', ctx); - if (hydrated) ctx.counts.statuses++; - } - } -} - -async function ingestIssueChildren(issueUris: string[], ctx: IngestContext): Promise { - for (const issueUri of issueUris) { - for await (const uri of listLinkingRecords({ - target: issueUri, - collection: 'sh.tangled.repo.issue.comment', - path: '.issue', - })) { - const hydrated = await ingestRecord(uri, 'sh.tangled.repo.issue.comment', ctx); - if (hydrated) ctx.counts.issueComments++; - } - } -} - -export async function coldStartFromConstellation( - db: D1Database, - owner: ActorIdentifier, -): Promise { - const view = await getDiscussionRepo(owner); - const ownerRepoUri = view.repo.uri; - const ctx: IngestContext = { - db, - ops: createDbOps(db), - ownerRepoUri, - pdsByDid: new Map(), - counts: { pulls: 0, comments: 0, statuses: 0, issues: 0, issueComments: 0 }, - }; - - const { pullUris, issueUris } = await ingestPullsAndIssues(ctx); - await ingestPullChildren(pullUris, ctx); - await ingestIssueChildren(issueUris, ctx); - - return { view, ...ctx.counts }; -} diff --git a/packages/www/src/lib/constellation.ts b/packages/www/src/lib/constellation.ts deleted file mode 100644 index d43c708..0000000 --- a/packages/www/src/lib/constellation.ts +++ /dev/null @@ -1,63 +0,0 @@ -export const CONSTELLATION_BASE_URL = 'https://constellation.microcosm.blue'; - -export interface RecordId { - did: string; - collection: string; - rkey: string; -} - -export interface LinksQuery { - target: string; - collection: string; - path: string; - cursor?: string; - limit?: number; - baseUrl?: string; -} - -interface LinksResponse { - total: number; - linking_records: RecordId[]; - cursor: string | null; -} - -export function recordIdToAtUri(id: RecordId): string { - return `at://${id.did}/${id.collection}/${id.rkey}`; -} - -export function buildLinksUrl(query: LinksQuery): string { - const base = query.baseUrl ?? CONSTELLATION_BASE_URL; - const params = new URLSearchParams(); - params.set('target', query.target); - params.set('collection', query.collection); - params.set('path', query.path); - if (query.cursor) params.set('cursor', query.cursor); - if (typeof query.limit === 'number') params.set('limit', String(query.limit)); - return `${base}/links?${params.toString()}`; -} - -export interface ListLinkingRecordsOptions { - fetch?: typeof fetch; - signal?: AbortSignal; -} - -export async function* listLinkingRecords( - query: LinksQuery, - options: ListLinkingRecordsOptions = {}, -): AsyncGenerator { - const fetchImpl = options.fetch ?? globalThis.fetch; - let cursor = query.cursor; - while (true) { - const url = buildLinksUrl({ ...query, cursor }); - const res = await fetchImpl(url, { signal: options.signal }); - if (!res.ok) { - throw new Error(`constellation /links failed: ${res.status} ${await res.text()}`); - } - const body = (await res.json()) as LinksResponse; - for (const record of body.linking_records) { - yield recordIdToAtUri(record); - } - if (!body.cursor) return; - cursor = body.cursor; - } -} diff --git a/packages/www/src/lib/db.ts b/packages/www/src/lib/db.ts deleted file mode 100644 index 7021bdc..0000000 --- a/packages/www/src/lib/db.ts +++ /dev/null @@ -1,333 +0,0 @@ -import type * as IssueComment from 'lexicon/types/sh/tangled/repo/issue/comment'; -import type * as Issue from 'lexicon/types/sh/tangled/repo/issue'; -import type * as PullComment from 'lexicon/types/sh/tangled/repo/pull/comment'; -import type * as PullStatus from 'lexicon/types/sh/tangled/repo/pull/status'; -import type * as Pull from 'lexicon/types/sh/tangled/repo/pull'; - -const PROPOSAL_SLUG_RE = /^\d{4}(?:-[a-z0-9][a-z0-9-]*)?$/; -const ISSUE_TITLE_PREFIX_RE = /^\[(\d{4}(?:-[a-z0-9][a-z0-9-]*)?)\]/; - -export interface PullRow { - uri: string; - cid: string; - author_did: string; - target_repo_uri: string; - target_branch: string; - source_repo_uri: string | null; - source_branch: string | null; - title: string; - body: string | null; - rounds_json: string; - state: 'open' | 'closed' | 'merged'; - state_updated_at: string | null; - created_at: string; -} - -export interface CommentRow { - uri: string; - cid: string; - author_did: string; - pull_uri: string; - body: string; - created_at: string; -} - -export interface IssueRow { - uri: string; - cid: string; - author_did: string; - target_repo_uri: string; - title: string; - body: string | null; - proposal_slug: string | null; - created_at: string; -} - -export interface IssueCommentRow { - uri: string; - cid: string; - author_did: string; - issue_uri: string; - body: string; - created_at: string; -} - -export function fileNameToSlug(path: string): string | null { - const name = path.split('/').pop() ?? ''; - if (!name.endsWith('.md')) return null; - const base = name.slice(0, -3); - return PROPOSAL_SLUG_RE.test(base) ? base : null; -} - -export function parseIssueTitleSlug(title: string): string | null { - const match = title.match(ISSUE_TITLE_PREFIX_RE); - return match?.[1] ?? null; -} - -export function statusValueToState(value?: string): 'open' | 'closed' | 'merged' { - switch (value) { - case 'sh.tangled.repo.pull.status.closed': - return 'closed'; - case 'sh.tangled.repo.pull.status.merged': - return 'merged'; - default: - return 'open'; - } -} - -export async function upsertPull( - db: D1Database, - authorDid: string, - uri: string, - cid: string, - record: Pull.Main, -): Promise { - const rounds = record.rounds.map((r) => ({ - createdAt: r.createdAt, - patchCid: (r.patchBlob as { ref: { $link: string } }).ref.$link, - })); - await db - .prepare( - `INSERT INTO pulls (uri, cid, author_did, target_repo_uri, target_branch, source_repo_uri, source_branch, title, body, rounds_json, created_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) - ON CONFLICT(uri) DO UPDATE SET - cid = excluded.cid, - target_repo_uri = excluded.target_repo_uri, - target_branch = excluded.target_branch, - source_repo_uri = excluded.source_repo_uri, - source_branch = excluded.source_branch, - title = excluded.title, - body = excluded.body, - rounds_json = excluded.rounds_json`, - ) - .bind( - uri, - cid, - authorDid, - record.target.repo ?? '', - record.target.branch, - record.source?.repo ?? null, - record.source?.branch ?? null, - record.title, - record.body ?? null, - JSON.stringify(rounds), - record.createdAt, - ) - .run(); -} - -export async function replacePullFiles( - db: D1Database, - pullUri: string, - paths: string[], -): Promise { - await db.prepare('DELETE FROM pull_files WHERE pull_uri = ?').bind(pullUri).run(); - const unique = Array.from(new Set(paths)); - if (unique.length === 0) return; - const stmts = unique.map((p) => - db - .prepare( - 'INSERT OR IGNORE INTO pull_files (pull_uri, file_path, proposal_slug) VALUES (?1, ?2, ?3)', - ) - .bind(pullUri, p, fileNameToSlug(p)), - ); - await db.batch(stmts); -} - -export async function setPullState( - db: D1Database, - pullUri: string, - state: 'open' | 'closed' | 'merged', - updatedAt: string, -): Promise { - await db - .prepare('UPDATE pulls SET state = ?1, state_updated_at = ?2 WHERE uri = ?3') - .bind(state, updatedAt, pullUri) - .run(); -} - -export async function upsertComment( - db: D1Database, - authorDid: string, - uri: string, - cid: string, - record: PullComment.Main, -): Promise { - await db - .prepare( - `INSERT INTO comments (uri, cid, author_did, pull_uri, body, created_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6) - ON CONFLICT(uri) DO UPDATE SET cid = excluded.cid, body = excluded.body`, - ) - .bind(uri, cid, authorDid, record.pull, record.body, record.createdAt) - .run(); -} - -export async function upsertIssue( - db: D1Database, - authorDid: string, - uri: string, - cid: string, - record: Issue.Main, -): Promise { - const slug = parseIssueTitleSlug(record.title); - await db - .prepare( - `INSERT INTO issues (uri, cid, author_did, target_repo_uri, title, body, proposal_slug, created_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) - ON CONFLICT(uri) DO UPDATE SET - cid = excluded.cid, - target_repo_uri = excluded.target_repo_uri, - title = excluded.title, - body = excluded.body, - proposal_slug = excluded.proposal_slug`, - ) - .bind( - uri, - cid, - authorDid, - record.repo ?? '', - record.title, - record.body ?? null, - slug, - record.createdAt, - ) - .run(); -} - -export async function upsertIssueComment( - db: D1Database, - authorDid: string, - uri: string, - cid: string, - record: IssueComment.Main, -): Promise { - await db - .prepare( - `INSERT INTO issue_comments (uri, cid, author_did, issue_uri, body, created_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6) - ON CONFLICT(uri) DO UPDATE SET cid = excluded.cid, body = excluded.body`, - ) - .bind(uri, cid, authorDid, record.issue, record.body, record.createdAt) - .run(); -} - -export async function pullExists(db: D1Database, uri: string): Promise { - const r = await db.prepare('SELECT 1 FROM pulls WHERE uri = ?').bind(uri).first(); - return r !== null; -} - -export async function issueExists(db: D1Database, uri: string): Promise { - const r = await db.prepare('SELECT 1 FROM issues WHERE uri = ?').bind(uri).first(); - return r !== null; -} - -const DELETE_TABLE_BY_COLLECTION: Record = { - 'sh.tangled.repo.pull': 'pulls', - 'sh.tangled.repo.pull.comment': 'comments', - 'sh.tangled.repo.issue': 'issues', - 'sh.tangled.repo.issue.comment': 'issue_comments', -}; - -export async function deleteRecord( - db: D1Database, - collection: string, - uri: string, -): Promise { - const table = DELETE_TABLE_BY_COLLECTION[collection]; - if (!table) return; - await db.prepare(`DELETE FROM ${table} WHERE uri = ?`).bind(uri).run(); -} - -/** - * Tangled stores `target.repo` as either the lexicon-correct at-uri form OR - * the bare `repoDid` that its own UI writes. Callers should pass both - * identifiers so we match either shape in the indexed rows. - */ -export type RepoIdentifiers = readonly string[]; - -export async function selectPullsTouchingProposal( - db: D1Database, - repoIds: RepoIdentifiers, - slug: string, -): Promise { - if (repoIds.length === 0) return []; - const numericSlug = slug.match(/^\d{4}/)?.[0] ?? slug; - const placeholders = repoIds.map((_, i) => `?${i + 1}`).join(', '); - const slugIdx = repoIds.length; - const res = await db - .prepare( - `SELECT p.* FROM pulls p - JOIN pull_files pf ON pf.pull_uri = p.uri - WHERE p.target_repo_uri IN (${placeholders}) - AND (pf.proposal_slug = ?${slugIdx + 1} OR pf.proposal_slug = ?${slugIdx + 2}) - ORDER BY p.created_at DESC`, - ) - .bind(...repoIds, slug, numericSlug) - .all(); - return res.results ?? []; -} - -export async function selectInDiscussionSlugs( - db: D1Database, - repoIds: RepoIdentifiers, -): Promise { - if (repoIds.length === 0) return []; - const placeholders = repoIds.map((_, i) => `?${i + 1}`).join(', '); - const res = await db - .prepare( - `SELECT DISTINCT pf.proposal_slug AS slug FROM pull_files pf - JOIN pulls p ON p.uri = pf.pull_uri - WHERE p.target_repo_uri IN (${placeholders}) - AND p.state = 'open' - AND pf.proposal_slug IS NOT NULL`, - ) - .bind(...repoIds) - .all<{ slug: string }>(); - return (res.results ?? []).map((r) => r.slug).filter((s): s is string => !!s); -} - -export async function selectCommentsForProposal( - db: D1Database, - repoIds: RepoIdentifiers, - slug: string, -): Promise { - if (repoIds.length === 0) return []; - const numericSlug = slug.match(/^\d{4}/)?.[0] ?? slug; - const placeholders = repoIds.map((_, i) => `?${i + 1}`).join(', '); - const slugIdx = repoIds.length; - const res = await db - .prepare( - `SELECT c.* FROM comments c - JOIN pull_files pf ON pf.pull_uri = c.pull_uri - JOIN pulls p ON p.uri = c.pull_uri - WHERE p.target_repo_uri IN (${placeholders}) - AND (pf.proposal_slug = ?${slugIdx + 1} OR pf.proposal_slug = ?${slugIdx + 2}) - ORDER BY c.created_at`, - ) - .bind(...repoIds, slug, numericSlug) - .all(); - return res.results ?? []; -} - -export async function selectIssueCommentsForProposal( - db: D1Database, - repoIds: RepoIdentifiers, - slug: string, -): Promise { - if (repoIds.length === 0) return []; - const numericSlug = slug.match(/^\d{4}/)?.[0] ?? slug; - const placeholders = repoIds.map((_, i) => `?${i + 1}`).join(', '); - const slugIdx = repoIds.length; - const res = await db - .prepare( - `SELECT ic.* FROM issue_comments ic - JOIN issues i ON i.uri = ic.issue_uri - WHERE i.target_repo_uri IN (${placeholders}) - AND (i.proposal_slug = ?${slugIdx + 1} OR i.proposal_slug = ?${slugIdx + 2}) - ORDER BY ic.created_at`, - ) - .bind(...repoIds, slug, numericSlug) - .all(); - return res.results ?? []; -} diff --git a/packages/www/src/lib/discussion.ts b/packages/www/src/lib/discussion.ts deleted file mode 100644 index 4358157..0000000 --- a/packages/www/src/lib/discussion.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { parseCanonicalResourceUri } from '@atcute/lexicons/syntax'; -import type { ActorIdentifier, Did } from '@atcute/lexicons/syntax'; -import type * as DiscussionRepo from 'lexicon/types/st/itch/discussion/repo'; -import type * as Repo from 'lexicon/types/sh/tangled/repo'; - -import { clientForSlingshot, resolveActor } from './atproto.ts'; -import { getDefaultBranch, knotRepoId } from './knot.ts'; - -export interface DiscussionRepoView { - claim: { - uri: string; - cid: string; - repo: string; - createdAt: string; - }; - repo: { - uri: string; - cid: string; - name: string; - knot: string; - description?: string; - createdAt: string; - defaultBranch: string; - /** The repo's own DID (assigned by the knot), distinct from the owner's DID. */ - repoDid?: string; - owner: { did: string; handle?: string }; - }; -} - -export class NoDiscussionRepoError extends Error { - override name = 'NoDiscussionRepoError'; - constructor(handle: string) { - super(`no discussion repo claimed for ${handle}`); - } -} - -export async function getDiscussionRepo(handle: ActorIdentifier): Promise { - const claimer = await resolveActor(handle); - const rpc = clientForSlingshot(); - - let claimRes; - try { - claimRes = await rpc.get('com.atproto.repo.getRecord', { - params: { - repo: claimer.did as Did, - collection: 'st.itch.discussion.repo', - rkey: 'self', - }, - }); - } catch (err) { - throw new NoDiscussionRepoError(claimer.handle); - } - const claimValue = claimRes.data.value as DiscussionRepo.Main; - - const parsed = parseCanonicalResourceUri(claimValue.repo); - const owner = await resolveActor(parsed.repo as ActorIdentifier); - const repoRes = await rpc.get('com.atproto.repo.getRecord', { - params: { - repo: parsed.repo, - collection: 'sh.tangled.repo', - rkey: parsed.rkey, - }, - }); - const repoValue = repoRes.data.value as Repo.Main; - - let defaultBranch = 'main'; - try { - const branch = await getDefaultBranch(repoValue.knot, knotRepoId(owner.did, repoValue.name)); - if (branch.name) defaultBranch = branch.name; - } catch { - // fall back to 'main' - } - - return { - claim: { - uri: claimRes.data.uri, - cid: claimRes.data.cid ?? '', - repo: claimValue.repo, - createdAt: claimValue.createdAt, - }, - repo: { - uri: repoRes.data.uri, - cid: repoRes.data.cid ?? '', - name: repoValue.name, - knot: repoValue.knot, - description: repoValue.description, - createdAt: repoValue.createdAt, - defaultBranch, - repoDid: repoValue.repoDid, - owner: { did: owner.did, handle: owner.handle }, - }, - }; -} diff --git a/packages/www/src/lib/index-event.ts b/packages/www/src/lib/index-event.ts deleted file mode 100644 index 1936594..0000000 --- a/packages/www/src/lib/index-event.ts +++ /dev/null @@ -1,180 +0,0 @@ -import type * as IssueComment from 'lexicon/types/sh/tangled/repo/issue/comment'; -import type * as Issue from 'lexicon/types/sh/tangled/repo/issue'; -import type * as PullComment from 'lexicon/types/sh/tangled/repo/pull/comment'; -import type * as Pull from 'lexicon/types/sh/tangled/repo/pull'; - -import { - deleteRecord, - issueExists, - pullExists, - replacePullFiles, - setPullState, - statusValueToState, - upsertComment, - upsertIssue, - upsertIssueComment, - upsertPull, -} from './db.ts'; - -export type TrackedCollection = - | 'sh.tangled.repo.pull' - | 'sh.tangled.repo.pull.comment' - | 'sh.tangled.repo.pull.status' - | 'sh.tangled.repo.issue' - | 'sh.tangled.repo.issue.comment'; - -export const TRACKED_COLLECTIONS: TrackedCollection[] = [ - 'sh.tangled.repo.pull', - 'sh.tangled.repo.pull.comment', - 'sh.tangled.repo.pull.status', - 'sh.tangled.repo.issue', - 'sh.tangled.repo.issue.comment', -]; - -export interface ParsedAtUri { - did: string; - collection: string; - rkey: string; -} - -export function parseAtUri(uri: string): ParsedAtUri | null { - if (!uri.startsWith('at://')) return null; - const rest = uri.slice('at://'.length); - const parts = rest.split('/'); - if (parts.length < 3) return null; - const [did, collection, ...rkeyParts] = parts; - if (!did || !collection || rkeyParts.length === 0) return null; - return { did, collection, rkey: rkeyParts.join('/') }; -} - -export interface IndexerOps { - upsertPull: ( - authorDid: string, - uri: string, - cid: string, - record: Pull.Main, - ) => Promise; - upsertComment: ( - authorDid: string, - uri: string, - cid: string, - record: PullComment.Main, - ) => Promise; - setPullState: ( - pullUri: string, - state: 'open' | 'closed' | 'merged', - updatedAt: string, - ) => Promise; - upsertIssue: ( - authorDid: string, - uri: string, - cid: string, - record: Issue.Main, - ) => Promise; - upsertIssueComment: ( - authorDid: string, - uri: string, - cid: string, - record: IssueComment.Main, - ) => Promise; - pullExists: (uri: string) => Promise; - issueExists: (uri: string) => Promise; - replacePullFiles?: (pullUri: string, paths: string[]) => Promise; - deleteByUri: (collection: string, uri: string) => Promise; -} - -export interface IndexInput { - uri: string; - cid: string; - collection: string; - value: unknown; -} - -export type IndexResult = 'indexed' | 'skipped' | 'unsupported'; - -export async function indexRecord( - input: IndexInput, - ops: IndexerOps, - ownerRepoUri: string, -): Promise { - const parsed = parseAtUri(input.uri); - if (!parsed) return 'unsupported'; - const value = input.value as Record | null | undefined; - if (!value) return 'skipped'; - - switch (input.collection) { - case 'sh.tangled.repo.pull': { - const target = (value as { target?: { repo?: string } }).target; - if (target?.repo !== ownerRepoUri) return 'skipped'; - await ops.upsertPull(parsed.did, input.uri, input.cid, value as Pull.Main); - return 'indexed'; - } - case 'sh.tangled.repo.pull.comment': { - const pullUri = (value as { pull?: string }).pull; - if (!pullUri || !(await ops.pullExists(pullUri))) return 'skipped'; - await ops.upsertComment(parsed.did, input.uri, input.cid, value as PullComment.Main); - return 'indexed'; - } - case 'sh.tangled.repo.pull.status': { - const pullUri = (value as { pull?: string }).pull; - if (!pullUri || !(await ops.pullExists(pullUri))) return 'skipped'; - const state = statusValueToState((value as { status?: string }).status); - const updatedAt = - (value as { createdAt?: string }).createdAt ?? new Date().toISOString(); - await ops.setPullState(pullUri, state, updatedAt); - return 'indexed'; - } - case 'sh.tangled.repo.issue': { - const repo = (value as { repo?: string }).repo; - if (repo !== ownerRepoUri) return 'skipped'; - await ops.upsertIssue(parsed.did, input.uri, input.cid, value as Issue.Main); - return 'indexed'; - } - case 'sh.tangled.repo.issue.comment': { - const issueUri = (value as { issue?: string }).issue; - if (!issueUri || !(await ops.issueExists(issueUri))) return 'skipped'; - await ops.upsertIssueComment( - parsed.did, - input.uri, - input.cid, - value as IssueComment.Main, - ); - return 'indexed'; - } - default: - return 'unsupported'; - } -} - -export interface DeleteInput { - uri: string; - collection: string; -} - -export type DeleteResult = 'deleted' | 'unsupported'; - -export async function indexDelete( - input: DeleteInput, - ops: IndexerOps, -): Promise { - if (!(TRACKED_COLLECTIONS as string[]).includes(input.collection)) { - return 'unsupported'; - } - await ops.deleteByUri(input.collection, input.uri); - return 'deleted'; -} - -export function createDbOps(db: D1Database): IndexerOps { - return { - upsertPull: (did, uri, cid, record) => upsertPull(db, did, uri, cid, record), - upsertComment: (did, uri, cid, record) => upsertComment(db, did, uri, cid, record), - setPullState: (uri, state, updatedAt) => setPullState(db, uri, state, updatedAt), - upsertIssue: (did, uri, cid, record) => upsertIssue(db, did, uri, cid, record), - upsertIssueComment: (did, uri, cid, record) => - upsertIssueComment(db, did, uri, cid, record), - pullExists: (uri) => pullExists(db, uri), - issueExists: (uri) => issueExists(db, uri), - replacePullFiles: (uri, paths) => replacePullFiles(db, uri, paths), - deleteByUri: (collection, uri) => deleteRecord(db, collection, uri), - }; -} diff --git a/packages/www/src/lib/knot.ts b/packages/www/src/lib/knot.ts deleted file mode 100644 index 10ae163..0000000 --- a/packages/www/src/lib/knot.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { simpleFetchHandler, XRPC } from '@atcute/client'; - -export interface DefaultBranch { - name: string; - hash: string; - when: string; -} - -export interface TreeFile { - name: string; - mode: string; - size: number; -} - -export interface ProposalFile { - slug: string; - path: string; - size: number; -} - -const PROPOSAL_FILE_RE = /^\d{4}(?:-[a-z0-9][a-z0-9-]*)?\.md$/; - -function clientFor(knot: string): XRPC { - const service = knot.startsWith('http') ? knot : `https://${knot}`; - return new XRPC({ handler: simpleFetchHandler({ service }) }); -} - -/** - * Knot's `repo` parameter is `did:plc:.../repoName` per the lexicon spec. - */ -export function knotRepoId(did: string, repoName: string): string { - return `${did}/${repoName}`; -} - -export async function getDefaultBranch(knot: string, repoId: string): Promise { - const rpc = clientFor(knot); - const res = await rpc.get('sh.tangled.repo.getDefaultBranch', { - params: { repo: repoId }, - }); - const data = res.data as DefaultBranch; - return data; -} - -export async function listMarkdownProposals( - knot: string, - repoId: string, - ref: string, -): Promise { - const rpc = clientFor(knot); - const res = await rpc.get('sh.tangled.repo.tree', { - params: { repo: repoId, ref }, - }); - const files = (res.data as { files: TreeFile[] }).files ?? []; - const out: ProposalFile[] = []; - for (const f of files) { - if (!PROPOSAL_FILE_RE.test(f.name)) continue; - const slug = f.name.slice(0, -3); - out.push({ slug, path: f.name, size: f.size }); - } - return out.sort((a, b) => a.slug.localeCompare(b.slug)); -} - -export interface BlobResponse { - content: string; - encoding: 'utf-8' | 'base64'; - size: number; - isBinary?: boolean; -} - -export async function getBlob( - knot: string, - repoId: string, - ref: string, - path: string, -): Promise { - const rpc = clientFor(knot); - try { - const res = await rpc.get('sh.tangled.repo.blob', { - params: { repo: repoId, ref, path }, - }); - const data = res.data as BlobResponse; - if (data.isBinary) return null; - if (data.encoding === 'base64') { - return atob(data.content); - } - return data.content; - } catch { - return null; - } -} diff --git a/packages/www/src/lib/oauth.ts b/packages/www/src/lib/oauth.ts index ae303f3..740b598 100644 --- a/packages/www/src/lib/oauth.ts +++ b/packages/www/src/lib/oauth.ts @@ -20,7 +20,21 @@ import { let configured = false; -export const SCOPE = 'atproto transition:generic'; +/** + * Granular permission grant, scoped to exactly what the app writes on the + * user's behalf (reads of public records don't require a scope): + * + * - `repo:sh.tangled.feed.comment` — posting a comment (`createRecord`). + * - `repo:sh.tangled.repo.pull` — creating a proposal/draft as a tangled pull + * (`createRecord`). + * - `blob:application/gzip` — uploading the gzipped patch blob attached to a + * proposal (`uploadBlob`). + * + * Replaces the broad `transition:generic` grant. Keep in sync with the `scope` + * in oauth/client-metadata.json.ts. + */ +export const SCOPE = + 'atproto repo:sh.tangled.feed.comment repo:sh.tangled.repo.pull blob:application/gzip'; /** * Build the OAuth `client_id` for the current origin. diff --git a/packages/www/src/lib/proposal.ts b/packages/www/src/lib/proposal.ts deleted file mode 100644 index f7b29be..0000000 --- a/packages/www/src/lib/proposal.ts +++ /dev/null @@ -1,391 +0,0 @@ -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; - -import { getDiscussionRepo, type DiscussionRepoView } from './discussion.ts'; -import { - getDefaultBranch, - getBlob, - knotRepoId, - listMarkdownProposals, - type ProposalFile, -} from './knot.ts'; -import { resolveActor, clientFor as pdsClient } from './atproto.ts'; -import type * as Pull from 'lexicon/types/sh/tangled/repo/pull'; -import { - fileNameToSlug, - selectCommentsForProposal, - selectInDiscussionSlugs, - selectIssueCommentsForProposal, - selectPullsTouchingProposal, - type CommentRow, - type IssueCommentRow, - type PullRow, -} from './db.ts'; -import { - extractMarkdownFileFromDiff, - gunzipToString, - listMarkdownFilesInDiff, -} from './patch.ts'; - -export type ProposalStatus = - | 'discussion' - | 'abandoned' - | 'published' - | 'committed' - | 'unknown'; - -export interface ProposalSummary { - slug: string; - title?: string; - status: ProposalStatus; -} - -export interface DiscussionEntry { - source: 'pull' | 'issue'; - uri: string; - authorDid: string; - body: string; - createdAt: string; -} - -export interface ProposalDetail { - slug: string; - repo: DiscussionRepoView['repo']; - status: ProposalStatus; - content: { source: 'default' | 'pull'; text: string } | null; - pulls: PullRow[]; - discussion: DiscussionEntry[]; -} - -function deriveStatus(opts: { - onDefaultBranch: boolean; - pulls: PullRow[]; -}): ProposalStatus { - const { onDefaultBranch, pulls } = opts; - const hasOpen = pulls.some((p) => p.state === 'open'); - const hasMerged = pulls.some((p) => p.state === 'merged'); - const allClosed = pulls.length > 0 && pulls.every((p) => p.state === 'closed'); - - if (hasOpen) return 'discussion'; - if (onDefaultBranch && hasMerged) return 'published'; - if (onDefaultBranch) return 'committed'; - if (allClosed) return 'abandoned'; - return 'unknown'; -} - -export interface ProposalEnv { - DB: D1Database | null; -} - -async function resolveOwner(handle: ActorIdentifier) { - const view = await getDiscussionRepo(handle); - return view; -} - -function repoIdsFor(view: DiscussionRepoView): readonly string[] { - const ids = new Set([view.repo.uri]); - if (view.repo.repoDid) ids.add(view.repo.repoDid); - return [...ids]; -} - -export async function listProposals( - env: ProposalEnv, - handle: ActorIdentifier, -): Promise<{ repo: DiscussionRepoView['repo']; proposals: ProposalSummary[] }> { - const view = await resolveOwner(handle); - const repoId = knotRepoId(view.repo.owner.did, view.repo.name); - - let onDefault: ProposalFile[] = []; - let branchName = 'main'; - try { - const branch = await getDefaultBranch(view.repo.knot, repoId); - branchName = branch.name; - onDefault = await listMarkdownProposals(view.repo.knot, repoId, branchName); - } catch { - // knot unreachable / repo empty — leave onDefault empty. - } - - const repoIds = repoIdsFor(view); - const inDiscussion = env.DB ? await selectInDiscussionSlugs(env.DB, repoIds) : []; - let liveSlugs: string[] = []; - try { - liveSlugs = await fallbackOwnerPullSlugs(view); - } catch { - // best-effort — leave empty if PDS lookup fails - } - const seen = new Set(); - const summaries: ProposalSummary[] = []; - - for (const file of onDefault) { - seen.add(file.slug); - summaries.push({ slug: file.slug, status: 'committed' }); - } - for (const slug of [...inDiscussion, ...liveSlugs]) { - if (seen.has(slug)) continue; - seen.add(slug); - summaries.push({ slug, status: 'discussion' }); - } - - if (env.DB) { - // Refine status only when D1 actually has indexed pulls for the slug. - // Otherwise keep the optimistic `committed`/`discussion` we just set. - for (const summary of summaries) { - const pulls = await selectPullsTouchingProposal(env.DB, repoIds, summary.slug); - if (pulls.length === 0) continue; - summary.status = deriveStatus({ - onDefaultBranch: seen.has(summary.slug) && onDefault.some((f) => f.slug === summary.slug), - pulls, - }); - } - } - - summaries.sort((a, b) => a.slug.localeCompare(b.slug)); - return { repo: view.repo, proposals: summaries }; -} - -async function fetchPatchAsText(pds: string, did: string, cid: string): Promise { - const url = new URL('/xrpc/com.atproto.sync.getBlob', pds); - url.searchParams.set('did', did); - url.searchParams.set('cid', cid); - const res = await fetch(url); - if (!res.ok) return null; - const bytes = new Uint8Array(await res.arrayBuffer()); - try { - return await gunzipToString(bytes); - } catch { - return null; - } -} - -async function readContentFromPull( - pull: PullRow, - path: string, -): Promise { - const rounds = JSON.parse(pull.rounds_json) as { createdAt: string; patchCid: string }[]; - const latest = rounds[rounds.length - 1]; - if (!latest) return null; - const owner = await resolveActor(pull.author_did as ActorIdentifier); - const text = await fetchPatchAsText(owner.pds, pull.author_did, latest.patchCid); - if (!text) return null; - const entry = extractMarkdownFileFromDiff(text, path); - return entry?.content ?? null; -} - -/** - * Same-author live fallback for the proposal list: walks the owner's own PDS - * for `sh.tangled.repo.pull` records, extracts every `.md` path each patch - * touches, and returns the proposal slugs derived from those filenames. Used - * when D1 hasn't been seeded with cross-author/forward-going data yet. - */ -async function fallbackOwnerPullSlugs(ownerView: DiscussionRepoView): Promise { - const ownerDid = ownerView.repo.owner.did; - const targetMatches = new Set([ownerView.repo.uri]); - if (ownerView.repo.repoDid) targetMatches.add(ownerView.repo.repoDid); - - const ownerActor = await resolveActor(ownerDid as ActorIdentifier); - const rpc = pdsClient(ownerActor.pds); - - const slugs = new Set(); - let cursor: string | undefined; - let pages = 0; - const MAX_PAGES = 3; - - while (pages < MAX_PAGES) { - const res = await rpc.get('com.atproto.repo.listRecords', { - params: { - repo: ownerDid as never, - collection: 'sh.tangled.repo.pull', - limit: 50, - cursor, - }, - }); - for (const record of res.data.records) { - const value = record.value as Pull.Main; - const targetRepo = value.target?.repo; - if (!targetRepo || !targetMatches.has(targetRepo)) continue; - const rounds = value.rounds ?? []; - const latest = rounds[rounds.length - 1]; - const patchCid = (latest?.patchBlob as { ref?: { $link?: string } } | undefined)?.ref - ?.$link; - if (!patchCid) continue; - const text = await fetchPatchAsText(ownerActor.pds, ownerDid, patchCid); - if (!text) continue; - for (const entry of listMarkdownFilesInDiff(text)) { - const slug = fileNameToSlug(entry.path); - if (slug) slugs.add(slug); - } - } - if (!res.data.cursor) break; - cursor = res.data.cursor; - pages++; - } - return [...slugs]; -} -/** - * Same-author live fallback used when D1 has no rows for this proposal yet - * (typically: a user just submitted a draft and the indexer hasn't caught up). - * Scans `sh.tangled.repo.pull` on the discussion repo owner's PDS, finds - * records whose latest patch touches `${slug}.md`, and synthesises PullRows. - * Cross-author pulls remain invisible until the indexer is running. - */ -async function fallbackOwnerPulls( - ownerView: DiscussionRepoView, - slug: string, -): Promise { - const ownerDid = ownerView.repo.owner.did; - const ownerRepoUri = ownerView.repo.uri; - // `target.repo` may be stored as either the lexicon-correct at-uri or the - // bare `repoDid` that tangled.org's own UI writes. Accept either. - const targetMatches = new Set([ownerRepoUri]); - if (ownerView.repo.repoDid) targetMatches.add(ownerView.repo.repoDid); - const filename = `${slug}.md`; - - const ownerActor = await resolveActor(ownerDid as ActorIdentifier); - const rpc = pdsClient(ownerActor.pds); - - const out: PullRow[] = []; - let cursor: string | undefined; - let pages = 0; - const MAX_PAGES = 3; - - while (pages < MAX_PAGES) { - const res = await rpc.get('com.atproto.repo.listRecords', { - params: { - repo: ownerDid as never, - collection: 'sh.tangled.repo.pull', - limit: 50, - cursor, - }, - }); - for (const record of res.data.records) { - const value = record.value as Pull.Main; - const targetRepo = value.target?.repo; - if (!targetRepo || !targetMatches.has(targetRepo)) continue; - - const rounds = value.rounds ?? []; - const latest = rounds[rounds.length - 1]; - const patchCid = (latest?.patchBlob as { ref?: { $link?: string } } | undefined)?.ref - ?.$link; - if (!patchCid) continue; - const text = await fetchPatchAsText(ownerActor.pds, ownerDid, patchCid); - if (!text) continue; - const entry = extractMarkdownFileFromDiff(text, filename); - if (!entry) continue; - - const mappedRounds = rounds.map((r) => ({ - createdAt: r.createdAt, - patchCid: - (r.patchBlob as { ref?: { $link?: string } } | undefined)?.ref?.$link ?? '', - })); - out.push({ - uri: record.uri, - cid: record.cid ?? '', - author_did: ownerDid, - target_repo_uri: value.target.repo ?? '', - target_branch: value.target.branch, - source_repo_uri: value.source?.repo ?? null, - source_branch: value.source?.branch ?? null, - title: value.title, - body: value.body ?? null, - rounds_json: JSON.stringify(mappedRounds), - state: 'open', - state_updated_at: null, - created_at: value.createdAt, - }); - } - if (!res.data.cursor) break; - cursor = res.data.cursor; - pages++; - } - - out.sort((a, b) => b.created_at.localeCompare(a.created_at)); - return out; -} - -export async function getProposal( - env: ProposalEnv, - handle: ActorIdentifier, - slug: string, -): Promise { - const view = await resolveOwner(handle); - const repoId = knotRepoId(view.repo.owner.did, view.repo.name); - - let branchName = 'main'; - try { - const branch = await getDefaultBranch(view.repo.knot, repoId); - branchName = branch.name; - } catch { - // stay with 'main' default - } - - const filename = `${slug}.md`; - let content: ProposalDetail['content'] = null; - let onDefaultBranch = false; - const fromDefault = await getBlob(view.repo.knot, repoId, branchName, filename); - if (fromDefault !== null) { - onDefaultBranch = true; - content = { source: 'default', text: fromDefault }; - } - - const repoIds = repoIdsFor(view); - let pulls = env.DB ? await selectPullsTouchingProposal(env.DB, repoIds, slug) : []; - if (pulls.length === 0) { - try { - pulls = await fallbackOwnerPulls(view, slug); - } catch { - // best-effort — leave empty if PDS lookup fails - } - } - - if (!content) { - const openPull = pulls.find((p) => p.state === 'open') ?? pulls[0]; - if (openPull) { - const fromPull = await readContentFromPull(openPull, filename); - if (fromPull !== null) { - content = { source: 'pull', text: fromPull }; - } - } - } - - if (!content && pulls.length === 0) return null; - - const status = deriveStatus({ onDefaultBranch, pulls }); - - const discussion: DiscussionEntry[] = []; - if (env.DB) { - const [pcs, ics]: [CommentRow[], IssueCommentRow[]] = await Promise.all([ - selectCommentsForProposal(env.DB, repoIds, slug), - selectIssueCommentsForProposal(env.DB, repoIds, slug), - ]); - for (const c of pcs) { - discussion.push({ - source: 'pull', - uri: c.uri, - authorDid: c.author_did, - body: c.body, - createdAt: c.created_at, - }); - } - for (const c of ics) { - discussion.push({ - source: 'issue', - uri: c.uri, - authorDid: c.author_did, - body: c.body, - createdAt: c.created_at, - }); - } - discussion.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); - } - - return { - slug, - repo: view.repo, - status, - content, - pulls, - discussion, - }; -} - -// suppress unused-import lint; pdsClient may be used by future helpers. -void pdsClient; diff --git a/packages/www/src/lib/pull.ts b/packages/www/src/lib/pull.ts deleted file mode 100644 index 34a91d3..0000000 --- a/packages/www/src/lib/pull.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { parseCanonicalResourceUri } from '@atcute/lexicons/syntax'; -import type { ActorIdentifier, Did } from '@atcute/lexicons/syntax'; -import type * as Pull from 'lexicon/types/sh/tangled/repo/pull'; -import type * as PullComment from 'lexicon/types/sh/tangled/repo/pull/comment'; -import type * as Repo from 'lexicon/types/sh/tangled/repo'; - -import { clientForSlingshot, resolveActor } from './atproto.ts'; -import { listLinkingRecords } from './constellation.ts'; -import { parseAtUri } from './index-event.ts'; -import { extractMarkdownFromPatch, type ExtractedMarkdown } from './patch.ts'; -import { hydrateRecord, type HydratedRecord } from './slingshot.ts'; - -export interface PullView { - pull: { - uri: string; - cid: string; - title: string; - body?: string; - target: Pull.Target; - source?: Pull.Source; - createdAt: string; - rounds: { createdAt: string; patchCid: string }[]; - }; - repo: { - uri: string; - cid: string; - name: string; - knot: string; - description?: string; - createdAt: string; - } | null; - markdown: ExtractedMarkdown | null; - comments: { - uri: string; - cid: string; - body: string; - createdAt: string; - author: { did: string; handle?: string }; - }[]; -} - -export interface FetchPullArgs { - handle: ActorIdentifier; - rkey: string; -} - -export async function fetchPull({ handle, rkey }: FetchPullArgs): Promise { - const author = await resolveActor(handle); - const pullRes = await clientForSlingshot().get('com.atproto.repo.getRecord', { - params: { repo: author.did as Did, collection: 'sh.tangled.repo.pull', rkey }, - }); - const pullValue = pullRes.data.value as Pull.Main; - const pullUri = pullRes.data.uri; - - const repoView = await fetchRepoFromTarget(pullValue.target); - - const latest = pullValue.rounds[pullValue.rounds.length - 1]; - let markdown: ExtractedMarkdown | null = null; - if (latest) { - const patchCid = (latest.patchBlob as { ref: { $link: string } }).ref.$link; - const bytes = await fetchBlob(author.pds, author.did, patchCid); - try { - markdown = await extractMarkdownFromPatch(bytes); - } catch { - markdown = null; - } - } - - const comments = await collectCommentsFor(pullUri); - - return { - pull: { - uri: pullRes.data.uri, - cid: pullRes.data.cid ?? '', - title: pullValue.title, - body: pullValue.body, - target: pullValue.target, - source: pullValue.source, - createdAt: pullValue.createdAt, - rounds: pullValue.rounds.map((r) => ({ - createdAt: r.createdAt, - patchCid: (r.patchBlob as { ref: { $link: string } }).ref.$link, - })), - }, - repo: repoView, - markdown, - comments, - }; -} - -async function fetchRepoFromTarget(target: Pull.Target): Promise { - if (!target.repo) return null; - let parsed; - try { - parsed = parseCanonicalResourceUri(target.repo); - } catch { - return null; - } - const { repo: ownerDid, rkey } = parsed; - - try { - const res = await clientForSlingshot().get('com.atproto.repo.getRecord', { - params: { repo: ownerDid, collection: 'sh.tangled.repo', rkey }, - }); - const value = res.data.value as Repo.Main; - return { - uri: res.data.uri, - cid: res.data.cid ?? '', - name: value.name, - knot: value.knot, - description: value.description, - createdAt: value.createdAt, - }; - } catch { - return null; - } -} - -async function fetchBlob(pds: string, did: string, cid: string): Promise { - const url = new URL('/xrpc/com.atproto.sync.getBlob', pds); - url.searchParams.set('did', did); - url.searchParams.set('cid', cid); - const res = await fetch(url); - if (!res.ok) { - throw new Error(`failed to fetch blob ${cid}: ${res.status}`); - } - return new Uint8Array(await res.arrayBuffer()); -} - -export interface CollectCommentsDeps { - listLinks?: (pullUri: string) => AsyncIterable; - hydrate?: (atUri: string) => Promise; - resolveHandle?: (did: string) => Promise; -} - -export async function collectCommentsFor( - pullUri: string, - deps: CollectCommentsDeps = {}, -): Promise { - const listLinks = - deps.listLinks ?? - ((uri: string) => - listLinkingRecords({ - target: uri, - collection: 'sh.tangled.repo.pull.comment', - path: '.pull', - })); - const hydrate = deps.hydrate ?? hydrateRecord; - const resolveHandle = deps.resolveHandle ?? defaultResolveHandle(); - - const out: PullView['comments'] = []; - for await (const commentUri of listLinks(pullUri)) { - const hydrated = await hydrate(commentUri); - if (!hydrated) continue; - const value = hydrated.value as PullComment.Main; - if (value.pull !== pullUri) continue; - const parsed = parseAtUri(hydrated.uri); - if (!parsed) continue; - const handle = await resolveHandle(parsed.did); - out.push({ - uri: hydrated.uri, - cid: hydrated.cid, - body: value.body, - createdAt: value.createdAt, - author: { did: parsed.did, handle }, - }); - } - out.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); - return out; -} - -function defaultResolveHandle(): (did: string) => Promise { - const cache = new Map>(); - return (did) => { - let promise = cache.get(did); - if (!promise) { - promise = resolveActor(did as ActorIdentifier) - .then((r) => r.handle) - .catch(() => undefined); - cache.set(did, promise); - } - return promise; - }; -} diff --git a/packages/www/src/lib/slingshot.ts b/packages/www/src/lib/slingshot.ts deleted file mode 100644 index 3b93273..0000000 --- a/packages/www/src/lib/slingshot.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { parseAtUri } from './index-event.ts'; - -export const SLINGSHOT_BASE_URL = 'https://slingshot.microcosm.blue'; - -export interface HydratedRecord { - uri: string; - cid: string; - value: unknown; -} - -export interface ResolvedActorMini { - did: string; - handle: string; - pds: string; -} - -export interface SlingshotOptions { - fetch?: typeof fetch; - baseUrl?: string; - signal?: AbortSignal; -} - -export type HydrateOptions = SlingshotOptions; - -export async function hydrateRecord( - atUri: string, - options: HydrateOptions = {}, -): Promise { - const parsed = parseAtUri(atUri); - if (!parsed) return null; - const fetchImpl = options.fetch ?? globalThis.fetch; - const base = options.baseUrl ?? SLINGSHOT_BASE_URL; - const params = new URLSearchParams({ - repo: parsed.did, - collection: parsed.collection, - rkey: parsed.rkey, - }); - const url = `${base}/xrpc/com.atproto.repo.getRecord?${params.toString()}`; - const res = await fetchImpl(url, { signal: options.signal }); - if (res.status === 404) return null; - if (!res.ok) { - throw new Error(`slingshot getRecord failed: ${res.status} ${await res.text()}`); - } - const body = (await res.json()) as HydratedRecord; - return body; -} - -export async function resolveActorViaSlingshot( - identifier: string, - options: SlingshotOptions = {}, -): Promise { - const fetchImpl = options.fetch ?? globalThis.fetch; - const base = options.baseUrl ?? SLINGSHOT_BASE_URL; - const params = new URLSearchParams({ identifier }); - const url = `${base}/xrpc/com.bad-example.identity.resolveMiniDoc?${params.toString()}`; - const res = await fetchImpl(url, { signal: options.signal }); - if (res.status === 400) return null; - if (!res.ok) { - throw new Error(`slingshot resolveMiniDoc failed: ${res.status} ${await res.text()}`); - } - const body = (await res.json()) as { did: string; handle: string; pds: string }; - return { did: body.did, handle: body.handle, pds: body.pds }; -} diff --git a/packages/www/src/lib/spacedust-subscriber.ts b/packages/www/src/lib/spacedust-subscriber.ts deleted file mode 100644 index c98817b..0000000 --- a/packages/www/src/lib/spacedust-subscriber.ts +++ /dev/null @@ -1,202 +0,0 @@ -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; - -import { coldStartFromConstellation } from './cold-start.ts'; -import { getDiscussionRepo } from './discussion.ts'; -import { - createDbOps, - indexDelete, - indexRecord, - TRACKED_COLLECTIONS, -} from './index-event.ts'; -import { hydrateRecord } from './slingshot.ts'; -import { - buildSpacedustSubscribeUrl, - parseSpacedustEvent, - type SpacedustLinkEvent, -} from './spacedust.ts'; - -interface OwnerConfig { - owner: string; - ownerDid: string; - ownerRepoUri: string; -} - -const RECONNECT_BACKOFF_MS = 5_000; -const RECONNECT_BACKOFF_MAX_MS = 60_000; - -const SPACEDUST_SOURCES = [ - 'sh.tangled.repo.pull:target.repo', - 'sh.tangled.repo.pull.comment:pull', - 'sh.tangled.repo.pull.status:pull', - 'sh.tangled.repo.issue:repo', - 'sh.tangled.repo.issue.comment:issue', -]; - -export interface SpacedustEnv { - db: D1Database; -} - -export class SpacedustSubscriber implements DurableObject { - private state: DurableObjectState; - private env: SpacedustEnv; - private ws: WebSocket | null = null; - private connecting = false; - private backoffMs = RECONNECT_BACKOFF_MS; - - constructor(state: DurableObjectState, env: SpacedustEnv) { - this.state = state; - this.env = env; - } - - async fetch(request: Request): Promise { - const url = new URL(request.url); - switch (url.pathname) { - case '/configure': { - const body = (await request.json()) as { owner?: string }; - if (!body.owner) return Response.json({ error: 'owner required' }, { status: 400 }); - const config = await this.resolveOwner(body.owner); - await this.state.storage.put('config', config); - return Response.json({ ok: true, ...config }); - } - case '/start': { - const config = await this.requireConfig(); - if (!config) { - return Response.json({ error: 'not configured' }, { status: 400 }); - } - await this.ensureConnected(config); - return Response.json({ ok: true, connected: this.ws !== null }); - } - case '/stop': { - await this.disconnect(); - await this.state.storage.deleteAlarm(); - return Response.json({ ok: true }); - } - case '/status': { - const config = await this.requireConfig(); - return Response.json({ - configured: config !== null, - connected: this.ws !== null, - connecting: this.connecting, - owner: config?.owner ?? null, - ownerDid: config?.ownerDid ?? null, - ownerRepoUri: config?.ownerRepoUri ?? null, - }); - } - default: - return new Response('not found', { status: 404 }); - } - } - - async alarm(): Promise { - const config = await this.requireConfig(); - if (!config) return; - await this.ensureConnected(config); - } - - async webSocketMessage(_ws: WebSocket, message: string | ArrayBuffer): Promise { - const text = typeof message === 'string' ? message : new TextDecoder().decode(message); - await this.handleEvent(text); - } - - async webSocketClose(): Promise { - await this.handleClose(); - } - - async webSocketError(): Promise { - await this.handleClose(); - } - - private async resolveOwner(owner: string): Promise { - const view = await getDiscussionRepo(owner as ActorIdentifier); - return { - owner, - ownerDid: view.repo.owner.did, - ownerRepoUri: view.repo.uri, - }; - } - - private async requireConfig(): Promise { - const stored = await this.state.storage.get('config'); - return stored ?? null; - } - - private async ensureConnected(config: OwnerConfig): Promise { - if (this.ws || this.connecting) return; - this.connecting = true; - try { - await this.reconcile(config); - const url = buildSpacedustSubscribeUrl({ wantedSources: SPACEDUST_SOURCES }); - const upgraded = await fetch(url, { headers: { Upgrade: 'websocket' } }); - const ws = upgraded.webSocket; - if (!ws) throw new Error('spacedust did not return a websocket'); - this.state.acceptWebSocket(ws); - this.ws = ws; - this.backoffMs = RECONNECT_BACKOFF_MS; - } catch (err) { - console.error('spacedust connect failed', err); - await this.scheduleReconnect(); - } finally { - this.connecting = false; - } - } - - private async disconnect(): Promise { - const ws = this.ws; - this.ws = null; - if (ws) { - try { - ws.close(1000, 'shutdown'); - } catch { - // ignore - } - } - } - - private async handleClose(): Promise { - this.ws = null; - await this.scheduleReconnect(); - } - - private async scheduleReconnect(): Promise { - const delay = this.backoffMs; - this.backoffMs = Math.min(this.backoffMs * 2, RECONNECT_BACKOFF_MAX_MS); - await this.state.storage.setAlarm(Date.now() + delay); - } - - private async handleEvent(raw: string): Promise { - const event = parseSpacedustEvent(raw); - if (!event) return; - const config = await this.requireConfig(); - if (!config) return; - if (!(TRACKED_COLLECTIONS as readonly string[]).includes(event.collection)) return; - try { - await this.applyEvent(event, config); - } catch (err) { - console.error('spacedust event failed', event, err); - } - } - - private async applyEvent(event: SpacedustLinkEvent, config: OwnerConfig): Promise { - const ops = createDbOps(this.env.db); - if (event.operation === 'delete') { - await indexDelete({ uri: event.sourceRecord, collection: event.collection }, ops); - return; - } - const hydrated = await hydrateRecord(event.sourceRecord); - if (!hydrated) return; - await indexRecord( - { - uri: hydrated.uri, - cid: hydrated.cid, - collection: event.collection, - value: hydrated.value, - }, - ops, - config.ownerRepoUri, - ); - } - - private async reconcile(config: OwnerConfig): Promise { - await coldStartFromConstellation(this.env.db, config.owner as ActorIdentifier); - } -} diff --git a/packages/www/src/lib/spacedust.ts b/packages/www/src/lib/spacedust.ts deleted file mode 100644 index bc990f7..0000000 --- a/packages/www/src/lib/spacedust.ts +++ /dev/null @@ -1,87 +0,0 @@ -export const SPACEDUST_BASE_URL = 'wss://spacedust.microcosm.blue'; - -export type SpacedustOperation = 'create' | 'delete'; - -export interface SpacedustLinkEvent { - operation: SpacedustOperation; - source: string; - collection: string; - path: string; - sourceRecord: string; - sourceRev: string; - subject: string; -} - -export interface SpacedustSubscribeFilters { - wantedSources?: string[]; - wantedSubjects?: string[]; - wantedSubjectPrefixes?: string[]; - wantedSubjectDids?: string[]; - baseUrl?: string; -} - -export function parseSourceCollection( - source: string, -): { collection: string; path: string } | null { - const colon = source.indexOf(':'); - if (colon === -1) return null; - return { collection: source.slice(0, colon), path: source.slice(colon + 1) }; -} - -export function parseSpacedustEvent(raw: string): SpacedustLinkEvent | null { - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch { - return null; - } - if (!parsed || typeof parsed !== 'object') return null; - const obj = parsed as Record; - if (obj.kind !== 'link') return null; - const link = obj.link as Record | undefined; - if (!link) return null; - const operation = link.operation; - const source = link.source; - const sourceRecord = link.source_record; - const sourceRev = link.source_rev; - const subject = link.subject; - if ( - (operation !== 'create' && operation !== 'delete') || - typeof source !== 'string' || - typeof sourceRecord !== 'string' || - typeof sourceRev !== 'string' || - typeof subject !== 'string' - ) { - return null; - } - const split = parseSourceCollection(source); - if (!split) return null; - return { - operation, - source, - collection: split.collection, - path: split.path, - sourceRecord, - sourceRev, - subject, - }; -} - -export function buildSpacedustSubscribeUrl(filters: SpacedustSubscribeFilters): string { - const parts: string[] = []; - const append = (key: string, values: string[] | undefined) => { - if (!values) return; - for (const v of values) { - parts.push(`${key}=${encodeURIComponent(v)}`); - } - }; - append('wantedSources', filters.wantedSources); - append('wantedSubjects', filters.wantedSubjects); - append('wantedSubjectPrefixes', filters.wantedSubjectPrefixes); - append('wantedSubjectDids', filters.wantedSubjectDids); - if (parts.length === 0) { - throw new Error('buildSpacedustSubscribeUrl requires at least one filter'); - } - const base = filters.baseUrl ?? SPACEDUST_BASE_URL; - return `${base}/subscribe?${parts.join('&')}`; -} diff --git a/packages/www/src/middleware.ts b/packages/www/src/middleware.ts deleted file mode 100644 index 793d801..0000000 --- a/packages/www/src/middleware.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { defineMiddleware } from 'astro:middleware'; -import { env } from 'cloudflare:workers'; - -// `0001` or `0001-name`. Matches the proposal slug shape used in routes. -const SLUG_RE = /^\d{4}(?:-[a-z0-9][a-z0-9-]*)?$/; - -export const onRequest = defineMiddleware((context, next) => { - const owner = env.RFD_DEFAULT_OWNER?.trim(); - if (!owner) return next(); - - const segments = context.url.pathname.split('/').filter(Boolean); - if (segments.length === 0) { - return context.rewrite(`/${owner}`); - } - if (segments.length === 1 && segments[0] && (segments[0] === 'new' || SLUG_RE.test(segments[0]))) { - return context.rewrite(`/${owner}/${segments[0]}`); - } - - return next(); -}); diff --git a/packages/www/src/pages/[handle].astro b/packages/www/src/pages/[handle].astro deleted file mode 100644 index ed9a4f8..0000000 --- a/packages/www/src/pages/[handle].astro +++ /dev/null @@ -1,75 +0,0 @@ ---- -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; -import { env } from 'cloudflare:workers'; - -import Link from '../components/Link.astro'; -import { NoDiscussionRepoError } from '../lib/discussion.ts'; -import { listProposals } from '../lib/proposal.ts'; - -export const prerender = false; - -const { handle } = Astro.params; -const db = env.db ?? null; - -let view; -let error: string | null = null; -try { - view = await listProposals({ DB: db }, handle as ActorIdentifier); -} catch (err) { - if (err instanceof NoDiscussionRepoError) { - Astro.response.status = 404; - error = err.message; - } else { - Astro.response.status = 500; - error = err instanceof Error ? err.message : String(err); - } -} ---- - - - - - {view ? `${view.repo.name} — st.itch` : `${handle} — st.itch`} - - - -
- st.itch -
-
- {error &&

{error}

} - {view && ( -
-

{view.repo.name}

-

- {view.repo.owner.handle ?? view.repo.owner.did} - {' · '} - {view.repo.knot} -

- {view.repo.description &&

{view.repo.description}

} - -

Proposals ({view.proposals.length})

-

- + New draft proposal -

- {view.proposals.length === 0 && ( -

No proposals yet. Add a 0001-name.md to the repo's default branch, or open a pull adding one.

- )} -
    - {view.proposals.map((p) => ( -
  • - {p.slug} - {' · '} - {p.status} -
  • - ))} -
- -

- View on tangled.org. -

-
- )} -
- - diff --git a/packages/www/src/pages/[handle]/[slug].astro b/packages/www/src/pages/[handle]/[slug].astro deleted file mode 100644 index d03e7c6..0000000 --- a/packages/www/src/pages/[handle]/[slug].astro +++ /dev/null @@ -1,111 +0,0 @@ ---- -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; -import { env } from 'cloudflare:workers'; - -import Link from '../../components/Link.astro'; -import { NoDiscussionRepoError } from '../../lib/discussion.ts'; -import { getProposal } from '../../lib/proposal.ts'; - -export const prerender = false; - -const { handle, slug } = Astro.params; -const db = env.db ?? null; - -let view; -let error: string | null = null; -try { - view = await getProposal({ DB: db }, handle as ActorIdentifier, slug as string); - if (!view) { - Astro.response.status = 404; - error = `proposal not found: ${slug}`; - } -} catch (err) { - if (err instanceof NoDiscussionRepoError) { - Astro.response.status = 404; - error = err.message; - } else { - Astro.response.status = 500; - error = err instanceof Error ? err.message : String(err); - } -} ---- - - - - - {view ? `${view.slug} — st.itch` : 'Proposal — st.itch'} - - - -
- st.itch - {' · '} - {handle} -
-
- {error &&

{error}

} - {view && ( -
-

{view.slug}

-

- Status: {view.status} - {view.content && ( - <> - {' · '} - Source: {view.content.source === 'default' ? 'default branch' : 'open pull'} - - )} -

- - {view.content ? ( -
-

{view.slug}.md

-
{view.content.text}
-
- ) : ( -

No content yet (file isn't on the default branch and no open pull touches it).

- )} - -
-

Pulls ({view.pulls.length})

- {view.pulls.length === 0 &&

No pulls indexed.

} -
    - {view.pulls.map((p) => ( -
  • - {p.title} - {' · '} - {p.state} - {' · '} - {p.author_did} - {' · '} - -
  • - ))} -
-
- -
-

Discussion ({view.discussion.length})

- {view.discussion.length === 0 && ( -

No comments yet.

- )} -
    - {view.discussion.map((c) => ( -
  • -

    - {c.authorDid} - {' · '} - {c.source} - {' · '} - -

    -
    {c.body}
    -
  • - ))} -
-
-
- )} -
- - diff --git a/packages/www/src/pages/[handle]/new.astro b/packages/www/src/pages/[handle]/new.astro deleted file mode 100644 index 9acb735..0000000 --- a/packages/www/src/pages/[handle]/new.astro +++ /dev/null @@ -1,188 +0,0 @@ ---- -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; - -import Link from '../../components/Link.astro'; -import { NoDiscussionRepoError, getDiscussionRepo } from '../../lib/discussion.ts'; - -export const prerender = false; - -const { handle } = Astro.params; - -let view; -let error: string | null = null; -try { - view = await getDiscussionRepo(handle as ActorIdentifier); -} catch (err) { - if (err instanceof NoDiscussionRepoError) { - Astro.response.status = 404; - error = err.message; - } else { - Astro.response.status = 500; - error = err instanceof Error ? err.message : String(err); - } -} - -// Match the shape tangled.org itself writes: `target.repo` is the repo's own -// DID (the `repoDid` field on `sh.tangled.repo`), NOT an at-uri. The lexicon -// declares `format: at-uri` but the appview parser accepts the bare DID form -// and uses it to look up the repo. Our previous "use the at-uri" attempt left -// the pull invisible on tangled.org despite living on the PDS just fine. -const targetMeta = view - ? { - handle, - repoTarget: view.repo.repoDid ?? view.repo.uri, - defaultBranch: view.repo.defaultBranch, - } - : null; ---- - - - - - {view ? `New proposal — ${view.repo.name}` : 'New proposal — st.itch'} - - - -
- st.itch - {' · '} - {handle} -
-
- {error &&

{error}

} - {view && targetMeta && ( -
-

New draft proposal

-

Proposing against {view.repo.name} on {view.repo.knot} (target branch: {view.repo.defaultBranch}).

- - - - - - - - diff --git a/packages/www/src/pages/[handle]/pulls/[rkey].astro b/packages/www/src/pages/[handle]/pulls/[rkey].astro deleted file mode 100644 index c62578c..0000000 --- a/packages/www/src/pages/[handle]/pulls/[rkey].astro +++ /dev/null @@ -1,82 +0,0 @@ ---- -import type { ActorIdentifier } from '@atcute/lexicons/syntax'; - -import { fetchPull } from '../../../lib/pull.ts'; - -export const prerender = false; - -const { handle, rkey } = Astro.params; - -let view; -let error: string | null = null; -try { - view = await fetchPull({ handle: handle as ActorIdentifier, rkey: rkey as string }); -} catch (err) { - Astro.response.status = err instanceof Error && /not found/i.test(err.message) ? 404 : 500; - error = err instanceof Error ? err.message : String(err); -} ---- - - - - - {view ? `${view.pull.title} — st.itch` : `Pull — st.itch`} - - - -
- st.itch - {' · '} - {handle} -
-
- {error &&

{error}

} - {view && ( -
-

{view.pull.title}

-

- {handle} - {' · '} - - {view.repo && ( - <> - {' · '} - {view.repo.name} - - )} -

- {view.pull.body && ( -
-

Description

-
{view.pull.body}
-
- )} - {view.markdown && ( -
-

{view.markdown.path}

-
{view.markdown.content}
-
- )} -
-

Comments ({view.comments.length})

- {view.comments.length === 0 && ( -

No comments yet.

- )} -
    - {view.comments.map((c) => ( -
  • -

    - {c.author.handle ?? c.author.did} - {' · '} - -

    -
    {c.body}
    -
  • - ))} -
-
-
- )} -
- - diff --git a/packages/www/src/pages/[slug].astro b/packages/www/src/pages/[slug].astro new file mode 100644 index 0000000..cdb40d4 --- /dev/null +++ b/packages/www/src/pages/[slug].astro @@ -0,0 +1,64 @@ +--- +import Base from '../layouts/Base.astro'; +import Discussion from '../components/Discussion.astro'; +import { getProposalCached } from '../config.ts'; + +export const prerender = false; + +const { slug } = Astro.params; +let detail: Awaited> = null; +let error: string | null = null; +try { + detail = await getProposalCached(slug as string); + if (!detail) { + Astro.response.status = 404; + error = `proposal not found: ${slug}`; + } +} catch (err) { + Astro.response.status = 500; + error = err instanceof Error ? err.message : String(err); +} + +const pullUris = detail ? detail.pulls.map((p) => p.uri) : []; +--- + + {error &&

{error}

} + {detail && ( +
+

{detail.slug}

+

Status: {detail.status}

+ + {detail.content ? ( +
{detail.content.text}
+ ) : ( +

No committed content yet — see the open pull below.

+ )} + +
+

Pulls ({detail.pulls.length})

+
    + {detail.pulls.map((p) => ( +
  • + {p.state} · {p.value.title} + {' · '}{p.commentCount} comments +
  • + ))} +
+
+ + +

Loading discussion…

+
+ + {pullUris.length > 0 && ( + +
+ + + +
+
+ )} +
+ )} + diff --git a/packages/www/src/pages/api/v0/healthz.ts b/packages/www/src/pages/api/v0/healthz.ts new file mode 100644 index 0000000..c28c339 --- /dev/null +++ b/packages/www/src/pages/api/v0/healthz.ts @@ -0,0 +1,8 @@ +import type { APIRoute } from 'astro'; + +export const prerender = false; + +export const GET: APIRoute = () => + new Response(JSON.stringify({ ok: true }), { + headers: { 'content-type': 'application/json' }, + }); diff --git a/packages/www/src/pages/api/v0/proposals.ts b/packages/www/src/pages/api/v0/proposals.ts new file mode 100644 index 0000000..e0b8d59 --- /dev/null +++ b/packages/www/src/pages/api/v0/proposals.ts @@ -0,0 +1,15 @@ +import type { APIRoute } from 'astro'; +import { listProposalsCached } from '../../../config.ts'; + +export const prerender = false; + +export const GET: APIRoute = async () => { + try { + const proposals = await listProposalsCached(); + return new Response(JSON.stringify({ proposals }), { headers: { 'content-type': 'application/json' } }); + } catch (err) { + return new Response(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }), { + status: 500, headers: { 'content-type': 'application/json' }, + }); + } +}; diff --git a/packages/www/src/pages/api/v0/proposals/[slug].ts b/packages/www/src/pages/api/v0/proposals/[slug].ts new file mode 100644 index 0000000..6262237 --- /dev/null +++ b/packages/www/src/pages/api/v0/proposals/[slug].ts @@ -0,0 +1,18 @@ +import type { APIRoute } from 'astro'; +import { getProposalCached } from '../../../../config.ts'; + +export const prerender = false; + +export const GET: APIRoute = async ({ params }) => { + try { + const proposal = await getProposalCached(params.slug as string); + if (!proposal) { + return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } }); + } + return new Response(JSON.stringify({ proposal }), { headers: { 'content-type': 'application/json' } }); + } catch (err) { + return new Response(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }), { + status: 500, headers: { 'content-type': 'application/json' }, + }); + } +}; diff --git a/packages/www/src/pages/index.astro b/packages/www/src/pages/index.astro index 082e9fa..6dc3d6c 100644 --- a/packages/www/src/pages/index.astro +++ b/packages/www/src/pages/index.astro @@ -1,36 +1,32 @@ --- +import Base from '../layouts/Base.astro'; +import Link from '../components/Link.astro'; +import { getRfd, listProposalsCached } from '../config.ts'; + +export const prerender = false; + +let proposals: Awaited> = []; +let repoName = 'rfd'; +let error: string | null = null; +try { + const [list, repo] = await Promise.all([listProposalsCached(), getRfd().getRepo()]); + proposals = list; + repoName = repo.value.name; +} catch (err) { + Astro.response.status = 500; + error = err instanceof Error ? err.message : String(err); +} --- - - - - - - - st.itch — RFDs over atproto - - -
-

st.itch

-

Hosted RFCs riding on atproto + tangled.

-
- - -
-

- Or sign in to claim your discussion repo. -

-
- - - + +

{repoName}

+ {error &&

{error}

} + {!error && proposals.length === 0 &&

No proposals yet. Draft one →

} +
    + {proposals.map((p) => ( +
  • + {p.slug} + {p.status} +
  • + ))} +
+ diff --git a/packages/www/src/pages/new.astro b/packages/www/src/pages/new.astro new file mode 100644 index 0000000..376fd14 --- /dev/null +++ b/packages/www/src/pages/new.astro @@ -0,0 +1,36 @@ +--- +import Base from '../layouts/Base.astro'; +import Link from '../components/Link.astro'; +import { getRfd } from '../config.ts'; + +export const prerender = false; + +let repoTarget = ''; +let defaultBranch = 'main'; +let repoName = 'rfd'; +let error: string | null = null; +try { + const [ctx, repo] = await Promise.all([getRfd().getContext(), getRfd().getRepo()]); + repoTarget = ctx.repoDid; + repoName = repo.value.name; +} catch (err) { + Astro.response.status = 500; + error = err instanceof Error ? err.message : String(err); +} +--- + +

New draft proposal

+ {error &&

{error}

} + {!error && ( + + +
+

+

+

Will create 0000-….md

+

+ +
+
+ )} + diff --git a/packages/www/src/pages/oauth/client-metadata.json.ts b/packages/www/src/pages/oauth/client-metadata.json.ts index 2bb2f52..859594e 100644 --- a/packages/www/src/pages/oauth/client-metadata.json.ts +++ b/packages/www/src/pages/oauth/client-metadata.json.ts @@ -9,7 +9,8 @@ export const GET: APIRoute = ({ url }) => { client_name: 'st.itch RFD', client_uri: origin, redirect_uris: [`${origin}/settings/oauth/callback`], - scope: 'atproto transition:generic', + // Keep in sync with SCOPE in src/lib/oauth.ts. + scope: 'atproto repo:sh.tangled.feed.comment repo:sh.tangled.repo.pull blob:application/gzip', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', diff --git a/packages/www/src/pages/pulls/[rkey].astro b/packages/www/src/pages/pulls/[rkey].astro new file mode 100644 index 0000000..f5d0bce --- /dev/null +++ b/packages/www/src/pages/pulls/[rkey].astro @@ -0,0 +1,27 @@ +--- +import Base from '../../layouts/Base.astro'; +import { getRfd } from '../../config.ts'; + +export const prerender = false; + +const { rkey } = Astro.params; +let pull: Awaited['getPull']>> | null = null; +let error: string | null = null; +try { + const ctx = await getRfd().getContext(); + const uri = `at://${ctx.ownerDid}/sh.tangled.repo.pull/${rkey}`; + pull = await getRfd().getPull(uri); +} catch (err) { + Astro.response.status = 500; + error = err instanceof Error ? err.message : String(err); +} +--- + + {error &&

{error}

} + {pull && ( +
+

{pull.value.title}

+ {pull.value.body &&
{pull.value.body}
} +
+ )} + diff --git a/packages/www/src/pages/settings/claim.astro b/packages/www/src/pages/settings/claim.astro deleted file mode 100644 index c66fa78..0000000 --- a/packages/www/src/pages/settings/claim.astro +++ /dev/null @@ -1,104 +0,0 @@ ---- ---- - - - - - Pick your discussion repo — st.itch - - - -
-

Pick your discussion repo

-

Loading your tangled repos…

- - - - -
- - - diff --git a/packages/www/src/pages/settings/login.astro b/packages/www/src/pages/settings/login.astro index 2b48c34..e5d5a8b 100644 --- a/packages/www/src/pages/settings/login.astro +++ b/packages/www/src/pages/settings/login.astro @@ -1,41 +1,15 @@ --- +import Base from '../../layouts/Base.astro'; +export const prerender = false; --- - - - - - Sign in — st.itch - - - -
-

Sign in

-
- - -
- -
- - - + +

Sign in

+ +
+ +

+
+
+ diff --git a/packages/www/src/pages/settings/oauth/callback.astro b/packages/www/src/pages/settings/oauth/callback.astro index b556bba..4dfa457 100644 --- a/packages/www/src/pages/settings/oauth/callback.astro +++ b/packages/www/src/pages/settings/oauth/callback.astro @@ -1,31 +1,9 @@ --- +import Base from '../../../layouts/Base.astro'; +export const prerender = false; --- - - - - - Signing in… — st.itch - - - -
-

Finishing sign-in…

- -
- - - + + +

Completing sign-in…

+
+ diff --git a/packages/www/src/styles/tokens.css b/packages/www/src/styles/tokens.css new file mode 100644 index 0000000..ee2db06 --- /dev/null +++ b/packages/www/src/styles/tokens.css @@ -0,0 +1,56 @@ +:root { + --font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --font-mono: ui-monospace, "SF Mono", "Cascadia Code", Menlo, monospace; + + --color-bg: #ffffff; + --color-fg: #1a1a1a; + --color-muted: #6b7280; + --color-border: #e5e7eb; + --color-accent: #2563eb; + --color-surface: #f9fafb; + + --space-1: 0.25rem; + --space-2: 0.5rem; + --space-3: 1rem; + --space-4: 1.5rem; + --space-5: 2.5rem; + + --radius: 0.5rem; + --measure: 42rem; + + --text-sm: 0.875rem; + --text-base: 1rem; + --text-lg: 1.25rem; + --text-xl: 1.75rem; +} + +@media (prefers-color-scheme: dark) { + :root { + --color-bg: #0d0d0f; + --color-fg: #ededed; + --color-muted: #9ca3af; + --color-border: #26262b; + --color-accent: #60a5fa; + --color-surface: #16161a; + } +} + +* { box-sizing: border-box; } +body { + margin: 0; + font-family: var(--font-sans); + color: var(--color-fg); + background: var(--color-bg); + line-height: 1.55; +} +main { max-width: var(--measure); margin: 0 auto; padding: var(--space-4) var(--space-3); } +a { color: var(--color-accent); } +code, pre { font-family: var(--font-mono); font-size: var(--text-sm); } +pre { + background: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius); + padding: var(--space-3); + overflow: auto; + white-space: pre-wrap; +} diff --git a/packages/www/test/cache.test.ts b/packages/www/test/cache.test.ts new file mode 100644 index 0000000..e8e8924 --- /dev/null +++ b/packages/www/test/cache.test.ts @@ -0,0 +1,38 @@ +import { expect, test, vi } from 'vitest'; +import { createCache } from '../src/lib/cache.ts'; + +test('caches within the TTL and refetches after expiry', async () => { + let now = 1000; + const cache = createCache({ nowMs: () => now }); + const fn = vi.fn(async () => ({ n: fn.mock.calls.length })); + + const a = await cache.wrap('k', 60, fn); + const b = await cache.wrap('k', 60, fn); + expect(a).toBe(b); // same cached value + expect(fn).toHaveBeenCalledTimes(1); + + now += 61_000; // past TTL + const c = await cache.wrap('k', 60, fn); + expect(fn).toHaveBeenCalledTimes(2); + expect(c).not.toBe(a); +}); + +test('different keys are independent', async () => { + const cache = createCache({ nowMs: () => 0 }); + const fn = vi.fn(async (k: string) => k.toUpperCase()); + expect(await cache.wrap('a', 60, () => fn('a'))).toBe('A'); + expect(await cache.wrap('b', 60, () => fn('b'))).toBe('B'); + expect(fn).toHaveBeenCalledTimes(2); +}); + +test('a rejected fn is not cached', async () => { + const cache = createCache({ nowMs: () => 0 }); + let calls = 0; + const fn = async () => { + calls++; + if (calls === 1) throw new Error('boom'); + return 'ok'; + }; + await expect(cache.wrap('k', 60, fn)).rejects.toThrow('boom'); + expect(await cache.wrap('k', 60, fn)).toBe('ok'); +}); diff --git a/packages/www/test/constellation.test.ts b/packages/www/test/constellation.test.ts deleted file mode 100644 index 261067f..0000000 --- a/packages/www/test/constellation.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; - -import { - buildLinksUrl, - listLinkingRecords, - recordIdToAtUri, -} from '../src/lib/constellation.ts'; - -describe('buildLinksUrl', () => { - it('encodes target, collection, and path', () => { - const url = buildLinksUrl({ - target: 'at://did:plc:owner/sh.tangled.repo/self', - collection: 'sh.tangled.repo.pull', - path: '.target.repo', - }); - expect(url).toBe( - 'https://constellation.microcosm.blue/links?target=at%3A%2F%2Fdid%3Aplc%3Aowner%2Fsh.tangled.repo%2Fself&collection=sh.tangled.repo.pull&path=.target.repo', - ); - }); - - it('appends cursor and limit when provided', () => { - const url = buildLinksUrl({ - target: 'did:plc:owner', - collection: 'sh.tangled.repo.pull', - path: '.target.repo', - cursor: 'opaque-cursor', - limit: 50, - }); - expect(url).toContain('&cursor=opaque-cursor'); - expect(url).toContain('&limit=50'); - }); -}); - -describe('recordIdToAtUri', () => { - it('formats did/collection/rkey as at-uri', () => { - expect( - recordIdToAtUri({ - did: 'did:plc:author', - collection: 'sh.tangled.repo.pull.comment', - rkey: 'abc123', - }), - ).toBe('at://did:plc:author/sh.tangled.repo.pull.comment/abc123'); - }); -}); - -describe('listLinkingRecords', () => { - it('paginates through cursors and yields at-uris', async () => { - const fetchMock = vi - .fn() - .mockResolvedValueOnce( - new Response( - JSON.stringify({ - total: 3, - linking_records: [ - { did: 'did:plc:a', collection: 'sh.tangled.repo.pull', rkey: 'r1' }, - { did: 'did:plc:b', collection: 'sh.tangled.repo.pull', rkey: 'r2' }, - ], - cursor: 'next-page', - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ), - ) - .mockResolvedValueOnce( - new Response( - JSON.stringify({ - total: 3, - linking_records: [ - { did: 'did:plc:c', collection: 'sh.tangled.repo.pull', rkey: 'r3' }, - ], - cursor: null, - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ), - ); - - const out: string[] = []; - for await (const uri of listLinkingRecords( - { - target: 'at://did:plc:owner/sh.tangled.repo/self', - collection: 'sh.tangled.repo.pull', - path: '.target.repo', - }, - { fetch: fetchMock as unknown as typeof fetch }, - )) { - out.push(uri); - } - - expect(out).toEqual([ - 'at://did:plc:a/sh.tangled.repo.pull/r1', - 'at://did:plc:b/sh.tangled.repo.pull/r2', - 'at://did:plc:c/sh.tangled.repo.pull/r3', - ]); - expect(fetchMock).toHaveBeenCalledTimes(2); - expect((fetchMock.mock.calls[1][0] as string)).toContain('cursor=next-page'); - }); - - it('throws on non-2xx response', async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response('boom', { status: 500 })); - const iter = listLinkingRecords( - { - target: 'did:plc:owner', - collection: 'sh.tangled.repo.pull', - path: '.target.repo', - }, - { fetch: fetchMock as unknown as typeof fetch }, - ); - await expect(iter.next()).rejects.toThrow(/constellation/i); - }); -}); diff --git a/packages/www/test/draft.test.ts b/packages/www/test/draft.test.ts index d19069a..2338371 100644 --- a/packages/www/test/draft.test.ts +++ b/packages/www/test/draft.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { listMarkdownFilesInDiff } from '../src/lib/patch.ts'; import { buildPatch, gitBlobSha1, slugify } from '../src/lib/draft.ts'; describe('slugify', () => { @@ -39,7 +38,9 @@ describe('gitBlobSha1', () => { }); describe('buildPatch', () => { - it('produces output our own listMarkdownFilesInDiff round-trips', async () => { + // Diff *parsing* (round-trip) is owned and tested by @rfd/core (patch.test.ts); + // here we only assert buildPatch emits a well-formed git format-patch. + it('produces a git format-patch that adds the file', async () => { const body = '# Hello\n\nworld'; const patch = await buildPatch({ title: 'Hello world', @@ -49,24 +50,19 @@ describe('buildPatch', () => { expect(patch.startsWith('From ')).toBe(true); expect(patch).toMatch(/Mon Sep 17 00:00:00 2001/); expect(patch).toContain('Subject: [PATCH] Hello world'); + expect(patch).toContain('new file mode 100644'); expect(patch).toContain('+++ b/0000-hello-world.md'); - const entries = listMarkdownFilesInDiff(patch); - expect(entries).toHaveLength(1); - expect(entries[0]!.path).toBe('0000-hello-world.md'); - expect(entries[0]!.isNew).toBe(true); - expect(entries[0]!.content).toBe(body); + expect(patch).toContain('+# Hello'); }); - it('handles an empty body', async () => { + it('handles an empty body (no hunk)', async () => { const patch = await buildPatch({ title: 'Empty', body: '', fileName: '0000-empty.md', }); - const entries = listMarkdownFilesInDiff(patch); - expect(entries).toHaveLength(1); - expect(entries[0]!.path).toBe('0000-empty.md'); - expect(entries[0]!.isNew).toBe(true); - expect(entries[0]!.content).toBe(''); + expect(patch).toContain('+++ b/0000-empty.md'); + expect(patch).toContain('create mode 100644 0000-empty.md'); + expect(patch).not.toContain('@@'); }); }); diff --git a/packages/www/test/index-event.test.ts b/packages/www/test/index-event.test.ts deleted file mode 100644 index df0e6c6..0000000 --- a/packages/www/test/index-event.test.ts +++ /dev/null @@ -1,217 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; - -import { indexRecord, indexDelete, parseAtUri } from '../src/lib/index-event.ts'; -import type { IndexerOps } from '../src/lib/index-event.ts'; - -const OWNER_REPO_URI = 'at://did:plc:owner/sh.tangled.repo/self'; - -function makeOps(overrides: Partial = {}): IndexerOps { - return { - upsertPull: vi.fn().mockResolvedValue(undefined), - upsertComment: vi.fn().mockResolvedValue(undefined), - setPullState: vi.fn().mockResolvedValue(undefined), - upsertIssue: vi.fn().mockResolvedValue(undefined), - upsertIssueComment: vi.fn().mockResolvedValue(undefined), - pullExists: vi.fn().mockResolvedValue(true), - issueExists: vi.fn().mockResolvedValue(true), - replacePullFiles: vi.fn().mockResolvedValue(undefined), - deleteByUri: vi.fn().mockResolvedValue(undefined), - ...overrides, - }; -} - -describe('parseAtUri', () => { - it('splits did/collection/rkey', () => { - expect(parseAtUri('at://did:plc:abc/sh.tangled.repo.pull/r1')).toEqual({ - did: 'did:plc:abc', - collection: 'sh.tangled.repo.pull', - rkey: 'r1', - }); - }); - - it('returns null for malformed uris', () => { - expect(parseAtUri('https://example.com/foo')).toBeNull(); - expect(parseAtUri('at://did:plc:abc/only-collection')).toBeNull(); - }); -}); - -describe('indexRecord', () => { - it('routes pulls targeting the owner repo to upsertPull', async () => { - const ops = makeOps(); - const result = await indexRecord( - { - uri: 'at://did:plc:author/sh.tangled.repo.pull/r1', - cid: 'bafy1', - collection: 'sh.tangled.repo.pull', - value: { - $type: 'sh.tangled.repo.pull', - title: 'Add RFD 0042', - target: { repo: OWNER_REPO_URI, branch: 'main' }, - rounds: [], - createdAt: '2026-05-10T00:00:00Z', - }, - }, - ops, - OWNER_REPO_URI, - ); - - expect(result).toBe('indexed'); - expect(ops.upsertPull).toHaveBeenCalledWith( - 'did:plc:author', - 'at://did:plc:author/sh.tangled.repo.pull/r1', - 'bafy1', - expect.objectContaining({ title: 'Add RFD 0042' }), - ); - }); - - it('skips pulls targeting other repos', async () => { - const ops = makeOps(); - const result = await indexRecord( - { - uri: 'at://did:plc:author/sh.tangled.repo.pull/r1', - cid: 'bafy1', - collection: 'sh.tangled.repo.pull', - value: { - target: { repo: 'at://did:plc:elsewhere/sh.tangled.repo/self', branch: 'main' }, - rounds: [], - title: 't', - createdAt: '2026-05-10T00:00:00Z', - }, - }, - ops, - OWNER_REPO_URI, - ); - - expect(result).toBe('skipped'); - expect(ops.upsertPull).not.toHaveBeenCalled(); - }); - - it('skips comments when their pull is not in our index', async () => { - const ops = makeOps({ pullExists: vi.fn().mockResolvedValue(false) }); - const result = await indexRecord( - { - uri: 'at://did:plc:b/sh.tangled.repo.pull.comment/c1', - cid: 'bafy2', - collection: 'sh.tangled.repo.pull.comment', - value: { - pull: 'at://did:plc:author/sh.tangled.repo.pull/unknown', - body: 'hi', - createdAt: '2026-05-10T00:00:00Z', - }, - }, - ops, - OWNER_REPO_URI, - ); - - expect(result).toBe('skipped'); - expect(ops.upsertComment).not.toHaveBeenCalled(); - }); - - it('routes comments on tracked pulls', async () => { - const ops = makeOps(); - const result = await indexRecord( - { - uri: 'at://did:plc:b/sh.tangled.repo.pull.comment/c1', - cid: 'bafy2', - collection: 'sh.tangled.repo.pull.comment', - value: { - pull: 'at://did:plc:author/sh.tangled.repo.pull/r1', - body: 'looks good', - createdAt: '2026-05-10T00:00:00Z', - }, - }, - ops, - OWNER_REPO_URI, - ); - - expect(result).toBe('indexed'); - expect(ops.upsertComment).toHaveBeenCalled(); - }); - - it('routes pull statuses to setPullState', async () => { - const ops = makeOps(); - await indexRecord( - { - uri: 'at://did:plc:author/sh.tangled.repo.pull.status/s1', - cid: 'bafy3', - collection: 'sh.tangled.repo.pull.status', - value: { - pull: 'at://did:plc:author/sh.tangled.repo.pull/r1', - status: 'sh.tangled.repo.pull.status.merged', - createdAt: '2026-05-10T01:00:00Z', - }, - }, - ops, - OWNER_REPO_URI, - ); - - expect(ops.setPullState).toHaveBeenCalledWith( - 'at://did:plc:author/sh.tangled.repo.pull/r1', - 'merged', - '2026-05-10T01:00:00Z', - ); - }); - - it('routes issues targeting the owner repo to upsertIssue', async () => { - const ops = makeOps(); - await indexRecord( - { - uri: 'at://did:plc:author/sh.tangled.repo.issue/i1', - cid: 'bafy4', - collection: 'sh.tangled.repo.issue', - value: { - title: '[0042] An issue', - repo: OWNER_REPO_URI, - createdAt: '2026-05-10T00:00:00Z', - }, - }, - ops, - OWNER_REPO_URI, - ); - - expect(ops.upsertIssue).toHaveBeenCalled(); - }); - - it('returns unsupported for unrelated collections', async () => { - const ops = makeOps(); - const result = await indexRecord( - { - uri: 'at://did:plc:author/app.bsky.feed.post/r1', - cid: 'bafyx', - collection: 'app.bsky.feed.post', - value: {}, - }, - ops, - OWNER_REPO_URI, - ); - expect(result).toBe('unsupported'); - }); -}); - -describe('indexDelete', () => { - it('calls deleteByUri for known collections', async () => { - const ops = makeOps(); - const result = await indexDelete( - { - uri: 'at://did:plc:b/sh.tangled.repo.pull.comment/c1', - collection: 'sh.tangled.repo.pull.comment', - }, - ops, - ); - expect(result).toBe('deleted'); - expect(ops.deleteByUri).toHaveBeenCalledWith( - 'sh.tangled.repo.pull.comment', - 'at://did:plc:b/sh.tangled.repo.pull.comment/c1', - ); - }); - - it('returns unsupported for unrelated collections', async () => { - const ops = makeOps(); - const result = await indexDelete( - { uri: 'at://did:plc:author/app.bsky.feed.post/r1', collection: 'app.bsky.feed.post' }, - ops, - ); - expect(result).toBe('unsupported'); - expect(ops.deleteByUri).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/www/test/pull-comments.test.ts b/packages/www/test/pull-comments.test.ts deleted file mode 100644 index 0fbdf1a..0000000 --- a/packages/www/test/pull-comments.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; - -import { collectCommentsFor } from '../src/lib/pull.ts'; - -const PULL_URI = 'at://did:plc:owner/sh.tangled.repo.pull/r1'; - -async function* asyncIter(items: T[]): AsyncGenerator { - for (const item of items) yield item; -} - -describe('collectCommentsFor', () => { - it('hydrates each at-uri returned by Constellation and sorts by createdAt', async () => { - const hydrate = vi - .fn() - .mockResolvedValueOnce({ - uri: 'at://did:plc:b/sh.tangled.repo.pull.comment/c2', - cid: 'bafy2', - value: { pull: PULL_URI, body: 'second', createdAt: '2026-05-10T01:00:00Z' }, - }) - .mockResolvedValueOnce({ - uri: 'at://did:plc:a/sh.tangled.repo.pull.comment/c1', - cid: 'bafy1', - value: { pull: PULL_URI, body: 'first', createdAt: '2026-05-10T00:00:00Z' }, - }); - - const comments = await collectCommentsFor(PULL_URI, { - listLinks: () => - asyncIter([ - 'at://did:plc:b/sh.tangled.repo.pull.comment/c2', - 'at://did:plc:a/sh.tangled.repo.pull.comment/c1', - ]), - hydrate, - resolveHandle: async () => undefined, - }); - - expect(comments.map((c) => c.body)).toEqual(['first', 'second']); - expect(comments[0].author).toEqual({ did: 'did:plc:a', handle: undefined }); - expect(comments[1].author).toEqual({ did: 'did:plc:b', handle: undefined }); - }); - - it('resolves handles via the injected resolver', async () => { - const hydrate = vi.fn().mockResolvedValue({ - uri: 'at://did:plc:a/sh.tangled.repo.pull.comment/c1', - cid: 'bafy1', - value: { pull: PULL_URI, body: 'hi', createdAt: '2026-05-10T00:00:00Z' }, - }); - const resolveHandle = vi.fn().mockResolvedValue('alice.example'); - - const comments = await collectCommentsFor(PULL_URI, { - listLinks: () => asyncIter(['at://did:plc:a/sh.tangled.repo.pull.comment/c1']), - hydrate, - resolveHandle, - }); - - expect(comments[0].author).toEqual({ did: 'did:plc:a', handle: 'alice.example' }); - expect(resolveHandle).toHaveBeenCalledWith('did:plc:a'); - }); - - it('skips comments whose pull field does not match the requested pull (defensive)', async () => { - const hydrate = vi.fn().mockResolvedValue({ - uri: 'at://did:plc:b/sh.tangled.repo.pull.comment/c1', - cid: 'bafy1', - value: { - pull: 'at://did:plc:other/sh.tangled.repo.pull/elsewhere', - body: 'not for us', - createdAt: '2026-05-10T00:00:00Z', - }, - }); - - const comments = await collectCommentsFor(PULL_URI, { - listLinks: () => asyncIter(['at://did:plc:b/sh.tangled.repo.pull.comment/c1']), - hydrate, - resolveHandle: async () => undefined, - }); - - expect(comments).toEqual([]); - }); - - it('skips at-uris whose hydrate returns null (deleted / missing record)', async () => { - const hydrate = vi.fn().mockResolvedValue(null); - - const comments = await collectCommentsFor(PULL_URI, { - listLinks: () => asyncIter(['at://did:plc:b/sh.tangled.repo.pull.comment/gone']), - hydrate, - resolveHandle: async () => undefined, - }); - - expect(comments).toEqual([]); - }); -}); diff --git a/packages/www/test/resolve-actor.test.ts b/packages/www/test/resolve-actor.test.ts deleted file mode 100644 index 3ee9cae..0000000 --- a/packages/www/test/resolve-actor.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; - -import { resolveActorViaSlingshot } from '../src/lib/slingshot.ts'; - -describe('resolveActorViaSlingshot', () => { - it('returns did/handle/pds from a successful response', async () => { - const fetchMock = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - did: 'did:plc:abc', - handle: 'alice.example', - pds: 'https://pds.example', - signing_key: 'multibase...', - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ), - ); - - const actor = await resolveActorViaSlingshot('alice.example', { - fetch: fetchMock as unknown as typeof fetch, - }); - - expect(actor).toEqual({ - did: 'did:plc:abc', - handle: 'alice.example', - pds: 'https://pds.example', - }); - const calledUrl = fetchMock.mock.calls[0][0] as string; - expect(calledUrl).toContain( - 'https://slingshot.microcosm.blue/xrpc/com.bad-example.identity.resolveMiniDoc', - ); - expect(calledUrl).toContain('identifier=alice.example'); - }); - - it('url-encodes DID identifiers (with colons)', async () => { - const fetchMock = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - did: 'did:plc:abc', - handle: 'alice.example', - pds: 'https://pds.example', - signing_key: 'k', - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ), - ); - - await resolveActorViaSlingshot('did:plc:abc', { - fetch: fetchMock as unknown as typeof fetch, - }); - - expect(fetchMock.mock.calls[0][0] as string).toContain('identifier=did%3Aplc%3Aabc'); - }); - - it('returns null on 400 (identity not resolved)', async () => { - const fetchMock = vi.fn().mockResolvedValue( - new Response(JSON.stringify({ error: 'HandleNotFound' }), { status: 400 }), - ); - - const actor = await resolveActorViaSlingshot('missing.example', { - fetch: fetchMock as unknown as typeof fetch, - }); - - expect(actor).toBeNull(); - }); - - it('throws on other non-2xx responses', async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response('boom', { status: 500 })); - - await expect( - resolveActorViaSlingshot('alice.example', { - fetch: fetchMock as unknown as typeof fetch, - }), - ).rejects.toThrow(/slingshot/i); - }); -}); diff --git a/packages/www/test/slingshot.test.ts b/packages/www/test/slingshot.test.ts deleted file mode 100644 index 86e08ca..0000000 --- a/packages/www/test/slingshot.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; - -import { hydrateRecord } from '../src/lib/slingshot.ts'; - -describe('hydrateRecord', () => { - it('fetches getRecord from slingshot using did/collection/rkey from the at-uri', async () => { - const fetchMock = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - uri: 'at://did:plc:author/sh.tangled.repo.pull/r1', - cid: 'bafy1', - value: { title: 't' }, - }), - { status: 200, headers: { 'content-type': 'application/json' } }, - ), - ); - - const record = await hydrateRecord( - 'at://did:plc:author/sh.tangled.repo.pull/r1', - { fetch: fetchMock as unknown as typeof fetch }, - ); - - expect(record).toEqual({ - uri: 'at://did:plc:author/sh.tangled.repo.pull/r1', - cid: 'bafy1', - value: { title: 't' }, - }); - const calledUrl = fetchMock.mock.calls[0][0] as string; - expect(calledUrl).toContain('https://slingshot.microcosm.blue/xrpc/com.atproto.repo.getRecord'); - expect(calledUrl).toContain('repo=did%3Aplc%3Aauthor'); - expect(calledUrl).toContain('collection=sh.tangled.repo.pull'); - expect(calledUrl).toContain('rkey=r1'); - }); - - it('returns null on 404 (record absent / deleted)', async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response('not found', { status: 404 })); - const record = await hydrateRecord( - 'at://did:plc:author/sh.tangled.repo.pull/missing', - { fetch: fetchMock as unknown as typeof fetch }, - ); - expect(record).toBeNull(); - }); - - it('returns null for malformed at-uri', async () => { - const fetchMock = vi.fn(); - const record = await hydrateRecord('not-an-at-uri', { - fetch: fetchMock as unknown as typeof fetch, - }); - expect(record).toBeNull(); - expect(fetchMock).not.toHaveBeenCalled(); - }); - - it('throws on other non-2xx responses', async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response('boom', { status: 500 })); - await expect( - hydrateRecord('at://did:plc:a/sh.tangled.repo.pull/r1', { - fetch: fetchMock as unknown as typeof fetch, - }), - ).rejects.toThrow(/slingshot/i); - }); -}); diff --git a/packages/www/test/spacedust.test.ts b/packages/www/test/spacedust.test.ts deleted file mode 100644 index 7b12641..0000000 --- a/packages/www/test/spacedust.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { - buildSpacedustSubscribeUrl, - parseSpacedustEvent, - parseSourceCollection, -} from '../src/lib/spacedust.ts'; - -describe('parseSpacedustEvent', () => { - it('parses a create link event', () => { - const raw = JSON.stringify({ - kind: 'link', - origin: 'live', - link: { - operation: 'create', - source: 'sh.tangled.repo.pull.comment:pull', - source_record: 'at://did:plc:author/sh.tangled.repo.pull.comment/abc', - source_rev: '3l5xyz', - subject: 'at://did:plc:owner/sh.tangled.repo.pull/123', - }, - }); - - const event = parseSpacedustEvent(raw); - - expect(event).toEqual({ - operation: 'create', - source: 'sh.tangled.repo.pull.comment:pull', - collection: 'sh.tangled.repo.pull.comment', - path: 'pull', - sourceRecord: 'at://did:plc:author/sh.tangled.repo.pull.comment/abc', - sourceRev: '3l5xyz', - subject: 'at://did:plc:owner/sh.tangled.repo.pull/123', - }); - }); - - it('parses a delete link event', () => { - const raw = JSON.stringify({ - kind: 'link', - origin: 'live', - link: { - operation: 'delete', - source: 'sh.tangled.repo.pull:target.repo', - source_record: 'at://did:plc:author/sh.tangled.repo.pull/xyz', - source_rev: '3l5abc', - subject: 'at://did:plc:owner/sh.tangled.repo/self', - }, - }); - - const event = parseSpacedustEvent(raw); - - expect(event?.operation).toBe('delete'); - expect(event?.collection).toBe('sh.tangled.repo.pull'); - expect(event?.path).toBe('target.repo'); - }); - - it('returns null for non-link events', () => { - const raw = JSON.stringify({ kind: 'something_else' }); - expect(parseSpacedustEvent(raw)).toBeNull(); - }); - - it('returns null for malformed JSON', () => { - expect(parseSpacedustEvent('{not json')).toBeNull(); - }); - - it('returns null when link payload is missing required fields', () => { - const raw = JSON.stringify({ kind: 'link', origin: 'live', link: { operation: 'create' } }); - expect(parseSpacedustEvent(raw)).toBeNull(); - }); -}); - -describe('parseSourceCollection', () => { - it('splits collection from path', () => { - expect(parseSourceCollection('sh.tangled.repo.pull.comment:pull')).toEqual({ - collection: 'sh.tangled.repo.pull.comment', - path: 'pull', - }); - }); - - it('handles dotted paths', () => { - expect(parseSourceCollection('sh.tangled.repo.pull:target.repo')).toEqual({ - collection: 'sh.tangled.repo.pull', - path: 'target.repo', - }); - }); - - it('returns null when no colon is present', () => { - expect(parseSourceCollection('sh.tangled.repo.pull')).toBeNull(); - }); -}); - -describe('buildSpacedustSubscribeUrl', () => { - it('encodes wantedSources as repeated params', () => { - const url = buildSpacedustSubscribeUrl({ - wantedSources: [ - 'sh.tangled.repo.pull:target.repo', - 'sh.tangled.repo.pull.comment:pull', - ], - }); - - expect(url).toBe( - 'wss://spacedust.microcosm.blue/subscribe?wantedSources=sh.tangled.repo.pull%3Atarget.repo&wantedSources=sh.tangled.repo.pull.comment%3Apull', - ); - }); - - it('combines wantedSources with wantedSubjectDids', () => { - const url = buildSpacedustSubscribeUrl({ - wantedSources: ['sh.tangled.repo.pull:target.repo'], - wantedSubjectDids: ['did:plc:owner'], - }); - - expect(url).toContain('wantedSources=sh.tangled.repo.pull%3Atarget.repo'); - expect(url).toContain('wantedSubjectDids=did%3Aplc%3Aowner'); - }); - - it('throws when no filter is provided', () => { - expect(() => buildSpacedustSubscribeUrl({})).toThrow(/at least one filter/i); - }); - - it('honours a custom base url', () => { - const url = buildSpacedustSubscribeUrl({ - wantedSources: ['sh.tangled.repo.pull:target.repo'], - baseUrl: 'wss://spacedust.example.test', - }); - - expect(url.startsWith('wss://spacedust.example.test/subscribe?')).toBe(true); - }); -}); diff --git a/packages/www/tsconfig.json b/packages/www/tsconfig.json index 41f5e7f..6a7fd51 100644 --- a/packages/www/tsconfig.json +++ b/packages/www/tsconfig.json @@ -2,8 +2,7 @@ "extends": "astro/tsconfigs/strict", "include": [ ".astro/types.d.ts", - "**/*", - "./worker-configuration.d.ts" + "**/*" ], "exclude": [ "dist" diff --git a/packages/www/worker-configuration.d.ts b/packages/www/worker-configuration.d.ts deleted file mode 100644 index 6857982..0000000 --- a/packages/www/worker-configuration.d.ts +++ /dev/null @@ -1,13553 +0,0 @@ -/* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: 9f22db97b2b4dd7287f7fc016182f7c4) -// Runtime types generated with workerd@1.20260507.1 2026-05-10 global_fetch_strictly_public -declare namespace Cloudflare { - interface Env { - DB: D1Database; - db: D1Database; - ASSETS: Fetcher; - RFD_DEFAULT_OWNER: string; - RFD_ADMIN_TOKEN: string; - SPACEDUST: Fetcher /* www-spacedust */; - } -} -interface Env extends Cloudflare.Env {} - -// 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. - * - * [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 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 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 { - 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_static. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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_static 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. - * - * [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. - * - * [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. - * - * [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. - * - * [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_static. - * - * [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_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) - */ - timeLog(label?: string, ...data: any[]): void; - 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. - * - * [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; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - 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; - 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(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - 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: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; -declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, 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. - * - * [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(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(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(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): Promise; -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; -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 { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; - cache?: CacheContext; - tracing?: Tracing; -} -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerConnectHandler = (socket: Socket, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - connect?: ExportedHandlerConnectHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; -} -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; -} -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; -} -declare abstract class ColoLocalActorNamespace { - get(actorId: string): Fetcher; -} -interface DurableObject { - fetch(request: Request): Response | Promise; - connect?(socket: Socket): void | Promise; - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; -} -type DurableObjectStub = Fetcher & { - readonly id: DurableObjectId; - readonly name?: string; -}; -interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; - readonly jurisdiction?: string; -} -declare abstract class DurableObjectNamespace { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; -} -type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; -interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; -} -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; -type DurableObjectRoutingMode = "primary-only"; -interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; - routingMode?: DurableObjectRoutingMode; -} -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { -} -interface DurableObjectState { - waitUntil(promise: Promise): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; - readonly id: DurableObjectId; - readonly storage: DurableObjectStorage; - container?: Container; - facets: DurableObjectFacets; - blockConcurrencyWhile(callback: () => Promise): Promise; - 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): void; -} -interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; -} -interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; -} -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(name: string, getStartupOptions: () => FacetStartupOptions | Promise>): Fetcher; - abort(name: string, reason: any): void; - delete(name: string): void; -} -interface FacetStartupOptions { - id?: DurableObjectId | string; - class: DurableObjectClass; -} -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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) - */ - get type(): string; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * The read-only **`composed`** property of the 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 dispatched. - * - * [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. - * @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 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 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. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - get cancelBubble(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - set cancelBubble(value: boolean); - /** - * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. - * - * [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 if the event does not get explicitly handled, its default action should not be taken as it normally would be. - * - * [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. - * - * [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. - * - * [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 = (event: EventType) => void; -interface EventListenerObject { - handleEvent(event: EventType): void; -} -type EventListenerOrEventListenerObject = EventListener | EventListenerObject; -/** - * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) - */ -declare class EventTarget = Record> { - 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: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, 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. - * - * [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. - * - * [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 AbortSignal/abort_event 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. - * - * [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 AbortSignal.reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void; -} -interface Scheduler { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; -} -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. - * - * [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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) - */ - waitUntil(promise: Promise): void; -} -/** - * The **`CustomEvent`** interface represents events initialized by an application for any purpose. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) - */ -declare class CustomEvent 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; - /** - * 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; - /** - * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) - */ - text(): Promise; - /** - * 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. - * - * [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). - * - * [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 the Cache object matching the `cacheName`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) - */ - open(cacheName: string): Promise; - 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; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; -} -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 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues(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; - /** - * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) - */ - decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; - /** - * 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; - /** - * 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; - /** - * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) - */ - digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * 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; - /** - * 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; - /** - * The **`deriveBits()`** method of the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) - */ - deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; - /** - * 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; - /** - * 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; - /** - * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) - */ - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; - /** - * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. - * - * [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; - 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 SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.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. - * - * [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 { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; -} -/** - * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. - * - * [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 takes a stream of code points as input and emits a stream of UTF-8 bytes. - * - * [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 Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. - * - * [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 a dictionary object indicating the progress of the encoding. - * - * [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 { - 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 The data sent by the message emitter; this can be any data type, depending on what originated this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: any; - /** - * The **`origin`** read-only property of 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 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 a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null; - /** - * The **`ports`** read-only property of the 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 { - data: ArrayBuffer | string; -} -/** - * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. - * - * [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 rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) - */ - readonly promise: Promise; - /** - * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). - * - * [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 Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. - * - * [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. - * - * [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; - /* Returns an array of key, value pairs for every entry in the list. */ - entries(): IterableIterator<[ - key: string, - value: File | string - ]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator<(File | string)>; - forEach(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; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; -} -interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; -} -interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; -} -interface Element { - tagName: string; - readonly attributes: IterableIterator; - 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; -} -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 ServiceWorkerGlobalScope. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) - */ -declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * The **`respondWith()`** method of 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): void; - passThroughOnException(): void; -} -type HeadersInit = Headers | Iterable> | Record; -/** - * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response 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. - * - * [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. - * - * [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(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable | AsyncIterable; -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; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; -} -/** - * 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 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. - * - * [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. - * - * [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> = Request | 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 >(input: RequestInfo | URL, init?: RequestInit): Request; -}; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -interface Request> 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; - /** - * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. - * - * [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 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) - */ - cache?: "no-store" | "no-cache"; -} -interface RequestInit { - /* 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 Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; -type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; -}; -interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; -} | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; -}; -interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: "text"): Promise; - get(key: Key, type: "json"): Promise; - get(key: Key, type: "arrayBuffer"): Promise; - get(key: Key, type: "stream"): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; - get(key: Array, type: "text"): Promise>; - get(key: Array, type: "json"): Promise>; - get(key: Array, options?: Partial>): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; - list(options?: KVNamespaceListOptions): Promise>; - put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; - getWithMetadata(key: Key, options?: Partial>): Promise>; - getWithMetadata(key: Key, type: "text"): Promise>; - getWithMetadata(key: Key, type: "json"): Promise>; - getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; - getWithMetadata(key: Key, type: "stream"): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; - getWithMetadata(key: Array, type: "text"): Promise>>; - getWithMetadata(key: Array, type: "json"): Promise>>; - getWithMetadata(key: Array, options?: Partial>): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; - delete(key: Key): Promise; -} -interface KVNamespaceListOptions { - limit?: number; - prefix?: (string | null); - cursor?: (string | null); -} -interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; -} -interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); -} -interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; -} -type QueueContentType = "text" | "bytes" | "json" | "v8"; -interface Queue { - metrics(): Promise; - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; -} -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: 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 { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; -} -interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - readonly metadata: MessageBatchMetadata; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface MessageBatch { - readonly messages: readonly Message[]; - 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; - get(key: string, options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - get(key: string, options?: R2GetOptions): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; -} -interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; -} -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; - 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; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; -} -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; - 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; - 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 { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; -} -interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; -} -interface UnderlyingByteSource { - type: "bytes"; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; -} -interface UnderlyingSource { - type?: "" | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: (number | bigint); -} -interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - 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 = { - done: false; - value: R; -} | { - done: true; - value?: undefined; -}; -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -interface ReadableStream { - /** - * 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; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(): ReadableStreamDefaultReader; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [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(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; - /** - * 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, options?: StreamPipeOptions): Promise; - /** - * The **`tee()`** method of the 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, - ReadableStream - ]; - values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; - [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; -} -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -declare const ReadableStream: { - prototype: ReadableStream; - new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; - new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; -}; -/** - * 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 { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * 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>; - /** - * 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) - */ -declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) - */ - read(view: T): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) - */ - releaseLock(): void; - readAtLeast(minElements: number, view: T): Promise>; -} -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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) - */ -declare abstract class ReadableStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the 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 ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) - */ - enqueue(chunk?: R): void; - /** - * The **`error()`** method of the 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. - * - * [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 copied 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. - * - * [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 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 { - /** - * 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. - * - * [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 { - readable: ReadableStream; - /** - * 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; -} -/** - * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) - */ -declare class WritableStream { - 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; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) - */ - getWriter(): WritableStreamDefaultWriter; -} -/** - * 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 { - constructor(stream: WritableStream); - /** - * The **`closed`** read-only property of the the stream errors or the writer's lock is released. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) - */ - get closed(): Promise; - /** - * The **`ready`** read-only property of the 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; - /** - * The **`desiredSize`** read-only property of the 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 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; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [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 { - constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - /** - * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) - */ - get readable(): ReadableStream; - /** - * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) - */ - get writable(): WritableStream; -} -declare class FixedLengthStream extends IdentityTransformStream { - constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); -} -interface ReadableStreamValuesOptions { - preventCancel?: boolean; -} -/** - * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) - */ -declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); -} -/** - * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) - */ -declare class DecompressionStream extends TransformStream { - 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) - */ -declare class TextEncoderStream extends TransformStream { - 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) - */ -declare class TextDecoderStream extends TransformStream { - 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 { - 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; - 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; - 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; -} -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 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. - * - * [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. - * - * [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. - * - * [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. - * - * [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 URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [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 URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - set hash(value: string); - /** - * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('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 ```js-nolint toJSON() ``` None. - * - * [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 URL representing 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 Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. - * - * [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> | Record | 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. - * - * [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`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) - */ - sort(): void; - /* Returns an array of key, value pairs for every entry in the search params. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach(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 - ]>; -} -declare class URLPattern { - constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - 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; -} -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. - * - * [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 { - 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 { - 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) - */ - send(message: (ArrayBuffer | ArrayBufferView) | string): void; - /** - * The **`WebSocket.close()`** method closes the 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. - * - * [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>(query: string, ...bindings: any[]): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; -} -declare abstract class SqlStorageStatement { -} -type SqlStorageValue = ArrayBuffer | string | number | null; -declare abstract class SqlStorageCursor> { - next(): { - done?: false; - value: T; - } | { - done: true; - value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; -} -interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): "on" | "off" | "starttls"; - close(): Promise; - 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 ```js-nolint close() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of 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 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 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 Container { - get running(): boolean; - start(options?: ContainerStartupOptions): void; - monitor(): Promise; - destroy(error?: any): Promise; - signal(signo: number): void; - getTcpPort(port: number): Fetcher; - setInactivityTimeout(durationMs: number | bigint): Promise; - interceptOutboundHttp(addr: string, binding: Fetcher): Promise; - interceptAllOutboundHttp(binding: Fetcher): Promise; - snapshotDirectory(options: ContainerDirectorySnapshotOptions): Promise; - snapshotContainer(options: ContainerSnapshotOptions): Promise; - interceptOutboundHttps(addr: string, binding: Fetcher): Promise; -} -interface ContainerDirectorySnapshot { - id: string; - size: number; - dir: string; - name?: string; -} -interface ContainerDirectorySnapshotOptions { - dir: string; - name?: string; -} -interface ContainerDirectorySnapshotRestoreParams { - snapshot: ContainerDirectorySnapshot; - mountPoint?: string; -} -interface ContainerSnapshot { - id: string; - size: number; - name?: string; -} -interface ContainerSnapshotOptions { - name?: string; -} -interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - labels?: Record; - directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; - containerSnapshot?: ContainerSnapshot; -} -/** - * 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 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. - * - * [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. - * - * [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 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 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 Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; -type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { - props?: Props; -}) => Fetcher : (opts: { - props?: any; -}) => Fetcher); -type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { - props?: Props; -}) => DurableObjectClass : (opts: { - props?: any; -}) => DurableObjectClass); -interface LoopbackDurableObjectNamespace extends DurableObjectNamespace { -} -interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace { -} -interface SyncKvStorage { - get(key: string): T | undefined; - list(options?: SyncKvListOptions): Iterable<[ - string, - T - ]>; - put(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(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; - getDurableObjectClass(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass; -} -interface WorkerStubEntrypointOptions { - props?: any; - limits?: workerdResourceLimits; -} -interface WorkerLoader { - get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; - load(code: WorkerLoaderWorkerCode): WorkerStub; -} -interface WorkerLoaderModule { - js?: string; - cjs?: string; - text?: string; - data?: ArrayBuffer; - json?: any; - py?: string; - wasm?: ArrayBuffer; -} -interface WorkerLoaderWorkerCode { - compatibilityDate: string; - compatibilityFlags?: string[]; - allowExperimental?: boolean; - limits?: workerdResourceLimits; - mainModule: string; - modules: Record; - 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 Serialization; 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(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T; - Span: typeof Span; -} -declare abstract class Span { - get isTraced(): boolean; - setAttribute(key: string, value?: (boolean | number | string)): 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 & { - ai_search_options: AiSearchMultiSearchOptions; -}; -/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */ -type AiSearchMultiChatCompletionsResponse = Omit & { - 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; - }; - 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; - [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; - [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; - [key: string]: unknown; -}; -type AiSearchItemContentResult = { - body: ReadableStream; - contentType: string; - filename: string; - size: number; -}; -type AiSearchUploadItemOptions = { - metadata?: Record; -}; -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; -}; -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; - }; -}; -/** 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; - /** - * Download the item's content. - * @returns Object with body stream, content type, filename, and size. - */ - download(): Promise; - /** - * Trigger re-indexing of this item. - * @returns The updated item info. - */ - sync(): Promise; - /** - * 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; - /** - * 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; -} -/** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; -} -/** - * 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; - /** Get logs for this job. */ - logs(params?: AiSearchJobLogsParams): Promise; - /** - * Cancel a running job. - * @returns The updated job info. - * @throws AiSearchNotFoundError if the job does not exist. - */ - cancel(): Promise; -} -/** - * 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; - /** - * Create a new indexing job. - * @param params Optional job parameters. - * @returns The created job info. - */ - create(params?: AiSearchCreateJobParams): Promise; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * Update the instance configuration. - * @param config Partial configuration to update. - * @returns Updated instance info. - */ - update(config: Partial): Promise; - /** Get metadata about this instance. */ - info(): Promise; - /** - * Get instance statistics (item count, indexing status, etc.). - * @returns Statistics with counts per status, last activity time, and engine details. - */ - stats(): Promise; - /** 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; - /** - * 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; - /** - * Delete an instance from the bound namespace. - * @param name Instance name to delete. - */ - delete(name: string): Promise; - /** - * 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; - /** - * 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; - /** - * 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; -} -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); - content: string; - name?: string; -}; -type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; -}; -type AiTextGenerationToolInput = { - type: "function" | (string & NonNullable); - function: { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - 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); - 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; -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; - 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>; - }; -}; -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; - name?: string; -}; -type AssistantMessageContentPart = { - type: "text" | "refusal"; - text?: string; - refusal?: string; -}; -type AssistantMessage = { - role: "assistant"; - content?: string | null | Array; - refusal?: string | null; - name?: string; - audio?: { - id: string; - }; - tool_calls?: Array; - 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; - 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 | null; - logprobs?: boolean | null; - top_logprobs?: number | null; - max_tokens?: number | null; - max_completion_tokens?: number | null; - metadata?: Record | 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 | null; - store?: boolean | null; - stream?: boolean | null; - stream_options?: ChatCompletionsStreamOptions; - temperature?: number | null; - tool_choice?: ChatCompletionToolChoiceOption; - tools?: Array; - top_p?: number | null; - user?: string; - web_search_options?: WebSearchOptions; - function_call?: "none" | "auto" | { - name: string; - }; - functions?: Array; -}; -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 | null; -}; -type ChatCompletionTokenLogprob = { - token: string; - logprob: number; - bytes: Array | null; - top_logprobs: Array; -}; -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; - audio?: ChatCompletionAudio; - tool_calls?: Array; - function_call?: { - name: string; - arguments: string; - } | null; -}; -type ChatCompletionLogprobs = { - content: Array | null; - refusal?: Array | null; -}; -type ChatCompletionChoice = { - index: number; - message: ChatCompletionResponseMessage; - finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; - logprobs: ChatCompletionLogprobs | null; -}; -type ChatCompletionsPromptInput = { - prompt: string; -} & ChatCompletionsCommonOptions; -type ChatCompletionsMessagesInput = { - messages: Array; -} & ChatCompletionsCommonOptions; -type ChatCompletionsOutput = { - id: string; - object: string; - created: number; - model: string; - choices: Array; - 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 | 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; - 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 | null; - object?: "response"; - output?: Array; - parallel_tool_calls?: boolean; - temperature?: number | null; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - 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; - 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; -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; - 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; -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; -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; - role: "assistant"; - status: "in_progress" | "completed" | "incomplete"; - type: "message"; -}; -type ResponseOutputRefusal = { - refusal: string; - type: "refusal"; -}; -type ResponseOutputText = { - text: string; - type: "output_text"; - logprobs?: Array; -}; -type ResponseReasoningItem = { - id: string; - summary: Array; - type: "reasoning"; - content?: Array; - 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; - output_index: number; - sequence_number: number; - type: "response.output_text.delta"; -}; -type ResponseTextDoneEvent = { - content_index: number; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - text: string; - type: "response.output_text.done"; -}; -type Logprob = { - token: string; - logprob: number; - top_logprobs?: Array; -}; -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 = { - [P in Exclude]?: never; -}; -/** Either T or U, but not both (mutually exclusive) */ -type XOR = (T & Without) | (U & Without); -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); - /** - * 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); - /** - * 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); - 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; - postProcessedOutputs: XOR; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: XOR; - postProcessedOutputs: XOR; -} -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_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; -} -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/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B; -} -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 = XOR; -type ChatCompletionsInput = XOR; -interface InferenceUpstreamError extends Error { -} -interface AiInternalError extends Error { -} -type AiModelListType = Record; -type AiAsyncBatchResponse = { - request_id: string; -}; -declare abstract class Ai { - 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(model: Name, inputs: { - requests: AiModelList[Name]['inputs'][]; - }, options: AiOptions & { - queueRequest: true; - }): Promise; - // Raw response - run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { - returnRawResponse: true; - }): Promise; - // WebSocket - run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { - websocket: true; - }): Promise; - // Streaming - run(model: Name, inputs: AiModelList[Name]['inputs'] & { - stream: true; - }, options?: AiOptions): Promise; - // Normal (default) - known model - run(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise; - // Unknown model (gateway fallback) - run(model: string & {}, inputs: Record, options?: AiOptions): Promise>; - models(params?: AiModelsSearchParams): Promise; - toMarkdown(): ToMarkdownService; - toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; -} -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; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; -}; -type UniversalGatewayOptions = Exclude & { - /** - ** @deprecated - */ - id?: string; -}; -type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | 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; - 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; - '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; - query: unknown; -}; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { -} -declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { - gateway?: UniversalGatewayOptions; - extraHeaders?: object; - signal?: AbortSignal; - }): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // 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[]; - /** 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(). */ -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). - */ - createToken(scope?: 'write' | 'read', ttl?: number): Promise; - /** List tokens for this repo (metadata only, no plaintext). */ - listTokens(): Promise; - /** - * Revoke a token by plaintext or ID. - * @param tokenOrId Plaintext token or token ID. - * @returns true if revoked, false if not found. - */ - revokeToken(tokenOrId: string): Promise; - // ── Fork ── - /** - * Fork this repo to a new repo. - * @param name Target repository name. - * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true). - */ - fork(name: string, opts?: { - description?: string; - readOnly?: boolean; - defaultBranchOnly?: boolean; - }): Promise; -} -/** Artifacts binding — namespace-level operations. */ -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. - */ - create(name: string, opts?: { - readOnly?: boolean; - description?: string; - setDefaultBranch?: string; - }): Promise; - /** - * Get a handle to an existing repository. - * @param name Repository name. - * @returns Repo handle. - */ - get(name: string): Promise; - /** - * 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. - */ - import(params: { - source: { - url: string; - branch?: string; - depth?: number; - }; - target: { - name: string; - opts?: { - description?: string; - readOnly?: boolean; - }; - }; - }): Promise; - /** - * 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; - /** - * Delete a repository and all associated tokens. - * @param name Repository name. - * @returns true if deleted, false if not found. - */ - delete(name: string): Promise; -} -/** - * @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 & { - 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; - 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; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - search(params: AutoRagSearchRequest): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; -} -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; - /** - * 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. - * - 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" | "contain" | "cover" | "crop" | "pad" | "squeeze"; - /** - * 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"; - /** - * 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; - /** - * 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; - /** - * 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; -} -interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: 'remainder' | 'box-center'; -} -/** - * 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 { - 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; - /** - * 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; - 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; -} -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"; - /** - * 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 { - /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . - */ - dpr?: number; - /** - * 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; - }; - }; - /** - * 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"; - /** - * 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; - /** - * 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"; - /** - * 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; - }; - /** - * 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 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 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; - /** - * 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'; - /** - * 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 = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; -interface IncomingRequestCfPropertiesBase extends Record { - /** - * [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 { - /** - * 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; - /** 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; -} -/** 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: ""; -} -/** 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 = IncomingRequestCfProperties | 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; - error?: never; -} -type D1Result = 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(statements: D1PreparedStatement[]): Promise[]>; - exec(query: string): Promise; - /** - * 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; -} -declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - /** - * @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(colName: string): Promise; - first>(): Promise; - run>(): Promise>; - all>(): Promise>; - raw(options: { - columnNames: true; - }): Promise<[ - string[], - ...T[] - ]>; - raw(options?: { - columnNames?: false; - }): Promise; -} -// `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; - /** - * 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; - /** - * 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; -} -/** 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; -} -/** - * A binding that allows a Worker to send email messages. - */ -interface SendEmail { - send(message: EmailMessage): Promise; - send(builder: { - from: string | EmailAddress; - to: string | string[]; - subject: string; - replyTo?: string | EmailAddress; - cc?: string | string[]; - bcc?: string | string[]; - headers?: Record; - text?: string; - html?: string; - attachments?: EmailAttachment[]; - }): Promise; -} -declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; -} -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; -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; -interface FlagshipEvaluationDetails { - 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise; - /** - * 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>; - /** - * 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>; - /** - * 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>; - /** - * 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(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise>; -} -/** - * 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; -} -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; - /* - * 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; -} -// 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; -}; -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; - top?: number; - left?: number; - bottom?: number; - right?: number; -}; -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; - variants: string[]; - draft?: boolean; - creator?: string; -} -interface ImageUploadOptions { - id?: string; - filename?: string; - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; - encoding?: 'base64'; -} -interface ImageUpdateOptions { - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; -} -interface ImageListOptions { - limit?: number; - cursor?: string; - sortOrder?: 'asc' | 'desc'; - creator?: 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; - /** - * Get the raw image data for a hosted image - * @returns ReadableStream of image bytes, or null if not found - */ - bytes(): Promise | null>; - /** - * Update hosted image metadata - * @param options Properties to update - * @returns Updated image metadata - * @throws {@link ImagesError} if update fails - */ - update(options: ImageUpdateOptions): Promise; - /** - * Delete a hosted image - * @returns True if deleted, false if not found - */ - delete(): Promise; -} -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 | ArrayBuffer, options?: ImageUploadOptions): Promise; - /** - * 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; -} -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, options?: ImageInputOptions): Promise; - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input(stream: ReadableStream, options?: ImageInputOptions): 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 | 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; -} -type ImageTransformationOutputOptions = { - encoding?: 'base64'; -}; -interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream; -} -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): 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>; - /** - * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Promise, ready to store in cache or return to users - */ - response(): Promise; - /** - * Returns the MIME type of the transformed media. - * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') - */ - contentType(): Promise; -} -/** - * 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

= Record; -type EventContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; -}; -type PagesFunction = Record> = (context: EventContext) => Response | Promise; -type EventPluginContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; - pluginArgs: PluginArgs; -}; -type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; -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 { - 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; - } - export type PipelineRecord = Record; - export type PipelineBatchMetadata = { - pipelineId: string; - pipelineName: string; - }; - export interface Pipeline { - /** - * 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; - } -} -// 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; -} -// 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 = - // Structured cloneables - BaseType - // Structured cloneable composites - | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { - [K in keyof T]: K extends number | string ? Serializable : never; - } - // Special types - | Stub - // 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 extends Disposable { - [__RPC_STUB_BRAND]: T; - dup(): this; - } - export type Stub = Provider & StubBase; - // 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 | WritableStream | Request | Response | Headers; - // Recursively rewrite all `Stubable` types with `Stub`s - // prettier-ignore - type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: any; - } ? { - [K in keyof T]: Stubify; - } : T; - // Recursively rewrite all `Stub`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 extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: unknown; - } ? { - [K in keyof T]: Unstubify; - } : T; - type UnstubifyAll = { - [I in keyof A]: Unstubify; - }; - // Utility type for adding `Provider`/`Disposable`s to `object` types only. - // Note `unknown & T` is equivalent to `T`. - type MaybeProvider = T extends object ? Provider : unknown; - type MaybeDisposable = 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 extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : 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 extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result>; - // Type for the callable part of an `Provider` if `T` is callable. - // This is intersected with methods/properties. - type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : 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 = MaybeCallableProvider & Pick<{ - [K in keyof T]: MethodOrProperty; - }, Exclude>>; -} -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 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 - // 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 : DurableObjectNamespace : DurableObjectNamespace : {}); - }; -} -declare namespace CloudflareWorkersModule { - export type RpcStub = Rpc.Stub; - export const RpcStub: { - new (value: T): Rpc.Stub; - }; - 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 implements Rpc.WorkerEntrypointBranded { - [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - email?(message: ForwardableEmailMessage): void | Promise; - fetch?(request: Request): Response | Promise; - connect?(socket: Socket): void | Promise; - queue?(batch: MessageBatch): void | Promise; - scheduled?(controller: ScheduledController): void | Promise; - tail?(events: TraceItem[]): void | Promise; - tailStream?(event: TailStream.TailEvent): TailStream.TailEventHandlerType | Promise; - test?(controller: TestController): void | Promise; - trace?(traces: TraceItem[]): void | Promise; - } - export abstract class DurableObject implements Rpc.DurableObjectBranded { - [Rpc.__DURABLE_OBJECT_BRAND]: never; - protected ctx: DurableObjectState; - protected env: Env; - constructor(ctx: DurableObjectState, env: Env); - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - fetch?(request: Request): Response | Promise; - connect?(socket: Socket): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; - } - export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; - export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; - export type WorkflowDelayDuration = WorkflowSleepDuration; - export type WorkflowTimeoutDuration = WorkflowSleepDuration; - export type WorkflowRetentionDuration = WorkflowSleepDuration; - export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; - export type WorkflowStepConfig = { - retries?: { - limit: number; - delay: WorkflowDelayDuration | number; - backoff?: WorkflowBackoff; - }; - timeout?: WorkflowTimeoutDuration | number; - }; - export type WorkflowEvent = { - payload: Readonly; - timestamp: Date; - instanceId: string; - }; - export type WorkflowStepEvent = { - payload: Readonly; - timestamp: Date; - type: string; - }; - export type WorkflowStepContext = { - step: { - name: string; - count: number; - }; - attempt: number; - config: WorkflowStepConfig; - }; - export abstract class WorkflowStep { - do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; - sleep: (name: string, duration: WorkflowSleepDuration) => Promise; - sleepUntil: (name: string, timestamp: Date | number) => Promise; - waitForEvent>(name: string, options: { - type: string; - timeout?: WorkflowTimeoutDuration | number; - }): Promise>; - } - export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; - export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { - [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - run(event: Readonly>, step: WorkflowStep): Promise; - } - export function waitUntil(promise: Promise): 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; -} -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; - /** - * 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; - 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; - /** - * 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; - /** - * 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; - /** - * 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; - 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; - /** - * 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; - /** - * 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; - /** - * Lists the origins allowed to display the video. - */ - allowedOrigins?: Array; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; -} -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; - /** - * 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; - /** - * 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; -} -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; -} -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; - /** - * 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; - /** - * Lists all watermark profiles for an account. - * @returns The list of watermark profiles. - * @throws {InternalError} if an unexpected error occurs - */ - list(): Promise; - /** - * 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; - /** - * 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; -} -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; - /** - * 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; - /** - * 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 ConversionResponse = { - id: string; - name: string; - mimeType: string; - format: 'markdown'; - 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 ConversionOptions = { - 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; - transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; - supported(): Promise; -} -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"; - 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 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 name: string; - readonly message: string; - readonly stack?: string; - } - interface Log { - readonly type: "log"; - readonly level: "debug" | "error" | "info" | "log" | "warn"; - readonly message: object; - } - 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; - } - interface TailEvent { - // 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: TailEvent) => void | Promise; - type TailEventHandlerObject = { - outcome?: TailEventHandler; - spanOpen?: TailEventHandler; - spanClose?: TailEventHandler; - diagnosticChannel?: TailEventHandler; - exception?: TailEventHandler; - log?: TailEventHandler; - return?: TailEventHandler; - attributes?: TailEventHandler; - }; - 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; -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 | null | { - [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; - } | { - [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; - }; -}; -/** - * 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; -} -/** - * Represents a matched vector for a query along with its score and (if specified) the matching vector information. - */ -type VectorizeMatch = Pick, "values"> & Omit & { - /** 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; -} -/** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; -} -/** - * 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; -}; -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 { - /** - * 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; - /** - * 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): Promise; - /** - * 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[]): Promise; -} -type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; -type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; -type WorkflowRetentionDuration = WorkflowSleepDuration; -interface WorkflowInstanceCreateOptions { - /** - * 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; - }; -} -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; -} -declare abstract class WorkflowInstance { - public id: string; - /** - * Pause the instance. - */ - public pause(): Promise; - /** - * Resume the instance. If it is already running, an error will be thrown. - */ - public resume(): Promise; - /** - * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. - */ - public terminate(): Promise; - /** - * Restart the instance. - */ - public restart(): Promise; - /** - * Returns the current status of the instance. - */ - public status(): Promise; - /** - * Send an event to this instance. - */ - public sendEvent({ type, payload, }: { - type: string; - payload: unknown; - }): Promise; -} diff --git a/packages/www/workers/spacedust.ts b/packages/www/workers/spacedust.ts deleted file mode 100644 index 13c95d2..0000000 --- a/packages/www/workers/spacedust.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { SpacedustSubscriber } from '../src/lib/spacedust-subscriber.ts'; - -export { SpacedustSubscriber }; - -interface AuxEnv { - db: D1Database; - SUBSCRIBER: DurableObjectNamespace; -} - -const SINGLETON_NAME = 'singleton'; - -export default { - async fetch(request: Request, env: AuxEnv): Promise { - const id = env.SUBSCRIBER.idFromName(SINGLETON_NAME); - const stub = env.SUBSCRIBER.get(id); - return stub.fetch(request); - }, -}; diff --git a/packages/www/workers/spacedust.wrangler.jsonc b/packages/www/workers/spacedust.wrangler.jsonc deleted file mode 100644 index b348d28..0000000 --- a/packages/www/workers/spacedust.wrangler.jsonc +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "www-spacedust", - "main": "./spacedust.ts", - "compatibility_date": "2026-05-10", - "compatibility_flags": ["global_fetch_strictly_public"], - "observability": { - "enabled": true - }, - "d1_databases": [ - { - "binding": "db", - "database_name": "db", - "database_id": "28268fa4-64f6-4a97-aa95-e569d26fc5c1" - } - ], - "durable_objects": { - "bindings": [ - { - "name": "SUBSCRIBER", - "class_name": "SpacedustSubscriber" - } - ] - }, - "migrations": [ - { - "tag": "v1", - "new_sqlite_classes": ["SpacedustSubscriber"] - } - ] -} diff --git a/packages/www/workers/worker-configuration.d.ts b/packages/www/workers/worker-configuration.d.ts deleted file mode 100644 index 8fe8c67..0000000 --- a/packages/www/workers/worker-configuration.d.ts +++ /dev/null @@ -1,13553 +0,0 @@ -/* eslint-disable */ -// Generated by Wrangler by running `wrangler types --config workers/spacedust.wrangler.jsonc --path workers/worker-configuration.d.ts` (hash: 7982545f5051f73c66082afafa58db4d) -// Runtime types generated with workerd@1.20260507.1 2026-05-10 global_fetch_strictly_public -declare namespace Cloudflare { - interface GlobalProps { - mainModule: typeof import("./spacedust"); - durableNamespaces: "SpacedustSubscriber"; - } - interface Env { - db: D1Database; - SUBSCRIBER: DurableObjectNamespace; - } -} -interface Env extends Cloudflare.Env {} - -// 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. - * - * [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 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 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 { - 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_static. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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_static 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. - * - * [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. - * - * [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. - * - * [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. - * - * [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_static. - * - * [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_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) - */ - timeLog(label?: string, ...data: any[]): void; - 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. - * - * [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; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - 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; - 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(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - 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: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; -declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, 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. - * - * [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(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(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(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): Promise; -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; -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 { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; - cache?: CacheContext; - tracing?: Tracing; -} -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerConnectHandler = (socket: Socket, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - connect?: ExportedHandlerConnectHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; -} -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; -} -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; -} -declare abstract class ColoLocalActorNamespace { - get(actorId: string): Fetcher; -} -interface DurableObject { - fetch(request: Request): Response | Promise; - connect?(socket: Socket): void | Promise; - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; -} -type DurableObjectStub = Fetcher & { - readonly id: DurableObjectId; - readonly name?: string; -}; -interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; - readonly jurisdiction?: string; -} -declare abstract class DurableObjectNamespace { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; -} -type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; -interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; -} -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; -type DurableObjectRoutingMode = "primary-only"; -interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; - routingMode?: DurableObjectRoutingMode; -} -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { -} -interface DurableObjectState { - waitUntil(promise: Promise): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; - readonly id: DurableObjectId; - readonly storage: DurableObjectStorage; - container?: Container; - facets: DurableObjectFacets; - blockConcurrencyWhile(callback: () => Promise): Promise; - 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): void; -} -interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; -} -interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; -} -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(name: string, getStartupOptions: () => FacetStartupOptions | Promise>): Fetcher; - abort(name: string, reason: any): void; - delete(name: string): void; -} -interface FacetStartupOptions { - id?: DurableObjectId | string; - class: DurableObjectClass; -} -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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) - */ - get type(): string; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * The read-only **`composed`** property of the 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 dispatched. - * - * [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. - * @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 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 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. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - get cancelBubble(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - set cancelBubble(value: boolean); - /** - * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. - * - * [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 if the event does not get explicitly handled, its default action should not be taken as it normally would be. - * - * [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. - * - * [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. - * - * [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 = (event: EventType) => void; -interface EventListenerObject { - handleEvent(event: EventType): void; -} -type EventListenerOrEventListenerObject = EventListener | EventListenerObject; -/** - * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) - */ -declare class EventTarget = Record> { - 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: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, 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. - * - * [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. - * - * [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 AbortSignal/abort_event 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. - * - * [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 AbortSignal.reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void; -} -interface Scheduler { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; -} -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. - * - * [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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) - */ - waitUntil(promise: Promise): void; -} -/** - * The **`CustomEvent`** interface represents events initialized by an application for any purpose. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) - */ -declare class CustomEvent 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; - /** - * 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; - /** - * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) - */ - text(): Promise; - /** - * 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. - * - * [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). - * - * [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 the Cache object matching the `cacheName`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) - */ - open(cacheName: string): Promise; - 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; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; -} -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 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues(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; - /** - * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) - */ - decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; - /** - * 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; - /** - * 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; - /** - * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) - */ - digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * 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; - /** - * 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; - /** - * The **`deriveBits()`** method of the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) - */ - deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; - /** - * 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; - /** - * 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; - /** - * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) - */ - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; - /** - * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. - * - * [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; - 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 SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.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. - * - * [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 { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; -} -/** - * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. - * - * [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 takes a stream of code points as input and emits a stream of UTF-8 bytes. - * - * [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 Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. - * - * [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 a dictionary object indicating the progress of the encoding. - * - * [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 { - 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 The data sent by the message emitter; this can be any data type, depending on what originated this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: any; - /** - * The **`origin`** read-only property of 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 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 a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null; - /** - * The **`ports`** read-only property of the 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 { - data: ArrayBuffer | string; -} -/** - * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. - * - * [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 rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) - */ - readonly promise: Promise; - /** - * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). - * - * [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 Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. - * - * [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. - * - * [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; - /* Returns an array of key, value pairs for every entry in the list. */ - entries(): IterableIterator<[ - key: string, - value: File | string - ]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator<(File | string)>; - forEach(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; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; -} -interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; -} -interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; -} -interface Element { - tagName: string; - readonly attributes: IterableIterator; - 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; -} -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 ServiceWorkerGlobalScope. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) - */ -declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * The **`respondWith()`** method of 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): void; - passThroughOnException(): void; -} -type HeadersInit = Headers | Iterable> | Record; -/** - * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response 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. - * - * [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. - * - * [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(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable | AsyncIterable; -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; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; -} -/** - * 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 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. - * - * [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. - * - * [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> = Request | 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 >(input: RequestInfo | URL, init?: RequestInit): Request; -}; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -interface Request> 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; - /** - * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. - * - * [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 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) - */ - cache?: "no-store" | "no-cache"; -} -interface RequestInit { - /* 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 Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; -type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; -}; -interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; -} | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; -}; -interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: "text"): Promise; - get(key: Key, type: "json"): Promise; - get(key: Key, type: "arrayBuffer"): Promise; - get(key: Key, type: "stream"): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; - get(key: Array, type: "text"): Promise>; - get(key: Array, type: "json"): Promise>; - get(key: Array, options?: Partial>): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; - list(options?: KVNamespaceListOptions): Promise>; - put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; - getWithMetadata(key: Key, options?: Partial>): Promise>; - getWithMetadata(key: Key, type: "text"): Promise>; - getWithMetadata(key: Key, type: "json"): Promise>; - getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; - getWithMetadata(key: Key, type: "stream"): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; - getWithMetadata(key: Array, type: "text"): Promise>>; - getWithMetadata(key: Array, type: "json"): Promise>>; - getWithMetadata(key: Array, options?: Partial>): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; - delete(key: Key): Promise; -} -interface KVNamespaceListOptions { - limit?: number; - prefix?: (string | null); - cursor?: (string | null); -} -interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; -} -interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); -} -interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; -} -type QueueContentType = "text" | "bytes" | "json" | "v8"; -interface Queue { - metrics(): Promise; - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; -} -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: 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 { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; -} -interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - readonly metadata: MessageBatchMetadata; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface MessageBatch { - readonly messages: readonly Message[]; - 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; - get(key: string, options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - get(key: string, options?: R2GetOptions): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; -} -interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; -} -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; - 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; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; -} -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; - 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; - 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 { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; -} -interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; -} -interface UnderlyingByteSource { - type: "bytes"; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; -} -interface UnderlyingSource { - type?: "" | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: (number | bigint); -} -interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - 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 = { - done: false; - value: R; -} | { - done: true; - value?: undefined; -}; -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -interface ReadableStream { - /** - * 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; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(): ReadableStreamDefaultReader; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [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(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; - /** - * 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, options?: StreamPipeOptions): Promise; - /** - * The **`tee()`** method of the 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, - ReadableStream - ]; - values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; - [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; -} -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -declare const ReadableStream: { - prototype: ReadableStream; - new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; - new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; -}; -/** - * 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 { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * 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>; - /** - * 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) - */ -declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) - */ - read(view: T): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) - */ - releaseLock(): void; - readAtLeast(minElements: number, view: T): Promise>; -} -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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) - */ -declare abstract class ReadableStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the 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 ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) - */ - enqueue(chunk?: R): void; - /** - * The **`error()`** method of the 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. - * - * [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 copied 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. - * - * [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 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 { - /** - * 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. - * - * [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 { - readable: ReadableStream; - /** - * 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; -} -/** - * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) - */ -declare class WritableStream { - 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; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) - */ - getWriter(): WritableStreamDefaultWriter; -} -/** - * 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 { - constructor(stream: WritableStream); - /** - * The **`closed`** read-only property of the the stream errors or the writer's lock is released. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) - */ - get closed(): Promise; - /** - * The **`ready`** read-only property of the 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; - /** - * The **`desiredSize`** read-only property of the 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 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; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [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 { - constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - /** - * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) - */ - get readable(): ReadableStream; - /** - * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) - */ - get writable(): WritableStream; -} -declare class FixedLengthStream extends IdentityTransformStream { - constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); -} -interface ReadableStreamValuesOptions { - preventCancel?: boolean; -} -/** - * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) - */ -declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); -} -/** - * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) - */ -declare class DecompressionStream extends TransformStream { - 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) - */ -declare class TextEncoderStream extends TransformStream { - 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) - */ -declare class TextDecoderStream extends TransformStream { - 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 { - 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; - 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; - 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; -} -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 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. - * - * [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. - * - * [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. - * - * [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. - * - * [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 URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [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 URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - set hash(value: string); - /** - * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('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 ```js-nolint toJSON() ``` None. - * - * [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 URL representing 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 Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. - * - * [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> | Record | 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. - * - * [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`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) - */ - sort(): void; - /* Returns an array of key, value pairs for every entry in the search params. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach(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 - ]>; -} -declare class URLPattern { - constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - 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; -} -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. - * - * [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 { - 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 { - 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. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) - */ - send(message: (ArrayBuffer | ArrayBufferView) | string): void; - /** - * The **`WebSocket.close()`** method closes the 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. - * - * [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>(query: string, ...bindings: any[]): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; -} -declare abstract class SqlStorageStatement { -} -type SqlStorageValue = ArrayBuffer | string | number | null; -declare abstract class SqlStorageCursor> { - next(): { - done?: false; - value: T; - } | { - done: true; - value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; -} -interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): "on" | "off" | "starttls"; - close(): Promise; - 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 ```js-nolint close() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of 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 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 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 Container { - get running(): boolean; - start(options?: ContainerStartupOptions): void; - monitor(): Promise; - destroy(error?: any): Promise; - signal(signo: number): void; - getTcpPort(port: number): Fetcher; - setInactivityTimeout(durationMs: number | bigint): Promise; - interceptOutboundHttp(addr: string, binding: Fetcher): Promise; - interceptAllOutboundHttp(binding: Fetcher): Promise; - snapshotDirectory(options: ContainerDirectorySnapshotOptions): Promise; - snapshotContainer(options: ContainerSnapshotOptions): Promise; - interceptOutboundHttps(addr: string, binding: Fetcher): Promise; -} -interface ContainerDirectorySnapshot { - id: string; - size: number; - dir: string; - name?: string; -} -interface ContainerDirectorySnapshotOptions { - dir: string; - name?: string; -} -interface ContainerDirectorySnapshotRestoreParams { - snapshot: ContainerDirectorySnapshot; - mountPoint?: string; -} -interface ContainerSnapshot { - id: string; - size: number; - name?: string; -} -interface ContainerSnapshotOptions { - name?: string; -} -interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - labels?: Record; - directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; - containerSnapshot?: ContainerSnapshot; -} -/** - * 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 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. - * - * [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. - * - * [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 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 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 Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; -type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { - props?: Props; -}) => Fetcher : (opts: { - props?: any; -}) => Fetcher); -type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { - props?: Props; -}) => DurableObjectClass : (opts: { - props?: any; -}) => DurableObjectClass); -interface LoopbackDurableObjectNamespace extends DurableObjectNamespace { -} -interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace { -} -interface SyncKvStorage { - get(key: string): T | undefined; - list(options?: SyncKvListOptions): Iterable<[ - string, - T - ]>; - put(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(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; - getDurableObjectClass(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass; -} -interface WorkerStubEntrypointOptions { - props?: any; - limits?: workerdResourceLimits; -} -interface WorkerLoader { - get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; - load(code: WorkerLoaderWorkerCode): WorkerStub; -} -interface WorkerLoaderModule { - js?: string; - cjs?: string; - text?: string; - data?: ArrayBuffer; - json?: any; - py?: string; - wasm?: ArrayBuffer; -} -interface WorkerLoaderWorkerCode { - compatibilityDate: string; - compatibilityFlags?: string[]; - allowExperimental?: boolean; - limits?: workerdResourceLimits; - mainModule: string; - modules: Record; - 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 Serialization; 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(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T; - Span: typeof Span; -} -declare abstract class Span { - get isTraced(): boolean; - setAttribute(key: string, value?: (boolean | number | string)): 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 & { - ai_search_options: AiSearchMultiSearchOptions; -}; -/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */ -type AiSearchMultiChatCompletionsResponse = Omit & { - 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; - }; - 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; - [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; - [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; - [key: string]: unknown; -}; -type AiSearchItemContentResult = { - body: ReadableStream; - contentType: string; - filename: string; - size: number; -}; -type AiSearchUploadItemOptions = { - metadata?: Record; -}; -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; -}; -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; - }; -}; -/** 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; - /** - * Download the item's content. - * @returns Object with body stream, content type, filename, and size. - */ - download(): Promise; - /** - * Trigger re-indexing of this item. - * @returns The updated item info. - */ - sync(): Promise; - /** - * 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; - /** - * 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; -} -/** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; -} -/** - * 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; - /** Get logs for this job. */ - logs(params?: AiSearchJobLogsParams): Promise; - /** - * Cancel a running job. - * @returns The updated job info. - * @throws AiSearchNotFoundError if the job does not exist. - */ - cancel(): Promise; -} -/** - * 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; - /** - * Create a new indexing job. - * @param params Optional job parameters. - * @returns The created job info. - */ - create(params?: AiSearchCreateJobParams): Promise; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * Update the instance configuration. - * @param config Partial configuration to update. - * @returns Updated instance info. - */ - update(config: Partial): Promise; - /** Get metadata about this instance. */ - info(): Promise; - /** - * Get instance statistics (item count, indexing status, etc.). - * @returns Statistics with counts per status, last activity time, and engine details. - */ - stats(): Promise; - /** 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; - /** - * 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; - /** - * Delete an instance from the bound namespace. - * @param name Instance name to delete. - */ - delete(name: string): Promise; - /** - * 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; - /** - * 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; - /** - * 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; -} -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); - content: string; - name?: string; -}; -type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; -}; -type AiTextGenerationToolInput = { - type: "function" | (string & NonNullable); - function: { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - 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); - 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; -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; - 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>; - }; -}; -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; - name?: string; -}; -type AssistantMessageContentPart = { - type: "text" | "refusal"; - text?: string; - refusal?: string; -}; -type AssistantMessage = { - role: "assistant"; - content?: string | null | Array; - refusal?: string | null; - name?: string; - audio?: { - id: string; - }; - tool_calls?: Array; - 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; - 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 | null; - logprobs?: boolean | null; - top_logprobs?: number | null; - max_tokens?: number | null; - max_completion_tokens?: number | null; - metadata?: Record | 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 | null; - store?: boolean | null; - stream?: boolean | null; - stream_options?: ChatCompletionsStreamOptions; - temperature?: number | null; - tool_choice?: ChatCompletionToolChoiceOption; - tools?: Array; - top_p?: number | null; - user?: string; - web_search_options?: WebSearchOptions; - function_call?: "none" | "auto" | { - name: string; - }; - functions?: Array; -}; -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 | null; -}; -type ChatCompletionTokenLogprob = { - token: string; - logprob: number; - bytes: Array | null; - top_logprobs: Array; -}; -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; - audio?: ChatCompletionAudio; - tool_calls?: Array; - function_call?: { - name: string; - arguments: string; - } | null; -}; -type ChatCompletionLogprobs = { - content: Array | null; - refusal?: Array | null; -}; -type ChatCompletionChoice = { - index: number; - message: ChatCompletionResponseMessage; - finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; - logprobs: ChatCompletionLogprobs | null; -}; -type ChatCompletionsPromptInput = { - prompt: string; -} & ChatCompletionsCommonOptions; -type ChatCompletionsMessagesInput = { - messages: Array; -} & ChatCompletionsCommonOptions; -type ChatCompletionsOutput = { - id: string; - object: string; - created: number; - model: string; - choices: Array; - 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 | 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; - 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 | null; - object?: "response"; - output?: Array; - parallel_tool_calls?: boolean; - temperature?: number | null; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - 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; - 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; -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; - 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; -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; -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; - role: "assistant"; - status: "in_progress" | "completed" | "incomplete"; - type: "message"; -}; -type ResponseOutputRefusal = { - refusal: string; - type: "refusal"; -}; -type ResponseOutputText = { - text: string; - type: "output_text"; - logprobs?: Array; -}; -type ResponseReasoningItem = { - id: string; - summary: Array; - type: "reasoning"; - content?: Array; - 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; - output_index: number; - sequence_number: number; - type: "response.output_text.delta"; -}; -type ResponseTextDoneEvent = { - content_index: number; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - text: string; - type: "response.output_text.done"; -}; -type Logprob = { - token: string; - logprob: number; - top_logprobs?: Array; -}; -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 = { - [P in Exclude]?: never; -}; -/** Either T or U, but not both (mutually exclusive) */ -type XOR = (T & Without) | (U & Without); -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); - /** - * 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); - /** - * 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); - 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; - postProcessedOutputs: XOR; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: XOR; - postProcessedOutputs: XOR; -} -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_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; -} -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/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B; -} -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 = XOR; -type ChatCompletionsInput = XOR; -interface InferenceUpstreamError extends Error { -} -interface AiInternalError extends Error { -} -type AiModelListType = Record; -type AiAsyncBatchResponse = { - request_id: string; -}; -declare abstract class Ai { - 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(model: Name, inputs: { - requests: AiModelList[Name]['inputs'][]; - }, options: AiOptions & { - queueRequest: true; - }): Promise; - // Raw response - run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { - returnRawResponse: true; - }): Promise; - // WebSocket - run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { - websocket: true; - }): Promise; - // Streaming - run(model: Name, inputs: AiModelList[Name]['inputs'] & { - stream: true; - }, options?: AiOptions): Promise; - // Normal (default) - known model - run(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise; - // Unknown model (gateway fallback) - run(model: string & {}, inputs: Record, options?: AiOptions): Promise>; - models(params?: AiModelsSearchParams): Promise; - toMarkdown(): ToMarkdownService; - toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; -} -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; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; -}; -type UniversalGatewayOptions = Exclude & { - /** - ** @deprecated - */ - id?: string; -}; -type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | 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; - 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; - '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; - query: unknown; -}; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { -} -declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { - gateway?: UniversalGatewayOptions; - extraHeaders?: object; - signal?: AbortSignal; - }): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // 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[]; - /** 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(). */ -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). - */ - createToken(scope?: 'write' | 'read', ttl?: number): Promise; - /** List tokens for this repo (metadata only, no plaintext). */ - listTokens(): Promise; - /** - * Revoke a token by plaintext or ID. - * @param tokenOrId Plaintext token or token ID. - * @returns true if revoked, false if not found. - */ - revokeToken(tokenOrId: string): Promise; - // ── Fork ── - /** - * Fork this repo to a new repo. - * @param name Target repository name. - * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true). - */ - fork(name: string, opts?: { - description?: string; - readOnly?: boolean; - defaultBranchOnly?: boolean; - }): Promise; -} -/** Artifacts binding — namespace-level operations. */ -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. - */ - create(name: string, opts?: { - readOnly?: boolean; - description?: string; - setDefaultBranch?: string; - }): Promise; - /** - * Get a handle to an existing repository. - * @param name Repository name. - * @returns Repo handle. - */ - get(name: string): Promise; - /** - * 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. - */ - import(params: { - source: { - url: string; - branch?: string; - depth?: number; - }; - target: { - name: string; - opts?: { - description?: string; - readOnly?: boolean; - }; - }; - }): Promise; - /** - * 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; - /** - * Delete a repository and all associated tokens. - * @param name Repository name. - * @returns true if deleted, false if not found. - */ - delete(name: string): Promise; -} -/** - * @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 & { - 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; - 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; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - search(params: AutoRagSearchRequest): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; -} -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; - /** - * 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. - * - 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" | "contain" | "cover" | "crop" | "pad" | "squeeze"; - /** - * 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"; - /** - * 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; - /** - * 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; - /** - * 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; -} -interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: 'remainder' | 'box-center'; -} -/** - * 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 { - 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; - /** - * 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; - 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; -} -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"; - /** - * 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 { - /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . - */ - dpr?: number; - /** - * 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; - }; - }; - /** - * 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"; - /** - * 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; - /** - * 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"; - /** - * 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; - }; - /** - * 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 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 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; - /** - * 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'; - /** - * 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 = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; -interface IncomingRequestCfPropertiesBase extends Record { - /** - * [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 { - /** - * 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; - /** 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; -} -/** 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: ""; -} -/** 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 = IncomingRequestCfProperties | 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; - error?: never; -} -type D1Result = 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(statements: D1PreparedStatement[]): Promise[]>; - exec(query: string): Promise; - /** - * 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; -} -declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - /** - * @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(colName: string): Promise; - first>(): Promise; - run>(): Promise>; - all>(): Promise>; - raw(options: { - columnNames: true; - }): Promise<[ - string[], - ...T[] - ]>; - raw(options?: { - columnNames?: false; - }): Promise; -} -// `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; - /** - * 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; - /** - * 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; -} -/** 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; -} -/** - * A binding that allows a Worker to send email messages. - */ -interface SendEmail { - send(message: EmailMessage): Promise; - send(builder: { - from: string | EmailAddress; - to: string | string[]; - subject: string; - replyTo?: string | EmailAddress; - cc?: string | string[]; - bcc?: string | string[]; - headers?: Record; - text?: string; - html?: string; - attachments?: EmailAttachment[]; - }): Promise; -} -declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; -} -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; -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; -interface FlagshipEvaluationDetails { - 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise; - /** - * 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>; - /** - * 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>; - /** - * 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>; - /** - * 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(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise>; -} -/** - * 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; -} -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; - /* - * 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; -} -// 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; -}; -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; - top?: number; - left?: number; - bottom?: number; - right?: number; -}; -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; - variants: string[]; - draft?: boolean; - creator?: string; -} -interface ImageUploadOptions { - id?: string; - filename?: string; - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; - encoding?: 'base64'; -} -interface ImageUpdateOptions { - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; -} -interface ImageListOptions { - limit?: number; - cursor?: string; - sortOrder?: 'asc' | 'desc'; - creator?: 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; - /** - * Get the raw image data for a hosted image - * @returns ReadableStream of image bytes, or null if not found - */ - bytes(): Promise | null>; - /** - * Update hosted image metadata - * @param options Properties to update - * @returns Updated image metadata - * @throws {@link ImagesError} if update fails - */ - update(options: ImageUpdateOptions): Promise; - /** - * Delete a hosted image - * @returns True if deleted, false if not found - */ - delete(): Promise; -} -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 | ArrayBuffer, options?: ImageUploadOptions): Promise; - /** - * 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; -} -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, options?: ImageInputOptions): Promise; - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input(stream: ReadableStream, options?: ImageInputOptions): 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 | 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; -} -type ImageTransformationOutputOptions = { - encoding?: 'base64'; -}; -interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream; -} -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): 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>; - /** - * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Promise, ready to store in cache or return to users - */ - response(): Promise; - /** - * Returns the MIME type of the transformed media. - * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') - */ - contentType(): Promise; -} -/** - * 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

= Record; -type EventContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; -}; -type PagesFunction = Record> = (context: EventContext) => Response | Promise; -type EventPluginContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; - pluginArgs: PluginArgs; -}; -type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; -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 { - 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; - } - export type PipelineRecord = Record; - export type PipelineBatchMetadata = { - pipelineId: string; - pipelineName: string; - }; - export interface Pipeline { - /** - * 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; - } -} -// 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; -} -// 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 = - // Structured cloneables - BaseType - // Structured cloneable composites - | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { - [K in keyof T]: K extends number | string ? Serializable : never; - } - // Special types - | Stub - // 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 extends Disposable { - [__RPC_STUB_BRAND]: T; - dup(): this; - } - export type Stub = Provider & StubBase; - // 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 | WritableStream | Request | Response | Headers; - // Recursively rewrite all `Stubable` types with `Stub`s - // prettier-ignore - type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: any; - } ? { - [K in keyof T]: Stubify; - } : T; - // Recursively rewrite all `Stub`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 extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: unknown; - } ? { - [K in keyof T]: Unstubify; - } : T; - type UnstubifyAll = { - [I in keyof A]: Unstubify; - }; - // Utility type for adding `Provider`/`Disposable`s to `object` types only. - // Note `unknown & T` is equivalent to `T`. - type MaybeProvider = T extends object ? Provider : unknown; - type MaybeDisposable = 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 extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : 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 extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result>; - // Type for the callable part of an `Provider` if `T` is callable. - // This is intersected with methods/properties. - type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : 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 = MaybeCallableProvider & Pick<{ - [K in keyof T]: MethodOrProperty; - }, Exclude>>; -} -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 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 - // 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 : DurableObjectNamespace : DurableObjectNamespace : {}); - }; -} -declare namespace CloudflareWorkersModule { - export type RpcStub = Rpc.Stub; - export const RpcStub: { - new (value: T): Rpc.Stub; - }; - 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 implements Rpc.WorkerEntrypointBranded { - [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - email?(message: ForwardableEmailMessage): void | Promise; - fetch?(request: Request): Response | Promise; - connect?(socket: Socket): void | Promise; - queue?(batch: MessageBatch): void | Promise; - scheduled?(controller: ScheduledController): void | Promise; - tail?(events: TraceItem[]): void | Promise; - tailStream?(event: TailStream.TailEvent): TailStream.TailEventHandlerType | Promise; - test?(controller: TestController): void | Promise; - trace?(traces: TraceItem[]): void | Promise; - } - export abstract class DurableObject implements Rpc.DurableObjectBranded { - [Rpc.__DURABLE_OBJECT_BRAND]: never; - protected ctx: DurableObjectState; - protected env: Env; - constructor(ctx: DurableObjectState, env: Env); - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - fetch?(request: Request): Response | Promise; - connect?(socket: Socket): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; - } - export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; - export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; - export type WorkflowDelayDuration = WorkflowSleepDuration; - export type WorkflowTimeoutDuration = WorkflowSleepDuration; - export type WorkflowRetentionDuration = WorkflowSleepDuration; - export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; - export type WorkflowStepConfig = { - retries?: { - limit: number; - delay: WorkflowDelayDuration | number; - backoff?: WorkflowBackoff; - }; - timeout?: WorkflowTimeoutDuration | number; - }; - export type WorkflowEvent = { - payload: Readonly; - timestamp: Date; - instanceId: string; - }; - export type WorkflowStepEvent = { - payload: Readonly; - timestamp: Date; - type: string; - }; - export type WorkflowStepContext = { - step: { - name: string; - count: number; - }; - attempt: number; - config: WorkflowStepConfig; - }; - export abstract class WorkflowStep { - do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; - sleep: (name: string, duration: WorkflowSleepDuration) => Promise; - sleepUntil: (name: string, timestamp: Date | number) => Promise; - waitForEvent>(name: string, options: { - type: string; - timeout?: WorkflowTimeoutDuration | number; - }): Promise>; - } - export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; - export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { - [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - run(event: Readonly>, step: WorkflowStep): Promise; - } - export function waitUntil(promise: Promise): 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; -} -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; - /** - * 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; - 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; - /** - * 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; - /** - * 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; - /** - * 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; - 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; - /** - * 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; - /** - * 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; - /** - * Lists the origins allowed to display the video. - */ - allowedOrigins?: Array; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; -} -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; - /** - * 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; - /** - * 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; -} -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; -} -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; - /** - * 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; - /** - * Lists all watermark profiles for an account. - * @returns The list of watermark profiles. - * @throws {InternalError} if an unexpected error occurs - */ - list(): Promise; - /** - * 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; - /** - * 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; -} -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; - /** - * 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; - /** - * 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 ConversionResponse = { - id: string; - name: string; - mimeType: string; - format: 'markdown'; - 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 ConversionOptions = { - 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; - transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; - supported(): Promise; -} -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"; - 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 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 name: string; - readonly message: string; - readonly stack?: string; - } - interface Log { - readonly type: "log"; - readonly level: "debug" | "error" | "info" | "log" | "warn"; - readonly message: object; - } - 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; - } - interface TailEvent { - // 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: TailEvent) => void | Promise; - type TailEventHandlerObject = { - outcome?: TailEventHandler; - spanOpen?: TailEventHandler; - spanClose?: TailEventHandler; - diagnosticChannel?: TailEventHandler; - exception?: TailEventHandler; - log?: TailEventHandler; - return?: TailEventHandler; - attributes?: TailEventHandler; - }; - 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; -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 | null | { - [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; - } | { - [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; - }; -}; -/** - * 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; -} -/** - * Represents a matched vector for a query along with its score and (if specified) the matching vector information. - */ -type VectorizeMatch = Pick, "values"> & Omit & { - /** 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; -} -/** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; -} -/** - * 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; -}; -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 { - /** - * 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; - /** - * 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): Promise; - /** - * 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[]): Promise; -} -type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; -type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; -type WorkflowRetentionDuration = WorkflowSleepDuration; -interface WorkflowInstanceCreateOptions { - /** - * 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; - }; -} -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; -} -declare abstract class WorkflowInstance { - public id: string; - /** - * Pause the instance. - */ - public pause(): Promise; - /** - * Resume the instance. If it is already running, an error will be thrown. - */ - public resume(): Promise; - /** - * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. - */ - public terminate(): Promise; - /** - * Restart the instance. - */ - public restart(): Promise; - /** - * Returns the current status of the instance. - */ - public status(): Promise; - /** - * Send an event to this instance. - */ - public sendEvent({ type, payload, }: { - type: string; - payload: unknown; - }): Promise; -} diff --git a/packages/www/wrangler.jsonc b/packages/www/wrangler.jsonc deleted file mode 100644 index c0520f8..0000000 --- a/packages/www/wrangler.jsonc +++ /dev/null @@ -1,38 +0,0 @@ -{ - "compatibility_date": "2026-05-10", - "compatibility_flags": [ - "global_fetch_strictly_public" - ], - "name": "www", - "main": "@astrojs/cloudflare/entrypoints/server", - "assets": { - "directory": "./dist", - "binding": "ASSETS" - }, - "observability": { - "enabled": true - }, - "vars": { - "RFD_DEFAULT_OWNER": "", - "RFD_ADMIN_TOKEN": "" - }, - "d1_databases": [ - { - "binding": "DB", - "database_name": "rfd", - "database_id": "00000000-0000-0000-0000-000000000000", - "migrations_dir": "migrations" - }, - { - "binding": "db", - "database_name": "db", - "database_id": "28268fa4-64f6-4a97-aa95-e569d26fc5c1" - } - ], - "services": [ - { - "binding": "SPACEDUST", - "service": "www-spacedust" - } - ] -} \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a8dfbe..2bc3fe5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,24 +8,24 @@ importers: .: {} - packages/lexicon: + packages/core: dependencies: - '@atcute/lexicons': + '@atcute/identity-resolver': specifier: ^2.0.0 - version: 2.0.0 + version: 2.0.0(@atcute/identity@2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3) devDependencies: - '@atcute/atproto': + '@types/node': + specifier: ^26.1.2 + version: 26.1.2 + vitest: specifier: ^4.0.0 - version: 4.0.0(@atcute/lexicons@2.0.0) - '@atcute/lex-cli': - specifier: ^3.0.0 - version: 3.0.0(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1)(typescript@6.0.3) + version: 4.1.5(@types/node@26.1.2)(vite@8.0.11(@types/node@26.1.2)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4)) packages/www: dependencies: - '@astrojs/cloudflare': - specifier: ^13.5.0 - version: 13.5.0(astro@6.3.1(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4))(jiti@2.7.0)(lightningcss@1.32.0)(workerd@1.20260507.1)(wrangler@4.90.0(@cloudflare/workers-types@4.20260509.1))(yaml@2.8.4) + '@astrojs/node': + specifier: ^10.1.1 + version: 10.1.1(astro@6.3.1(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4)) '@atcute/atproto': specifier: ^4.0.0 version: 4.0.0(@atcute/lexicons@2.0.0) @@ -44,18 +44,15 @@ importers: '@atcute/oauth-browser-client': specifier: ^4.0.0 version: 4.0.0(@atcute/identity-resolver@2.0.0(@atcute/identity@2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3) + '@rfd/core': + specifier: workspace:* + version: link:../core astro: specifier: ^6.3.1 - version: 6.3.1(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4) + version: 6.3.1(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4) hono: specifier: ^4.0.0 version: 4.12.18 - lexicon: - specifier: workspace:* - version: link:../lexicon - wrangler: - specifier: ^4.90.0 - version: 4.90.0(@cloudflare/workers-types@4.20260509.1) devDependencies: '@astrojs/check': specifier: ^0.9.9 @@ -63,12 +60,9 @@ importers: '@astrojs/compiler-rs': specifier: ^0.1.10 version: 0.1.10(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) - '@cloudflare/workers-types': - specifier: ^4.0.0 - version: 4.20260509.1 vitest: specifier: ^4.0.0 - version: 4.1.5(vite@8.0.11(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4)) + version: 4.1.5(@types/node@26.1.2)(vite@8.0.11(@types/node@26.1.2)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4)) packages: @@ -78,12 +72,6 @@ packages: peerDependencies: typescript: ^5.0.0 || ^6.0.0 - '@astrojs/cloudflare@13.5.0': - resolution: {integrity: sha512-kP3/SwPzZi7tq+fZG6H9GpaYQF3jw9L6vg92QL6q7FLI7t0rGiuG6Q0AckeJYjBUsO4Y+2w7aI7m+Q2r/WpssQ==} - peerDependencies: - astro: ^6.3.0 - wrangler: ^4.83.0 - '@astrojs/compiler-binding-darwin-arm64@0.1.10': resolution: {integrity: sha512-zDYwHvXVCm91XUm5xBRPbZK6yx9foM+Ut2qHiL0L37r1daF1bGLhnYjNV/VP35OLH5o/A1j+9uvl1xEX2a3ftw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -101,24 +89,28 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] + libc: [glibc] '@astrojs/compiler-binding-linux-arm64-musl@0.1.10': resolution: {integrity: sha512-ot1Lksml0FqrrlYa89wGXQM+n290ncj65PZAq8siEWmXsmwoNCYCbqRSwRO6I/cT+PDlmmV0AcFTrp1DEO3PUA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] + libc: [musl] '@astrojs/compiler-binding-linux-x64-gnu@0.1.10': resolution: {integrity: sha512-RGKGCbCvDat+DppnQbiWIhif6ptvkyXMdqOa7NjES4UoqIIUjE3YZfRn8gp3bXUe4ReWv4hGO1TQd2eitONt1g==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] + libc: [glibc] '@astrojs/compiler-binding-linux-x64-musl@0.1.10': resolution: {integrity: sha512-UemMv5Xq9c7trG9Cel4MHAo2wYiCxZ6qIKUnI4NJqBXDtOBqAjcMoqMbw78KYkb9vg2OIewVaJ+YvQrFZs5VBg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] + libc: [musl] '@astrojs/compiler-binding-wasm32-wasi@0.1.10': resolution: {integrity: sha512-SwawjgiYnm7s5neVKRoHIsnGG06vhuFhKg0iMBO6EsnL19xVbUp61V50gVtdgFlsfXalfH6SHuv2wQw8FhFSNg==} @@ -153,6 +145,9 @@ packages: '@astrojs/internal-helpers@0.9.0': resolution: {integrity: sha512-GdYkzR26re8izmyYlBqf4z2s7zNngmWLFuxw0UKiPNqHraZGS6GKWIwSHgS22RDlu2ePFJ8bzmpBcUszut/SDg==} + '@astrojs/internal-helpers@0.9.1': + resolution: {integrity: sha512-1pWuARqYom/TzuU3+0ZugsTrKlUydWKuULmDqSMTuonY+9IRDUEGKX/8PXQ1nBxRq3w85uGtd9q9SXfqEldMIQ==} + '@astrojs/language-server@2.16.8': resolution: {integrity: sha512-yg1pZF6hs9FaKr2fgXMOGbW7pDLgFexFjuhWilPAc8VybTU+WSnbfbhYaUL1exm6dAK4sM3aKXGcfVwss+HXbg==} hasBin: true @@ -168,6 +163,11 @@ packages: '@astrojs/markdown-remark@7.1.1': resolution: {integrity: sha512-C6e9BnLGlbdv6bV8MYGeHpHxsUHrCrB4OuRLqi5LI7oiBVcBcqfUN06zpwFQdHgV48QCCrMmLpyqBr7VqC+swA==} + '@astrojs/node@10.1.1': + resolution: {integrity: sha512-kCRbxconkgPpY4vR0GS7exovWEiCbxXLarsp+JeKixyDNf+fKN6v7jXDL8KdQgrzjhy131Kvl+GGGX8jGd8adA==} + peerDependencies: + astro: ^6.3.0 + '@astrojs/prism@4.0.1': resolution: {integrity: sha512-nksZQVjlferuWzhPsBpQ1JE5XuKAf1id1/9Hj4a9KG4+ofrlzxUUwX4YGQF/SuDiuiGKEnzopGOt38F3AnVWsQ==} engines: {node: '>=22.12.0'} @@ -176,9 +176,6 @@ packages: resolution: {integrity: sha512-j8DNruA8ors99Al39RYZPJK4DC1bKkoNm93mAMuBhY9TCNC4R8n1q7ovFnJ5qhGh5Lsh7pa1gpQVpYpsJPeTHQ==} engines: {node: 18.20.8 || ^20.3.0 || >=22.0.0} - '@astrojs/underscore-redirects@1.0.3': - resolution: {integrity: sha512-cxnGSw+sJigBLdX4TMSZKkzV6C3gMLJMucDk2W+n281Xhie68T2/9f1+1NMNDCZsc5i0FED7Qt5I10g2O9wtZg==} - '@astrojs/yaml2ts@0.2.3': resolution: {integrity: sha512-PJzRmgQzUxI2uwpdX2lXSHtP4G8ocp24/t+bZyf5Fy0SZLSF9f9KXZoMlFM/XCGue+B0nH/2IZ7FpBYQATBsCg==} @@ -187,20 +184,6 @@ packages: peerDependencies: '@atcute/lexicons': ^2.0.0 - '@atcute/car@6.0.0': - resolution: {integrity: sha512-v3lhHfqxBi/wxq3q4N9f3/9ed44xqwKI0VAlgPge9NKjJ2xuJcEvj12v4m+P2FB758cioCsghKy58tz2s20eAA==} - peerDependencies: - '@atcute/cbor': ^2.0.0 - '@atcute/cid': ^2.0.0 - - '@atcute/cbor@2.3.3': - resolution: {integrity: sha512-zZ4nHOK837zTMWJtta35YD7pcukrTzDc8jkpIGlSgoDYzu3l4BX3WVgpPJtRn3K6h2v97uyiWfiVjSpM7JSFzQ==} - peerDependencies: - '@atcute/cid': ^2.0.0 - - '@atcute/cid@2.4.1': - resolution: {integrity: sha512-bwhna69RCv7yetXudtj+2qrMPYvhhIQqvJz6YUpUS98v7OdF3X2dnye9Nig2NDrklZcuyOsu7sQo7GOykJXRLQ==} - '@atcute/client@2.0.9': resolution: {integrity: sha512-QNDm9gMP6x9LY77ArwY+urQOBtQW74/onEAz42c40JxRm6Rl9K9cU4ROvNKJ+5cpVmEm1sthEWVRmDr5CSZENA==} @@ -209,9 +192,6 @@ packages: peerDependencies: '@atcute/lexicons': ^2.0.0 - '@atcute/crypto@2.4.1': - resolution: {integrity: sha512-tJ3Pi/XYcAsABKtqSlSOTKfO5YiQ4XdqlTuPS8HiRZSezOPcXBFFzAFWpSIJPURbVPFQL3LLrrK0Ea24wl5qeQ==} - '@atcute/identity-resolver@2.0.0': resolution: {integrity: sha512-IKg1BDQAF2bIdN10DL6KAXmTjK+3enTU2IRbuani9TsFahBwGZ7O5FiVmTiL6QlGfauGNW5S0xNCOxWXWMoR2Q==} peerDependencies: @@ -223,32 +203,9 @@ packages: peerDependencies: '@atcute/lexicons': ^2.0.0 - '@atcute/lex-cli@3.0.0': - resolution: {integrity: sha512-DWoSc+l/6zgShSn9sWJXxo2Qs100jTIws0uZ9zrqSbzSZcUccUTFWZWfQmti3g8yqdoD4Jey3BYcmyDrV9ymFA==} - hasBin: true - - '@atcute/lexicon-doc@3.0.0': - resolution: {integrity: sha512-hxBTEvO78X4j/HsGgcH8GKgMA9hP9FM6jtwQL8Yd6MIHtGXdB8QygvBmOAJEqm1oE9ckU1SSU3cwa2t4tbZZNw==} - peerDependencies: - '@atcute/lexicons': ^2.0.0 - - '@atcute/lexicon-resolver@1.0.0': - resolution: {integrity: sha512-4v3oSijgd3w9JS2BMsV1dfD+GD1ClQeuEJatM9b7rNffi1kMTSn/3nOQbJ1aNeXfqZbCkn3ATDRdvgki1xIAZw==} - peerDependencies: - '@atcute/identity': ^2.0.0 - '@atcute/identity-resolver': ^2.0.0 - '@atcute/lexicon-doc': ^3.0.0 - '@atcute/lexicons': ^2.0.0 - '@atcute/lexicons@2.0.0': resolution: {integrity: sha512-fIlwP+TPEAGoF5aU5s+f8N5sOjOu8Mww/sQL1B57Dp2hj3G/EWG9XwOHPokzycBCgXx+UxIIrzZCGy8whsVDZw==} - '@atcute/mst@1.0.1': - resolution: {integrity: sha512-F3PfHt/6RedpSCwPFVOK8YQ+9lohAqeqUfqWrXLEZUmSVjXPlhSY6re+fmAnNuYX1g124QprIea9G2K3IfymyQ==} - peerDependencies: - '@atcute/cbor': ^2.0.0 - '@atcute/cid': ^2.0.0 - '@atcute/multibase@1.2.0': resolution: {integrity: sha512-ZK2GRra+qIYq9nNuQB52m2ul0hOmCQEtPobGfTSUxm7pF0OGEkWGkWHugFhNEDVzHzTwPxHp6VGotdZFue4lYQ==} @@ -267,13 +224,6 @@ packages: '@atcute/oauth-types@1.0.0': resolution: {integrity: sha512-YOpjLU8H5PG6oKfgau+dx7rSmGsLxIA36MeGL7BDeopcyq80RqPSBAzOasEEsmbMRJ/nTsMRJhnmGkp3RCa/Zw==} - '@atcute/repo@1.0.0': - resolution: {integrity: sha512-3s6VDKMimmYxVXn9OTlYQ7bJGPRcZRyFZ+oF/IFdfm3PsEUxwwSXajw1bG0HVXns1rNgNnDUT0PqMlUd2GnjqA==} - peerDependencies: - '@atcute/cbor': ^2.0.0 - '@atcute/cid': ^2.0.0 - '@atcute/lexicons': ^2.0.0 - '@atcute/uint8array@1.1.1': resolution: {integrity: sha512-3LsC8XB8TKe9q/5hOA5sFuzGaIFdJZJNewC5OKa3o/eU6+K7JR6see9Zy2JbQERNVnRl11EzbNov1efgLMAs4g==} @@ -283,9 +233,6 @@ packages: '@atcute/util-text@1.3.1': resolution: {integrity: sha512-MRgJXkx67znuBXuoAYCJkBZyd3OApL7zZlNf5kXhuoCXcdiu1nblRDycYTADSkym4epBSQWxh26kmI9sewaq6A==} - '@atcute/varint@2.0.0': - resolution: {integrity: sha512-CEY/oVK/nVpL4e5y3sdenLETDL6/Xu5xsE/0TupK+f0Yv8jcD60t2gD8SHROWSvUwYLdkjczLCSA7YrtnjCzWw==} - '@babel/helper-string-parser@7.27.1': resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==} engines: {node: '>=6.9.0'} @@ -315,62 +262,6 @@ packages: resolution: {integrity: sha512-GgcWwRCs/xPtaqlMy8qRhPnZf9vlWcWZNHAitnVQ3yk7JmSralSiq5q07yaffYE8SogtDm7zFeKccx1QNVARpw==} engines: {node: '>= 20.12.0'} - '@cloudflare/kv-asset-handler@0.5.0': - resolution: {integrity: sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==} - engines: {node: '>=22.0.0'} - - '@cloudflare/unenv-preset@2.16.1': - resolution: {integrity: sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==} - peerDependencies: - unenv: 2.0.0-rc.24 - workerd: '>1.20260305.0 <2.0.0-0' - peerDependenciesMeta: - workerd: - optional: true - - '@cloudflare/vite-plugin@1.36.3': - resolution: {integrity: sha512-n3SZhEZQxk4B2xHaCwgXfc7oLkx/4leTxL254P09DK2Qoj1VVOqVELo62CsUYq5dZS+okMdeWqNa13xEOKMs4g==} - peerDependencies: - vite: ^6.1.0 || ^7.0.0 || ^8.0.0 - wrangler: ^4.90.0 - - '@cloudflare/workerd-darwin-64@1.20260507.1': - resolution: {integrity: sha512-S85aMwcaPJUjKWDiG6iMMnioKWtPLACa6m0j/EhHR1GYfVpnxb974cBc6d25L+sf7jHWHJI2u5hGp0UTJ7MtXQ==} - engines: {node: '>=16'} - cpu: [x64] - os: [darwin] - - '@cloudflare/workerd-darwin-arm64@1.20260507.1': - resolution: {integrity: sha512-GMEBu8Zp9Q97HLnf7bWJN4KjWpN5MxpeqdvHjBGWNl8UYprJI0k+Jkp89+Wh5S8vIon+HoVbDfOzPa7VwgL6Eg==} - engines: {node: '>=16'} - cpu: [arm64] - os: [darwin] - - '@cloudflare/workerd-linux-64@1.20260507.1': - resolution: {integrity: sha512-QlrKEBdgA3uVc0Ok0Q3+0/CW0CTjgj5ySir1i1YY5FXVv0X6GpwtnB5umjunjF2MFprss+L+iFGZzxcSvMC1nA==} - engines: {node: '>=16'} - cpu: [x64] - os: [linux] - - '@cloudflare/workerd-linux-arm64@1.20260507.1': - resolution: {integrity: sha512-eGbbupEtK2nh9V9Dhcx3vv3GTKeXqSVNgAEYVCCN0NGS9tl9HbMoHRX/4JL181FKXROMigWBCQVL//qPhsAzBQ==} - engines: {node: '>=16'} - cpu: [arm64] - os: [linux] - - '@cloudflare/workerd-windows-64@1.20260507.1': - resolution: {integrity: sha512-dmClJ/E0BAcuDetQIZFqbeAXejWrG5pysGRMQ6T83Y0IW/7IAamY2zFEkAJ10I5xwZsdHuYsZtzlOxpEXpJs7A==} - engines: {node: '>=16'} - cpu: [x64] - os: [win32] - - '@cloudflare/workers-types@4.20260509.1': - resolution: {integrity: sha512-jFlTTD+0MK/01TdL5sHIsQ8RqzfmvBsGl4hSp87INv2+JIs/JF6EL9J8enuCz6z3fNdfOKISNbGCIrzZRXVrcw==} - - '@cspotcode/source-map-support@0.8.1': - resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} - engines: {node: '>=12'} - '@emmetio/abbreviation@2.3.3': resolution: {integrity: sha512-mgv58UrU3rh4YgbE/TzgLQwJ3pFsHHhCLqY20aJq+9comytTXUDNGG/SMtSeMJdkpxgXSXunBGLD8Boka3JyVA==} @@ -401,312 +292,156 @@ packages: '@emnapi/wasi-threads@1.2.1': resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==} - '@esbuild/aix-ppc64@0.27.3': - resolution: {integrity: sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [aix] - '@esbuild/aix-ppc64@0.27.7': resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==} engines: {node: '>=18'} cpu: [ppc64] os: [aix] - '@esbuild/android-arm64@0.27.3': - resolution: {integrity: sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [android] - '@esbuild/android-arm64@0.27.7': resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==} engines: {node: '>=18'} cpu: [arm64] os: [android] - '@esbuild/android-arm@0.27.3': - resolution: {integrity: sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==} - engines: {node: '>=18'} - cpu: [arm] - os: [android] - '@esbuild/android-arm@0.27.7': resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==} engines: {node: '>=18'} cpu: [arm] os: [android] - '@esbuild/android-x64@0.27.3': - resolution: {integrity: sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [android] - '@esbuild/android-x64@0.27.7': resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==} engines: {node: '>=18'} cpu: [x64] os: [android] - '@esbuild/darwin-arm64@0.27.3': - resolution: {integrity: sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [darwin] - '@esbuild/darwin-arm64@0.27.7': resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==} engines: {node: '>=18'} cpu: [arm64] os: [darwin] - '@esbuild/darwin-x64@0.27.3': - resolution: {integrity: sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==} - engines: {node: '>=18'} - cpu: [x64] - os: [darwin] - '@esbuild/darwin-x64@0.27.7': resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==} engines: {node: '>=18'} cpu: [x64] os: [darwin] - '@esbuild/freebsd-arm64@0.27.3': - resolution: {integrity: sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==} - engines: {node: '>=18'} - cpu: [arm64] - os: [freebsd] - '@esbuild/freebsd-arm64@0.27.7': resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==} engines: {node: '>=18'} cpu: [arm64] os: [freebsd] - '@esbuild/freebsd-x64@0.27.3': - resolution: {integrity: sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==} - engines: {node: '>=18'} - cpu: [x64] - os: [freebsd] - '@esbuild/freebsd-x64@0.27.7': resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==} engines: {node: '>=18'} cpu: [x64] os: [freebsd] - '@esbuild/linux-arm64@0.27.3': - resolution: {integrity: sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [linux] - '@esbuild/linux-arm64@0.27.7': resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==} engines: {node: '>=18'} cpu: [arm64] os: [linux] - '@esbuild/linux-arm@0.27.3': - resolution: {integrity: sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==} - engines: {node: '>=18'} - cpu: [arm] - os: [linux] - '@esbuild/linux-arm@0.27.7': resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==} engines: {node: '>=18'} cpu: [arm] os: [linux] - '@esbuild/linux-ia32@0.27.3': - resolution: {integrity: sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==} - engines: {node: '>=18'} - cpu: [ia32] - os: [linux] - '@esbuild/linux-ia32@0.27.7': resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==} engines: {node: '>=18'} cpu: [ia32] os: [linux] - '@esbuild/linux-loong64@0.27.3': - resolution: {integrity: sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==} - engines: {node: '>=18'} - cpu: [loong64] - os: [linux] - '@esbuild/linux-loong64@0.27.7': resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==} engines: {node: '>=18'} cpu: [loong64] os: [linux] - '@esbuild/linux-mips64el@0.27.3': - resolution: {integrity: sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==} - engines: {node: '>=18'} - cpu: [mips64el] - os: [linux] - '@esbuild/linux-mips64el@0.27.7': resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==} engines: {node: '>=18'} cpu: [mips64el] os: [linux] - '@esbuild/linux-ppc64@0.27.3': - resolution: {integrity: sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [linux] - '@esbuild/linux-ppc64@0.27.7': resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==} engines: {node: '>=18'} cpu: [ppc64] os: [linux] - '@esbuild/linux-riscv64@0.27.3': - resolution: {integrity: sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==} - engines: {node: '>=18'} - cpu: [riscv64] - os: [linux] - '@esbuild/linux-riscv64@0.27.7': resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==} engines: {node: '>=18'} cpu: [riscv64] os: [linux] - '@esbuild/linux-s390x@0.27.3': - resolution: {integrity: sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==} - engines: {node: '>=18'} - cpu: [s390x] - os: [linux] - '@esbuild/linux-s390x@0.27.7': resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==} engines: {node: '>=18'} cpu: [s390x] os: [linux] - '@esbuild/linux-x64@0.27.3': - resolution: {integrity: sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==} - engines: {node: '>=18'} - cpu: [x64] - os: [linux] - '@esbuild/linux-x64@0.27.7': resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==} engines: {node: '>=18'} cpu: [x64] os: [linux] - '@esbuild/netbsd-arm64@0.27.3': - resolution: {integrity: sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==} - engines: {node: '>=18'} - cpu: [arm64] - os: [netbsd] - '@esbuild/netbsd-arm64@0.27.7': resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] - '@esbuild/netbsd-x64@0.27.3': - resolution: {integrity: sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==} - engines: {node: '>=18'} - cpu: [x64] - os: [netbsd] - '@esbuild/netbsd-x64@0.27.7': resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==} engines: {node: '>=18'} cpu: [x64] os: [netbsd] - '@esbuild/openbsd-arm64@0.27.3': - resolution: {integrity: sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openbsd] - '@esbuild/openbsd-arm64@0.27.7': resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] - '@esbuild/openbsd-x64@0.27.3': - resolution: {integrity: sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [openbsd] - '@esbuild/openbsd-x64@0.27.7': resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==} engines: {node: '>=18'} cpu: [x64] os: [openbsd] - '@esbuild/openharmony-arm64@0.27.3': - resolution: {integrity: sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openharmony] - '@esbuild/openharmony-arm64@0.27.7': resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==} engines: {node: '>=18'} cpu: [arm64] os: [openharmony] - '@esbuild/sunos-x64@0.27.3': - resolution: {integrity: sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==} - engines: {node: '>=18'} - cpu: [x64] - os: [sunos] - '@esbuild/sunos-x64@0.27.7': resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==} engines: {node: '>=18'} cpu: [x64] os: [sunos] - '@esbuild/win32-arm64@0.27.3': - resolution: {integrity: sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==} - engines: {node: '>=18'} - cpu: [arm64] - os: [win32] - '@esbuild/win32-arm64@0.27.7': resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==} engines: {node: '>=18'} cpu: [arm64] os: [win32] - '@esbuild/win32-ia32@0.27.3': - resolution: {integrity: sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==} - engines: {node: '>=18'} - cpu: [ia32] - os: [win32] - '@esbuild/win32-ia32@0.27.7': resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==} engines: {node: '>=18'} cpu: [ia32] os: [win32] - '@esbuild/win32-x64@0.27.3': - resolution: {integrity: sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==} - engines: {node: '>=18'} - cpu: [x64] - os: [win32] - '@esbuild/win32-x64@0.27.7': resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==} engines: {node: '>=18'} @@ -743,89 +478,105 @@ packages: resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==} cpu: [arm64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-arm@1.2.4': resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==} cpu: [arm] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-ppc64@1.2.4': resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==} cpu: [ppc64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-riscv64@1.2.4': resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==} cpu: [riscv64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-s390x@1.2.4': resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==} cpu: [s390x] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-x64@1.2.4': resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==} cpu: [x64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linuxmusl-arm64@1.2.4': resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==} cpu: [arm64] os: [linux] + libc: [musl] '@img/sharp-libvips-linuxmusl-x64@1.2.4': resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==} cpu: [x64] os: [linux] + libc: [musl] '@img/sharp-linux-arm64@0.34.5': resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] + libc: [glibc] '@img/sharp-linux-arm@0.34.5': resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm] os: [linux] + libc: [glibc] '@img/sharp-linux-ppc64@0.34.5': resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [ppc64] os: [linux] + libc: [glibc] '@img/sharp-linux-riscv64@0.34.5': resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [riscv64] os: [linux] + libc: [glibc] '@img/sharp-linux-s390x@0.34.5': resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [s390x] os: [linux] + libc: [glibc] '@img/sharp-linux-x64@0.34.5': resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] + libc: [glibc] '@img/sharp-linuxmusl-arm64@0.34.5': resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] + libc: [musl] '@img/sharp-linuxmusl-x64@0.34.5': resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] + libc: [musl] '@img/sharp-wasm32@0.34.5': resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==} @@ -850,48 +601,21 @@ packages: cpu: [x64] os: [win32] - '@jridgewell/resolve-uri@3.1.2': - resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} - engines: {node: '>=6.0.0'} - '@jridgewell/sourcemap-codec@1.5.5': resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} - '@jridgewell/trace-mapping@0.3.9': - resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} - '@napi-rs/wasm-runtime@1.1.4': resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==} peerDependencies: '@emnapi/core': ^1.7.1 '@emnapi/runtime': ^1.7.1 - '@noble/secp256k1@3.1.0': - resolution: {integrity: sha512-+F7iS7tUMaNGXcc9X3PjmjvuQnXEuSjCRNzVVA2xAcKXgCaP0dHYz4SFyt4FKNHef7sOP//xihowcySSS7PK9g==} - - '@optique/core@1.0.2': - resolution: {integrity: sha512-znsqMmjAdeOgSJzdJlpZpgAscojwQmeQYXzYnuEKllz5VCj6WyEkdzU4QuvJQtWQY3ve2taXwudEBRur0VHBOQ==} - engines: {bun: '>=1.2.0', deno: '>=2.3.0', node: '>=20.0.0'} - - '@optique/run@1.0.2': - resolution: {integrity: sha512-0Wc+zC8SLGV8zXQX+pk+o0c6wE/ddx/36CHZ0toTh5lApsjruUuGhqbxvljerAAG5un1xQbOLxzksBVC6UPgSg==} - engines: {bun: '>=1.2.0', deno: '>=2.3.0', node: '>=20.0.0'} - '@oslojs/encoding@1.1.0': resolution: {integrity: sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ==} '@oxc-project/types@0.128.0': resolution: {integrity: sha512-huv1Y/LzBJkBVHt3OlC7u0zHBW9qXf1FdD7sGmc1rXc2P1mTwHssYv7jyGx5KAACSCH+9B3Bhn6Z9luHRvf7pQ==} - '@poppinss/colors@4.1.6': - resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==} - - '@poppinss/dumper@0.6.5': - resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==} - - '@poppinss/exception@1.2.3': - resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==} - '@rolldown/binding-android-arm64@1.0.0-rc.18': resolution: {integrity: sha512-lIDyUAfD7U3+BWKzdxMbJcsYHuqXqmGz40aeRqvuAm3y5TkJSYTBW2RDrn65DJFPQqVjUAUqq5uz8urzQ8aBdQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -927,36 +651,42 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] + libc: [glibc] '@rolldown/binding-linux-arm64-musl@1.0.0-rc.18': resolution: {integrity: sha512-QWjdxN1HJCpBTAcZ5N5F7wju3gVPzRzSpmGzx7na0c/1qpN9CFil+xt+l9lV/1M6/gqHSNXCiqPfwhVJPeLnug==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] + libc: [musl] '@rolldown/binding-linux-ppc64-gnu@1.0.0-rc.18': resolution: {integrity: sha512-ugCOyj7a4d9h3q9B+wXmf6g3a68UsjGh6dob5DHevHGMwDUbhsYNbSPxJsENcIttJZ9jv7qGM2UesLw5jqIhdg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] + libc: [glibc] '@rolldown/binding-linux-s390x-gnu@1.0.0-rc.18': resolution: {integrity: sha512-kKWRhbsotpXkGbcd5dllUWg5gEXcDAa8u5YnP9AV5DYNbvJHGzzuwv7dpmhc8NqKMJldl0a+x76IHbspEpEmdA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] + libc: [glibc] '@rolldown/binding-linux-x64-gnu@1.0.0-rc.18': resolution: {integrity: sha512-uCo8ElcCIAMyYAZyuIZ81oFkhTSIllNvUCHCAlbhlN4ji3uC28h7IIdlXyIvGO7HsuqnV9p3rD/bpH7XhIyhRw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] + libc: [glibc] '@rolldown/binding-linux-x64-musl@1.0.0-rc.18': resolution: {integrity: sha512-XNOQZtuE6yUIvx4rwGemwh8kpL1xvU41FXy/s9K7T/3JVcqGzo3NfKM2HrbrGgfPYGFW42f07Wk++aOC6B9NWA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] + libc: [musl] '@rolldown/binding-openharmony-arm64@1.0.0-rc.18': resolution: {integrity: sha512-tSn/kzrfa7tNOXr7sEacDBN4YsIqTyLqh45IO0nHDwtpKIDNDJr+VFojt+4klSpChxB29JLyduSsE0MKEwa65A==} @@ -1027,66 +757,79 @@ packages: resolution: {integrity: sha512-DV6fJoxEYWJOvaZIsok7KrYl0tPvga5OZ2yvKHNNYyk/2roMLqQAbGhr78EQ5YhHpnhLKJD3S1WFusAkmUuV5g==} cpu: [arm] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.60.3': resolution: {integrity: sha512-mQKoJAzvuOs6F+TZybQO4GOTSMUu7v0WdxEk24krQ/uUxXoPTtHjuaUuPmFhtBcM4K0ons8nrE3JyhTuCFtT/w==} cpu: [arm] os: [linux] + libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.60.3': resolution: {integrity: sha512-Whjj2qoiJ6+OOJMGptTYazaJvjOJm+iKHpXQM1P3LzGjt7Ff++Tp7nH4N8J/BUA7R9IHfDyx4DJIflifwnbmIA==} cpu: [arm64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.60.3': resolution: {integrity: sha512-4YTNHKqGng5+yiZt3mg77nmyuCfmNfX4fPmyUapBcIk+BdwSwmCWGXOUxhXbBEkFHtoN5boLj/5NON+u5QC9tg==} cpu: [arm64] os: [linux] + libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.60.3': resolution: {integrity: sha512-SU3kNlhkpI4UqlUc2VXPGK9o886ZsSeGfMAX2ba2b8DKmMXq4AL7KUrkSWVbb7koVqx41Yczx6dx5PNargIrEA==} cpu: [loong64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-loong64-musl@4.60.3': resolution: {integrity: sha512-6lDLl5h4TXpB1mTf2rQWnAk/LcXrx9vBfu/DT5TIPhvMhRWaZ5MxkIc8u4lJAmBo6klTe1ywXIUHFjylW505sg==} cpu: [loong64] os: [linux] + libc: [musl] '@rollup/rollup-linux-ppc64-gnu@4.60.3': resolution: {integrity: sha512-BMo8bOw8evlup/8G+cj5xWtPyp93xPdyoSN16Zy90Q2QZ0ZYRhCt6ZJSwbrRzG9HApFabjwj2p25TUPDWrhzqQ==} cpu: [ppc64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-ppc64-musl@4.60.3': resolution: {integrity: sha512-E0L8X1dZN1/Rph+5VPF6Xj2G7JJvMACVXtamTJIDrVI44Y3K+G8gQaMEAavbqCGTa16InptiVrX6eM6pmJ+7qA==} cpu: [ppc64] os: [linux] + libc: [musl] '@rollup/rollup-linux-riscv64-gnu@4.60.3': resolution: {integrity: sha512-oZJ/WHaVfHUiRAtmTAeo3DcevNsVvH8mbvodjZy7D5QKvCefO371SiKRpxoDcCxB3PTRTLayWBkvmDQKTcX/sw==} cpu: [riscv64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.60.3': resolution: {integrity: sha512-Dhbyh7j9FybM3YaTgaHmVALwA8AkUwTPccyCQ79TG9AJUsMQqgN1DDEZNr4+QUfwiWvLDumW5vdwzoeUF+TNxQ==} cpu: [riscv64] os: [linux] + libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.60.3': resolution: {integrity: sha512-cJd1X5XhHHlltkaypz1UcWLA8AcoIi1aWhsvaWDskD1oz2eKCypnqvTQ8ykMNI0RSmm7NkTdSqSSD7zM0xa6Ig==} cpu: [s390x] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.60.3': resolution: {integrity: sha512-DAZDBHQfG2oQuhY7mc6I3/qB4LU2fQCjRvxbDwd/Jdvb9fypP4IJ4qmtu6lNjes6B531AI8cg1aKC2di97bUxA==} cpu: [x64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-musl@4.60.3': resolution: {integrity: sha512-cRxsE8c13mZOh3vP+wLDxpQBRrOHDIGOWyDL93Sy0Ga8y515fBcC2pjUfFwUe5T7tqvTvWbCpg1URM/AXdWIXA==} cpu: [x64] os: [linux] + libc: [musl] '@rollup/rollup-openbsd-x64@4.60.3': resolution: {integrity: sha512-QaWcIgRxqEdQdhJqW4DJctsH6HCmo5vHxY0krHSX4jMtOqfzC+dqDGuHM87bu4H8JBeibWx7jFz+h6/4C8wA5Q==} @@ -1149,13 +892,6 @@ packages: '@shikijs/vscode-textmate@10.0.2': resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==} - '@sindresorhus/is@7.2.0': - resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} - engines: {node: '>=18'} - - '@speed-highlight/core@1.2.15': - resolution: {integrity: sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==} - '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} @@ -1189,6 +925,9 @@ packages: '@types/nlcst@2.0.3': resolution: {integrity: sha512-vSYNSDe6Ix3q+6Z7ri9lyWqgGhJTmzRjZRqyq15N0Z/1/UnVsno9G/N40NBijoYx2seFDIl0+B2mgAb9mezUCA==} + '@types/node@26.1.2': + resolution: {integrity: sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==} + '@types/unist@3.0.3': resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} @@ -1299,9 +1038,6 @@ packages: bail@2.0.2: resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} - blake3-wasm@2.1.5: - resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} - boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} @@ -1406,6 +1142,10 @@ packages: defu@6.1.7: resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} + depd@2.0.0: + resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} + engines: {node: '>= 0.8'} + dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -1444,12 +1184,19 @@ packages: resolution: {integrity: sha512-2QF/g9/zTaPDc3BjNcVTGoBbXBgYfMTTceLaYcFJ/W9kggFUkhxD/hMEeuLKbugyef9SqAx8cpgwlIP/jinUTA==} engines: {node: '>=4'} + ee-first@1.1.1: + resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} + emmet@2.4.11: resolution: {integrity: sha512-23QPJB3moh/U9sT4rQzGgeyyGIrcM+GH5uVYg2C6wZIxAIJq7Ng3QLT79tl8FUwDXhyq9SusfknOrofAKqvgyQ==} emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + encodeurl@2.0.0: + resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} + engines: {node: '>= 0.8'} + entities@4.5.0: resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} engines: {node: '>=0.12'} @@ -1458,17 +1205,9 @@ packages: resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} engines: {node: '>=0.12'} - error-stack-parser-es@1.0.5: - resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==} - es-module-lexer@2.1.0: resolution: {integrity: sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==} - esbuild@0.27.3: - resolution: {integrity: sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==} - engines: {node: '>=18'} - hasBin: true - esbuild@0.27.7: resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==} engines: {node: '>=18'} @@ -1478,6 +1217,9 @@ packages: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} + escape-html@1.0.3: + resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} + escape-string-regexp@5.0.0: resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==} engines: {node: '>=12'} @@ -1491,6 +1233,10 @@ packages: estree-walker@3.0.3: resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + etag@1.8.1: + resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} + engines: {node: '>= 0.6'} + eventemitter3@5.0.4: resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==} @@ -1536,6 +1282,10 @@ packages: resolution: {integrity: sha512-Wp1zXWPVUPBmfoa3Cqc9ctaKuzKAV6uLstRqlR56kSjplf5uAce+qeyYym7F+PHbGTk+tCEdkCW6RD7DX/gBZw==} engines: {node: '>=20'} + fresh@2.0.0: + resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} + engines: {node: '>= 0.8'} + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -1598,6 +1348,13 @@ packages: http-cache-semantics@4.2.0: resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==} + http-errors@2.0.1: + resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==} + engines: {node: '>= 0.8'} + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + iron-webcrypto@1.2.1: resolution: {integrity: sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg==} @@ -1684,24 +1441,28 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [glibc] lightningcss-linux-arm64-musl@1.32.0: resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [musl] lightningcss-linux-x64-gnu@1.32.0: resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [glibc] lightningcss-linux-x64-musl@1.32.0: resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [musl] lightningcss-win32-arm64-msvc@1.32.0: resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} @@ -1864,10 +1625,13 @@ packages: micromark@4.0.2: resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==} - miniflare@4.20260507.1: - resolution: {integrity: sha512-PSXBiLExTdZ4UGO/raKCHQauUpYL7F880ZRB7j0+78Rv8h7TsdN2E/iEDK9sK2Y+SPQ5wJSeAa+rDeVKoZZoEw==} - engines: {node: '>=22.0.0'} - hasBin: true + mime-db@1.54.0: + resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} + engines: {node: '>= 0.6'} + + mime-types@3.0.2: + resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==} + engines: {node: '>=18'} mrmime@2.0.1: resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==} @@ -1918,6 +1682,10 @@ packages: ohash@2.0.11: resolution: {integrity: sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==} + on-finished@2.4.1: + resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==} + engines: {node: '>= 0.8'} + oniguruma-parser@0.12.2: resolution: {integrity: sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==} @@ -1948,9 +1716,6 @@ packages: path-browserify@1.0.1: resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} - path-to-regexp@6.3.0: - resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==} - pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} @@ -1987,6 +1752,10 @@ packages: radix3@1.1.2: resolution: {integrity: sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==} + range-parser@1.3.0: + resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==} + engines: {node: '>= 0.6'} + readdirp@4.1.2: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} @@ -2080,6 +1849,16 @@ packages: engines: {node: '>=10'} hasBin: true + send@1.2.1: + resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==} + engines: {node: '>= 18'} + + server-destroy@1.0.1: + resolution: {integrity: sha512-rb+9B5YBIEzYcD6x2VKidaa+cqYBJQKnU4oe4E3ANwRRN56yk/ua1YCJT1n21NTS8w6CcOclAKNP3PhdCXKYtQ==} + + setprototypeof@1.2.0: + resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} + sharp@0.34.5: resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} @@ -2108,6 +1887,10 @@ packages: stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + statuses@2.0.2: + resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} + engines: {node: '>= 0.8'} + std-env@4.1.0: resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} @@ -2122,10 +1905,6 @@ packages: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} - supports-color@10.2.2: - resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} - engines: {node: '>=18'} - svgo@4.0.1: resolution: {integrity: sha512-XDpWUOPC6FEibaLzjfe0ucaV0YrOjYotGJO1WpF0Zd+n6ZGEQUsSugaoLq9QkEZtAfQIxT42UChcssDVPP3+/w==} engines: {node: '>=16'} @@ -2153,6 +1932,10 @@ packages: resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} engines: {node: '>=14.0.0'} + toidentifier@1.0.1: + resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} + engines: {node: '>=0.6'} + trim-lines@3.0.1: resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} @@ -2182,12 +1965,8 @@ packages: uncrypto@0.1.3: resolution: {integrity: sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==} - undici@7.24.8: - resolution: {integrity: sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==} - engines: {node: '>=20.18.1'} - - unenv@2.0.0-rc.24: - resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==} + undici-types@8.3.0: + resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==} unicode-segmenter@0.14.5: resolution: {integrity: sha512-jHGmj2LUuqDcX3hqY12Ql+uhUTn8huuxNZGq7GvtF6bSybzH3aFgedYu/KTzQStEgt1Ra2F3HxadNXsNjb3m3g==} @@ -2540,37 +2319,10 @@ packages: engines: {node: '>=8'} hasBin: true - workerd@1.20260507.1: - resolution: {integrity: sha512-z7JhsFSe6+X1b5fUHaVpo15VM1IRMJiLofEkq8iKdCo+Veqc+FUg5lIsuz8NwePxuSKrXtO4ZQpGkQLbPVXFhg==} - engines: {node: '>=16'} - hasBin: true - - wrangler@4.90.0: - resolution: {integrity: sha512-bmNIykl59TfCUn5xQgU7IWylSsPx3LQaPLMSAq2VQHt89CBrcj9qXQ0eYfjBCWA5XTBVgten391evt7xxtXwcA==} - engines: {node: '>=22.0.0'} - hasBin: true - peerDependencies: - '@cloudflare/workers-types': ^4.20260507.1 - peerDependenciesMeta: - '@cloudflare/workers-types': - optional: true - wrap-ansi@7.0.0: resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} engines: {node: '>=10'} - ws@8.18.0: - resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==} - engines: {node: '>=10.0.0'} - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: '>=5.0.2' - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - xxhash-wasm@1.1.0: resolution: {integrity: sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==} @@ -2608,12 +2360,6 @@ packages: resolution: {integrity: sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==} engines: {node: '>=12.20'} - youch-core@0.3.3: - resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==} - - youch@4.1.0-beta.10: - resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==} - zod@4.4.3: resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} @@ -2633,32 +2379,6 @@ snapshots: - prettier - prettier-plugin-astro - '@astrojs/cloudflare@13.5.0(astro@6.3.1(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4))(jiti@2.7.0)(lightningcss@1.32.0)(workerd@1.20260507.1)(wrangler@4.90.0(@cloudflare/workers-types@4.20260509.1))(yaml@2.8.4)': - dependencies: - '@astrojs/internal-helpers': 0.9.0 - '@astrojs/underscore-redirects': 1.0.3 - '@cloudflare/vite-plugin': 1.36.3(vite@7.3.3(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4))(workerd@1.20260507.1)(wrangler@4.90.0(@cloudflare/workers-types@4.20260509.1)) - astro: 6.3.1(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4) - piccolore: 0.1.3 - tinyglobby: 0.2.16 - vite: 7.3.3(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4) - wrangler: 4.90.0(@cloudflare/workers-types@4.20260509.1) - transitivePeerDependencies: - - '@types/node' - - bufferutil - - jiti - - less - - lightningcss - - sass - - sass-embedded - - stylus - - sugarss - - terser - - tsx - - utf-8-validate - - workerd - - yaml - '@astrojs/compiler-binding-darwin-arm64@0.1.10': optional: true @@ -2721,6 +2441,10 @@ snapshots: dependencies: picomatch: 4.0.4 + '@astrojs/internal-helpers@0.9.1': + dependencies: + picomatch: 4.0.4 + '@astrojs/language-server@2.16.8(prettier@3.8.3)(typescript@6.0.3)': dependencies: '@astrojs/compiler': 2.13.1 @@ -2772,6 +2496,15 @@ snapshots: transitivePeerDependencies: - supports-color + '@astrojs/node@10.1.1(astro@6.3.1(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4))': + dependencies: + '@astrojs/internal-helpers': 0.9.1 + astro: 6.3.1(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4) + send: 1.2.1 + server-destroy: 1.0.1 + transitivePeerDependencies: + - supports-color + '@astrojs/prism@4.0.1': dependencies: prismjs: 1.30.0 @@ -2784,8 +2517,6 @@ snapshots: is-wsl: 3.1.1 which-pm-runs: 1.1.0 - '@astrojs/underscore-redirects@1.0.3': {} - '@astrojs/yaml2ts@0.2.3': dependencies: yaml: 2.8.4 @@ -2794,24 +2525,6 @@ snapshots: dependencies: '@atcute/lexicons': 2.0.0 - '@atcute/car@6.0.0(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1)': - dependencies: - '@atcute/cbor': 2.3.3(@atcute/cid@2.4.1) - '@atcute/cid': 2.4.1 - '@atcute/uint8array': 1.1.1 - '@atcute/varint': 2.0.0 - - '@atcute/cbor@2.3.3(@atcute/cid@2.4.1)': - dependencies: - '@atcute/cid': 2.4.1 - '@atcute/multibase': 1.2.0 - '@atcute/uint8array': 1.1.1 - - '@atcute/cid@2.4.1': - dependencies: - '@atcute/multibase': 1.2.0 - '@atcute/uint8array': 1.1.1 - '@atcute/client@2.0.9': {} '@atcute/client@5.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3)': @@ -2821,12 +2534,6 @@ snapshots: transitivePeerDependencies: - typescript - '@atcute/crypto@2.4.1': - dependencies: - '@atcute/multibase': 1.2.0 - '@atcute/uint8array': 1.1.1 - '@noble/secp256k1': 3.1.0 - '@atcute/identity-resolver@2.0.0(@atcute/identity@2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3)': dependencies: '@atcute/identity': 2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3) @@ -2843,48 +2550,6 @@ snapshots: transitivePeerDependencies: - typescript - '@atcute/lex-cli@3.0.0(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1)(typescript@6.0.3)': - dependencies: - '@atcute/identity': 2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3) - '@atcute/identity-resolver': 2.0.0(@atcute/identity@2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3) - '@atcute/lexicon-doc': 3.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3) - '@atcute/lexicon-resolver': 1.0.0(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1)(@atcute/identity-resolver@2.0.0(@atcute/identity@2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/identity@2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicon-doc@3.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3) - '@atcute/lexicons': 2.0.0 - '@optique/core': 1.0.2 - '@optique/run': 1.0.2 - picocolors: 1.1.1 - prettier: 3.8.3 - valibot: 1.4.0(typescript@6.0.3) - transitivePeerDependencies: - - '@atcute/cbor' - - '@atcute/cid' - - typescript - - '@atcute/lexicon-doc@3.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3)': - dependencies: - '@atcute/identity': 2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3) - '@atcute/lexicons': 2.0.0 - '@atcute/uint8array': 1.1.1 - '@atcute/util-text': 1.3.1 - valibot: 1.4.0(typescript@6.0.3) - transitivePeerDependencies: - - typescript - - '@atcute/lexicon-resolver@1.0.0(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1)(@atcute/identity-resolver@2.0.0(@atcute/identity@2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/identity@2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicon-doc@3.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3)': - dependencies: - '@atcute/crypto': 2.4.1 - '@atcute/identity': 2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3) - '@atcute/identity-resolver': 2.0.0(@atcute/identity@2.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3))(@atcute/lexicons@2.0.0)(typescript@6.0.3) - '@atcute/lexicon-doc': 3.0.0(@atcute/lexicons@2.0.0)(typescript@6.0.3) - '@atcute/lexicons': 2.0.0 - '@atcute/repo': 1.0.0(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1)(@atcute/lexicons@2.0.0) - '@atcute/util-fetch': 2.0.0(typescript@6.0.3) - valibot: 1.4.0(typescript@6.0.3) - transitivePeerDependencies: - - '@atcute/cbor' - - '@atcute/cid' - - typescript - '@atcute/lexicons@2.0.0': dependencies: '@atcute/uint8array': 1.1.1 @@ -2892,12 +2557,6 @@ snapshots: '@standard-schema/spec': 1.1.0 esm-env: 1.2.2 - '@atcute/mst@1.0.1(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1)': - dependencies: - '@atcute/cbor': 2.3.3(@atcute/cid@2.4.1) - '@atcute/cid': 2.4.1 - '@atcute/uint8array': 1.1.1 - '@atcute/multibase@1.2.0': dependencies: '@atcute/uint8array': 1.1.1 @@ -2938,16 +2597,6 @@ snapshots: transitivePeerDependencies: - typescript - '@atcute/repo@1.0.0(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1)(@atcute/lexicons@2.0.0)': - dependencies: - '@atcute/car': 6.0.0(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1) - '@atcute/cbor': 2.3.3(@atcute/cid@2.4.1) - '@atcute/cid': 2.4.1 - '@atcute/crypto': 2.4.1 - '@atcute/lexicons': 2.0.0 - '@atcute/mst': 1.0.1(@atcute/cbor@2.3.3(@atcute/cid@2.4.1))(@atcute/cid@2.4.1) - '@atcute/uint8array': 1.1.1 - '@atcute/uint8array@1.1.1': {} '@atcute/util-fetch@2.0.0(typescript@6.0.3)': @@ -2960,8 +2609,6 @@ snapshots: dependencies: unicode-segmenter: 0.14.5 - '@atcute/varint@2.0.0': {} - '@babel/helper-string-parser@7.27.1': {} '@babel/helper-validator-identifier@7.28.5': {} @@ -2991,48 +2638,6 @@ snapshots: fast-wrap-ansi: 0.2.0 sisteransi: 1.0.5 - '@cloudflare/kv-asset-handler@0.5.0': {} - - '@cloudflare/unenv-preset@2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260507.1)': - dependencies: - unenv: 2.0.0-rc.24 - optionalDependencies: - workerd: 1.20260507.1 - - '@cloudflare/vite-plugin@1.36.3(vite@7.3.3(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4))(workerd@1.20260507.1)(wrangler@4.90.0(@cloudflare/workers-types@4.20260509.1))': - dependencies: - '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260507.1) - miniflare: 4.20260507.1 - unenv: 2.0.0-rc.24 - vite: 7.3.3(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4) - wrangler: 4.90.0(@cloudflare/workers-types@4.20260509.1) - ws: 8.18.0 - transitivePeerDependencies: - - bufferutil - - utf-8-validate - - workerd - - '@cloudflare/workerd-darwin-64@1.20260507.1': - optional: true - - '@cloudflare/workerd-darwin-arm64@1.20260507.1': - optional: true - - '@cloudflare/workerd-linux-64@1.20260507.1': - optional: true - - '@cloudflare/workerd-linux-arm64@1.20260507.1': - optional: true - - '@cloudflare/workerd-windows-64@1.20260507.1': - optional: true - - '@cloudflare/workers-types@4.20260509.1': {} - - '@cspotcode/source-map-support@0.8.1': - dependencies: - '@jridgewell/trace-mapping': 0.3.9 - '@emmetio/abbreviation@2.3.3': dependencies: '@emmetio/scanner': 1.0.4 @@ -3072,163 +2677,86 @@ snapshots: tslib: 2.8.1 optional: true - '@esbuild/aix-ppc64@0.27.3': - optional: true - '@esbuild/aix-ppc64@0.27.7': optional: true - '@esbuild/android-arm64@0.27.3': - optional: true - '@esbuild/android-arm64@0.27.7': optional: true - '@esbuild/android-arm@0.27.3': - optional: true - '@esbuild/android-arm@0.27.7': optional: true - '@esbuild/android-x64@0.27.3': - optional: true - '@esbuild/android-x64@0.27.7': optional: true - '@esbuild/darwin-arm64@0.27.3': - optional: true - '@esbuild/darwin-arm64@0.27.7': optional: true - '@esbuild/darwin-x64@0.27.3': - optional: true - '@esbuild/darwin-x64@0.27.7': optional: true - '@esbuild/freebsd-arm64@0.27.3': - optional: true - '@esbuild/freebsd-arm64@0.27.7': optional: true - '@esbuild/freebsd-x64@0.27.3': - optional: true - '@esbuild/freebsd-x64@0.27.7': optional: true - '@esbuild/linux-arm64@0.27.3': - optional: true - '@esbuild/linux-arm64@0.27.7': optional: true - '@esbuild/linux-arm@0.27.3': - optional: true - '@esbuild/linux-arm@0.27.7': optional: true - '@esbuild/linux-ia32@0.27.3': - optional: true - '@esbuild/linux-ia32@0.27.7': optional: true - '@esbuild/linux-loong64@0.27.3': - optional: true - '@esbuild/linux-loong64@0.27.7': optional: true - '@esbuild/linux-mips64el@0.27.3': - optional: true - '@esbuild/linux-mips64el@0.27.7': optional: true - '@esbuild/linux-ppc64@0.27.3': - optional: true - '@esbuild/linux-ppc64@0.27.7': optional: true - '@esbuild/linux-riscv64@0.27.3': - optional: true - '@esbuild/linux-riscv64@0.27.7': optional: true - '@esbuild/linux-s390x@0.27.3': - optional: true - '@esbuild/linux-s390x@0.27.7': optional: true - '@esbuild/linux-x64@0.27.3': - optional: true - '@esbuild/linux-x64@0.27.7': optional: true - '@esbuild/netbsd-arm64@0.27.3': - optional: true - '@esbuild/netbsd-arm64@0.27.7': optional: true - '@esbuild/netbsd-x64@0.27.3': - optional: true - '@esbuild/netbsd-x64@0.27.7': optional: true - '@esbuild/openbsd-arm64@0.27.3': - optional: true - '@esbuild/openbsd-arm64@0.27.7': optional: true - '@esbuild/openbsd-x64@0.27.3': - optional: true - '@esbuild/openbsd-x64@0.27.7': optional: true - '@esbuild/openharmony-arm64@0.27.3': - optional: true - '@esbuild/openharmony-arm64@0.27.7': optional: true - '@esbuild/sunos-x64@0.27.3': - optional: true - '@esbuild/sunos-x64@0.27.7': optional: true - '@esbuild/win32-arm64@0.27.3': - optional: true - '@esbuild/win32-arm64@0.27.7': optional: true - '@esbuild/win32-ia32@0.27.3': - optional: true - '@esbuild/win32-ia32@0.27.7': optional: true - '@esbuild/win32-x64@0.27.3': - optional: true - '@esbuild/win32-x64@0.27.7': optional: true - '@img/colour@1.1.0': {} + '@img/colour@1.1.0': + optional: true '@img/sharp-darwin-arm64@0.34.5': optionalDependencies: @@ -3324,15 +2852,8 @@ snapshots: '@img/sharp-win32-x64@0.34.5': optional: true - '@jridgewell/resolve-uri@3.1.2': {} - '@jridgewell/sourcemap-codec@1.5.5': {} - '@jridgewell/trace-mapping@0.3.9': - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.5.5 - '@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': dependencies: '@emnapi/core': 1.10.0 @@ -3340,30 +2861,10 @@ snapshots: '@tybys/wasm-util': 0.10.2 optional: true - '@noble/secp256k1@3.1.0': {} - - '@optique/core@1.0.2': {} - - '@optique/run@1.0.2': - dependencies: - '@optique/core': 1.0.2 - '@oslojs/encoding@1.1.0': {} '@oxc-project/types@0.128.0': {} - '@poppinss/colors@4.1.6': - dependencies: - kleur: 4.1.5 - - '@poppinss/dumper@0.6.5': - dependencies: - '@poppinss/colors': 4.1.6 - '@sindresorhus/is': 7.2.0 - supports-color: 10.2.2 - - '@poppinss/exception@1.2.3': {} - '@rolldown/binding-android-arm64@1.0.0-rc.18': optional: true @@ -3538,10 +3039,6 @@ snapshots: '@shikijs/vscode-textmate@10.0.2': {} - '@sindresorhus/is@7.2.0': {} - - '@speed-highlight/core@1.2.15': {} - '@standard-schema/spec@1.1.0': {} '@tybys/wasm-util@0.10.2': @@ -3578,6 +3075,10 @@ snapshots: dependencies: '@types/unist': 3.0.3 + '@types/node@26.1.2': + dependencies: + undici-types: 8.3.0 + '@types/unist@3.0.3': {} '@ungap/structured-clone@1.3.1': {} @@ -3591,13 +3092,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.5(vite@8.0.11(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4))': + '@vitest/mocker@4.1.5(vite@8.0.11(@types/node@26.1.2)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4))': dependencies: '@vitest/spy': 4.1.5 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 8.0.11(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4) + vite: 8.0.11(@types/node@26.1.2)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4) '@vitest/pretty-format@4.1.5': dependencies: @@ -3703,7 +3204,7 @@ snapshots: assertion-error@2.0.1: {} - astro@6.3.1(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4): + astro@6.3.1(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(rollup@4.60.3)(yaml@2.8.4): dependencies: '@astrojs/compiler': 4.0.0 '@astrojs/internal-helpers': 0.9.0 @@ -3755,8 +3256,8 @@ snapshots: unist-util-visit: 5.1.0 unstorage: 1.17.5 vfile: 6.0.3 - vite: 7.3.3(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4) - vitefu: 1.1.3(vite@7.3.3(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)) + vite: 7.3.3(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4) + vitefu: 1.1.3(vite@7.3.3(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)) xxhash-wasm: 1.1.0 yargs-parser: 22.0.0 zod: 4.4.3 @@ -3800,8 +3301,6 @@ snapshots: bail@2.0.2: {} - blake3-wasm@2.1.5: {} - boolbase@1.0.0: {} ccount@2.0.1: {} @@ -3888,6 +3387,8 @@ snapshots: defu@6.1.7: {} + depd@2.0.0: {} + dequal@2.0.3: {} destr@2.0.5: {} @@ -3922,6 +3423,8 @@ snapshots: dset@3.1.4: {} + ee-first@1.1.1: {} + emmet@2.4.11: dependencies: '@emmetio/abbreviation': 2.3.3 @@ -3929,43 +3432,14 @@ snapshots: emoji-regex@8.0.0: {} + encodeurl@2.0.0: {} + entities@4.5.0: {} entities@6.0.1: {} - error-stack-parser-es@1.0.5: {} - es-module-lexer@2.1.0: {} - esbuild@0.27.3: - optionalDependencies: - '@esbuild/aix-ppc64': 0.27.3 - '@esbuild/android-arm': 0.27.3 - '@esbuild/android-arm64': 0.27.3 - '@esbuild/android-x64': 0.27.3 - '@esbuild/darwin-arm64': 0.27.3 - '@esbuild/darwin-x64': 0.27.3 - '@esbuild/freebsd-arm64': 0.27.3 - '@esbuild/freebsd-x64': 0.27.3 - '@esbuild/linux-arm': 0.27.3 - '@esbuild/linux-arm64': 0.27.3 - '@esbuild/linux-ia32': 0.27.3 - '@esbuild/linux-loong64': 0.27.3 - '@esbuild/linux-mips64el': 0.27.3 - '@esbuild/linux-ppc64': 0.27.3 - '@esbuild/linux-riscv64': 0.27.3 - '@esbuild/linux-s390x': 0.27.3 - '@esbuild/linux-x64': 0.27.3 - '@esbuild/netbsd-arm64': 0.27.3 - '@esbuild/netbsd-x64': 0.27.3 - '@esbuild/openbsd-arm64': 0.27.3 - '@esbuild/openbsd-x64': 0.27.3 - '@esbuild/openharmony-arm64': 0.27.3 - '@esbuild/sunos-x64': 0.27.3 - '@esbuild/win32-arm64': 0.27.3 - '@esbuild/win32-ia32': 0.27.3 - '@esbuild/win32-x64': 0.27.3 - esbuild@0.27.7: optionalDependencies: '@esbuild/aix-ppc64': 0.27.7 @@ -3997,6 +3471,8 @@ snapshots: escalade@3.2.0: {} + escape-html@1.0.3: {} + escape-string-regexp@5.0.0: {} esm-env@1.2.2: {} @@ -4007,6 +3483,8 @@ snapshots: dependencies: '@types/estree': 1.0.9 + etag@1.8.1: {} + eventemitter3@5.0.4: {} expect-type@1.3.0: {} @@ -4041,6 +3519,8 @@ snapshots: dependencies: tiny-inflate: 1.0.3 + fresh@2.0.0: {} + fsevents@2.3.3: optional: true @@ -4159,6 +3639,16 @@ snapshots: http-cache-semantics@4.2.0: {} + http-errors@2.0.1: + dependencies: + depd: 2.0.0 + inherits: 2.0.4 + setprototypeof: 1.2.0 + statuses: 2.0.2 + toidentifier: 1.0.1 + + inherits@2.0.4: {} + iron-webcrypto@1.2.1: {} is-docker@3.0.0: {} @@ -4572,17 +4062,11 @@ snapshots: transitivePeerDependencies: - supports-color - miniflare@4.20260507.1: + mime-db@1.54.0: {} + + mime-types@3.0.2: dependencies: - '@cspotcode/source-map-support': 0.8.1 - sharp: 0.34.5 - undici: 7.24.8 - workerd: 1.20260507.1 - ws: 8.18.0 - youch: 4.1.0-beta.10 - transitivePeerDependencies: - - bufferutil - - utf-8-validate + mime-db: 1.54.0 mrmime@2.0.1: {} @@ -4620,6 +4104,10 @@ snapshots: ohash@2.0.11: {} + on-finished@2.4.1: + dependencies: + ee-first: 1.1.1 + oniguruma-parser@0.12.2: {} oniguruma-to-es@4.3.6: @@ -4656,8 +4144,6 @@ snapshots: path-browserify@1.0.1: {} - path-to-regexp@6.3.0: {} - pathe@2.0.3: {} piccolore@0.1.3: {} @@ -4682,6 +4168,8 @@ snapshots: radix3@1.1.2: {} + range-parser@1.3.0: {} + readdirp@4.1.2: {} readdirp@5.0.0: {} @@ -4853,6 +4341,26 @@ snapshots: semver@7.8.0: {} + send@1.2.1: + dependencies: + debug: 4.4.3 + encodeurl: 2.0.0 + escape-html: 1.0.3 + etag: 1.8.1 + fresh: 2.0.0 + http-errors: 2.0.1 + mime-types: 3.0.2 + ms: 2.1.3 + on-finished: 2.4.1 + range-parser: 1.3.0 + statuses: 2.0.2 + transitivePeerDependencies: + - supports-color + + server-destroy@1.0.1: {} + + setprototypeof@1.2.0: {} + sharp@0.34.5: dependencies: '@img/colour': 1.1.0 @@ -4883,6 +4391,7 @@ snapshots: '@img/sharp-win32-arm64': 0.34.5 '@img/sharp-win32-ia32': 0.34.5 '@img/sharp-win32-x64': 0.34.5 + optional: true shiki@4.0.2: dependencies: @@ -4907,6 +4416,8 @@ snapshots: stackback@0.0.2: {} + statuses@2.0.2: {} + std-env@4.1.0: {} string-width@4.2.3: @@ -4924,8 +4435,6 @@ snapshots: dependencies: ansi-regex: 5.0.1 - supports-color@10.2.2: {} - svgo@4.0.1: dependencies: commander: 11.1.0 @@ -4951,6 +4460,8 @@ snapshots: tinyrainbow@3.1.0: {} + toidentifier@1.0.1: {} + trim-lines@3.0.1: {} trough@2.2.0: {} @@ -4972,11 +4483,7 @@ snapshots: uncrypto@0.1.3: {} - undici@7.24.8: {} - - unenv@2.0.0-rc.24: - dependencies: - pathe: 2.0.3 + undici-types@8.3.0: {} unicode-segmenter@0.14.5: {} @@ -5068,7 +4575,7 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - vite@7.3.3(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4): + vite@7.3.3(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4): dependencies: esbuild: 0.27.7 fdir: 6.5.0(picomatch@4.0.4) @@ -5077,12 +4584,13 @@ snapshots: rollup: 4.60.3 tinyglobby: 0.2.16 optionalDependencies: + '@types/node': 26.1.2 fsevents: 2.3.3 jiti: 2.7.0 lightningcss: 1.32.0 yaml: 2.8.4 - vite@8.0.11(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4): + vite@8.0.11(@types/node@26.1.2)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4): dependencies: lightningcss: 1.32.0 picomatch: 4.0.4 @@ -5090,19 +4598,20 @@ snapshots: rolldown: 1.0.0-rc.18 tinyglobby: 0.2.16 optionalDependencies: + '@types/node': 26.1.2 esbuild: 0.27.7 fsevents: 2.3.3 jiti: 2.7.0 yaml: 2.8.4 - vitefu@1.1.3(vite@7.3.3(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)): + vitefu@1.1.3(vite@7.3.3(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4)): optionalDependencies: - vite: 7.3.3(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4) + vite: 7.3.3(@types/node@26.1.2)(jiti@2.7.0)(lightningcss@1.32.0)(yaml@2.8.4) - vitest@4.1.5(vite@8.0.11(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4)): + vitest@4.1.5(@types/node@26.1.2)(vite@8.0.11(@types/node@26.1.2)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4)): dependencies: '@vitest/expect': 4.1.5 - '@vitest/mocker': 4.1.5(vite@8.0.11(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4)) + '@vitest/mocker': 4.1.5(vite@8.0.11(@types/node@26.1.2)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4)) '@vitest/pretty-format': 4.1.5 '@vitest/runner': 4.1.5 '@vitest/snapshot': 4.1.5 @@ -5119,8 +4628,10 @@ snapshots: tinyexec: 1.1.2 tinyglobby: 0.2.16 tinyrainbow: 3.1.0 - vite: 8.0.11(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4) + vite: 8.0.11(@types/node@26.1.2)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.8.4) why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 26.1.2 transitivePeerDependencies: - msw @@ -5230,39 +4741,12 @@ snapshots: siginfo: 2.0.0 stackback: 0.0.2 - workerd@1.20260507.1: - optionalDependencies: - '@cloudflare/workerd-darwin-64': 1.20260507.1 - '@cloudflare/workerd-darwin-arm64': 1.20260507.1 - '@cloudflare/workerd-linux-64': 1.20260507.1 - '@cloudflare/workerd-linux-arm64': 1.20260507.1 - '@cloudflare/workerd-windows-64': 1.20260507.1 - - wrangler@4.90.0(@cloudflare/workers-types@4.20260509.1): - dependencies: - '@cloudflare/kv-asset-handler': 0.5.0 - '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260507.1) - blake3-wasm: 2.1.5 - esbuild: 0.27.3 - miniflare: 4.20260507.1 - path-to-regexp: 6.3.0 - unenv: 2.0.0-rc.24 - workerd: 1.20260507.1 - optionalDependencies: - '@cloudflare/workers-types': 4.20260509.1 - fsevents: 2.3.3 - transitivePeerDependencies: - - bufferutil - - utf-8-validate - wrap-ansi@7.0.0: dependencies: ansi-styles: 4.3.0 string-width: 4.2.3 strip-ansi: 6.0.1 - ws@8.18.0: {} - xxhash-wasm@1.1.0: {} y18n@5.0.8: {} @@ -5301,19 +4785,6 @@ snapshots: yocto-queue@1.2.2: {} - youch-core@0.3.3: - dependencies: - '@poppinss/exception': 1.2.3 - error-stack-parser-es: 1.0.5 - - youch@4.1.0-beta.10: - dependencies: - '@poppinss/colors': 4.1.6 - '@poppinss/dumper': 0.6.5 - '@speed-highlight/core': 1.2.15 - cookie: 1.1.1 - youch-core: 0.3.3 - zod@4.4.3: {} zwitch@2.0.4: {} diff --git a/railway.json b/railway.json new file mode 100644 index 0000000..a90a684 --- /dev/null +++ b/railway.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://railway.app/railway.schema.json", + "build": { "builder": "DOCKERFILE", "dockerfilePath": "Dockerfile" }, + "deploy": { + "healthcheckPath": "/api/v0/healthz", + "healthcheckTimeout": 30, + "restartPolicyType": "ON_FAILURE" + } +}