diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..02f536e --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,37 @@ +name: CI + +on: + push: + branches: [main, develop] + pull_request: + branches: [main, develop] + +jobs: + ci: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '24' + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 8 + + - name: Install global packages + run: pnpm install -g tsup + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Lint + run: pnpm nx:lint + + - name: Build + run: pnpm nx:build diff --git a/.gitignore b/.gitignore index 8451a74..dfbd25a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ node_modules .env .dev.vars -.vscode .nx/installation .nx/cache .nx/workspace-data @@ -11,6 +10,4 @@ node_modules .cursor/rules/nx-rules.mdc .github/instructions/nx.instructions.md -wrangler.jsonc - !.env.example \ No newline at end of file diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index 0def6e4..0000000 --- a/.prettierrc +++ /dev/null @@ -1,23 +0,0 @@ -{ - "arrowParens": "always", - "bracketSpacing": true, - "endOfLine": "lf", - "htmlWhitespaceSensitivity": "css", - "insertPragma": false, - "singleAttributePerLine": false, - "bracketSameLine": false, - "jsxBracketSameLine": false, - "jsxSingleQuote": true, - "printWidth": 100, - "proseWrap": "preserve", - "quoteProps": "as-needed", - "requirePragma": false, - "semi": true, - "singleQuote": true, - "tabWidth": 2, - "trailingComma": "es5", - "useTabs": false, - "embeddedLanguageFormatting": "auto", - "vueIndentScriptAndStyle": false, - "experimentalTernaries": false -} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..e0e684e --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,25 @@ +{ + "editor.defaultFormatter": "biomejs.biome", + "editor.formatOnSave": true, + "editor.formatOnPaste": true, + "editor.formatOnType": false, + "files.readonlyInclude": { + "**/routeTree.gen.ts": true + }, + "files.watcherExclude": { + "**/routeTree.gen.ts": true + }, + "search.exclude": { + "**/routeTree.gen.ts": true + }, + "[typescript]": { + "editor.defaultFormatter": "biomejs.biome" + }, + "editor.codeActionsOnSave": { + "source.organizeImports.biome": "explicit", + "source.fixAll.biome": "explicit" + }, + "[typescriptreact]": { + "editor.defaultFormatter": "biomejs.biome" + } +} diff --git a/apps/api/.gitignore b/apps/api/.gitignore index 1d0e12b..9614229 100644 --- a/apps/api/.gitignore +++ b/apps/api/.gitignore @@ -169,5 +169,4 @@ dist # wrangler project .dev.vars -.wrangler/ -worker-configuration.d.ts \ No newline at end of file +.wrangler/ \ No newline at end of file diff --git a/apps/api/package.json b/apps/api/package.json index 50257cb..b7444aa 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -1,57 +1,60 @@ { - "name": "@coderscreen/api", - "version": "0.0.0", - "private": true, - "scripts": { - "build": "tsc", - "dev": "wrangler dev", - "start": "wrangler dev", - "test": "vitest", - "cf-deploy": "wrangler deploy", - "cf-types": "wrangler types", - "auth:generate": "pnpm dlx @better-auth/cli@latest generate --config ./better-auth.config.ts --output ../../packages/db/src/user.db.ts", - "sandbox:build": "cd ../.. && pnpm sandbox:build", - "sandbox:push": "wrangler containers push sandbox-image:production", - "stripe:listen": "stripe listen --forward-to localhost:8000/webhook/stripe" - }, - "devDependencies": { - "@cloudflare/vitest-pool-workers": "^0.8.36", - "@types/lodash.throttle": "^4.1.9", - "@types/node": "^24.0.3", - "partykit": "0.0.115", - "typescript": "^5.8.3", - "vitest": "~3.0.9", - "wrangler": "^4.22.0" - }, - "dependencies": { - "@cloudflare/containers": "^0.0.13", - "@cloudflare/sandbox": "workspace:^", - "@coderscreen/common": "workspace:^", - "@coderscreen/db": "workspace:^", - "@daytonaio/sdk": "0.21.1", - "@hono/zod-validator": "^0.7.0", - "@tldraw/sync-core": "^3.14.0", - "@tldraw/tlschema": "^3.14.0", - "better-auth": "^1.2.10", - "drizzle-orm": "^0.44.2", - "hono": "^4.7.11", - "hono-openapi": "^0.4.8", - "hono-party": "^0.0.13", - "lodash.throttle": "^4.1.1", - "loops": "^5.0.1", - "openai": "^5.9.0", - "partyserver": "^0.0.72", - "partysocket": "1.1.4", - "postgres": "^3.4.7", - "stripe": "^18.3.0", - "y-partykit": "^0.0.33", - "y-partyserver": "^0.0.45", - "y-protocols": "^1.0.6", - "yjs": "^13.6.27", - "zod": "^3.25.67", - "zod-openapi": "^4.2.4" - }, - "exports": { - ".": "./dist/src/index.d.ts" - } + "name": "@coderscreen/api", + "version": "0.0.0", + "private": true, + "scripts": { + "lint": "biome check src", + "lint:fix": "biome check src --write", + "format": "biome format src --write", + "build": "tsc", + "dev": "wrangler dev", + "start": "wrangler dev", + "test": "vitest", + "cf-deploy": "wrangler deploy", + "cf-types": "wrangler types", + "auth:generate": "pnpm dlx @better-auth/cli@latest generate --config ./better-auth.config.ts --output ../../packages/db/src/user.db.ts", + "sandbox:build": "cd ../.. && pnpm sandbox:build", + "sandbox:push": "wrangler containers push sandbox-image:production", + "stripe:listen": "stripe listen --forward-to localhost:8000/webhook/stripe" + }, + "devDependencies": { + "@cloudflare/vitest-pool-workers": "^0.8.36", + "@types/lodash.throttle": "^4.1.9", + "@types/node": "^24.0.3", + "partykit": "0.0.115", + "typescript": "^5.8.3", + "vitest": "~3.0.9", + "wrangler": "^4.22.0" + }, + "dependencies": { + "@cloudflare/containers": "^0.0.13", + "@cloudflare/sandbox": "workspace:^", + "@coderscreen/common": "workspace:^", + "@coderscreen/db": "workspace:^", + "@daytonaio/sdk": "0.21.1", + "@hono/zod-validator": "^0.7.0", + "@tldraw/sync-core": "^3.14.0", + "@tldraw/tlschema": "^3.14.0", + "better-auth": "^1.2.10", + "drizzle-orm": "^0.44.2", + "hono": "^4.7.11", + "hono-openapi": "^0.4.8", + "hono-party": "^0.0.13", + "lodash.throttle": "^4.1.1", + "loops": "^5.0.1", + "openai": "^5.9.0", + "partyserver": "^0.0.72", + "partysocket": "1.1.4", + "postgres": "^3.4.7", + "stripe": "^18.3.0", + "y-partykit": "^0.0.33", + "y-partyserver": "^0.0.45", + "y-protocols": "^1.0.6", + "yjs": "^13.6.27", + "zod": "^3.25.67", + "zod-openapi": "^4.2.4" + }, + "exports": { + ".": "./dist/src/index.d.ts" + } } diff --git a/apps/api/project.json b/apps/api/project.json new file mode 100644 index 0000000..0047a34 --- /dev/null +++ b/apps/api/project.json @@ -0,0 +1,17 @@ +{ + "targets": { + "build": { + "dependsOn": [ + { + "projects": ["sandbox"], + "target": "build", + "params": "ignore" + }, + "^build" + ] + }, + "test": { + "dependsOn": ["build"] + } + } +} diff --git a/apps/api/src/containers/CustomSandbox.ts b/apps/api/src/containers/CustomSandbox.ts index 4a85b26..bb3d956 100644 --- a/apps/api/src/containers/CustomSandbox.ts +++ b/apps/api/src/containers/CustomSandbox.ts @@ -1,19 +1,19 @@ +import { SpawnOptions } from 'node:child_process'; import { Sandbox } from '@cloudflare/sandbox'; -import { AppContext } from '@/index'; import { RoomEntity } from '@coderscreen/db/room.db'; -import { TypescriptRunner } from '@/containers/runners/ts.runner'; import { CodeRunner } from '@/containers/runners/base'; -import { JavaScriptRunner } from '@/containers/runners/js.runner'; -import { PythonRunner } from '@/containers/runners/python.runner'; import { BashRunner } from '@/containers/runners/bash.runner'; import { CRunner } from '@/containers/runners/c.runner'; import { CppRunner } from '@/containers/runners/cpp.runner'; import { GoRunner } from '@/containers/runners/go.runner'; -import { RustRunner } from '@/containers/runners/rust.runner'; +import { JavaRunner } from '@/containers/runners/java.runner'; +import { JavaScriptRunner } from '@/containers/runners/js.runner'; import { PhpRunner } from '@/containers/runners/php.runner'; +import { PythonRunner } from '@/containers/runners/python.runner'; import { RubyRunner } from '@/containers/runners/ruby.runner'; -import { JavaRunner } from '@/containers/runners/java.runner'; -import { SpawnOptions } from 'child_process'; +import { RustRunner } from '@/containers/runners/rust.runner'; +import { TypescriptRunner } from '@/containers/runners/ts.runner'; +import { AppContext } from '@/index'; import { ExecuteResponse } from '@/lib/sandbox'; export class CustomSandbox extends Sandbox { @@ -26,7 +26,7 @@ export class CustomSandbox extends Sandbox { args: string[], options?: { stream?: boolean; childOptions?: SpawnOptions } ): Promise { - let start = Date.now(); + const start = Date.now(); const result = await super.exec(command, args, { ...options, childOptions: { @@ -34,7 +34,7 @@ export class CustomSandbox extends Sandbox { timeout: options?.childOptions?.timeout || this.FALLBACK_TIMEOUT_MS, }, }); - let end = Date.now(); + const end = Date.now(); const elapsedTime = end - start; if (!result) { diff --git a/apps/api/src/containers/config/tsconfig.json b/apps/api/src/containers/config/tsconfig.json index 9ad0e76..a4fff26 100644 --- a/apps/api/src/containers/config/tsconfig.json +++ b/apps/api/src/containers/config/tsconfig.json @@ -1,14 +1,14 @@ { - "compilerOptions": { - "target": "es2021", - "module": "commonjs", - "lib": ["es2021", "dom"], - "types": ["node"], - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "noEmit": true - }, - "include": ["**/*.ts"] + "compilerOptions": { + "target": "es2021", + "module": "commonjs", + "lib": ["es2021", "dom"], + "types": ["node"], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "include": ["**/*.ts"] } diff --git a/apps/api/src/containers/runners/base.ts b/apps/api/src/containers/runners/base.ts index cfc7492..b0b98af 100644 --- a/apps/api/src/containers/runners/base.ts +++ b/apps/api/src/containers/runners/base.ts @@ -2,121 +2,128 @@ import { CustomSandbox } from '@/containers/CustomSandbox'; import { ExecuteResponse } from '@/lib/sandbox'; export class CodeRunner { - static emptyResponse: ExecuteResponse = { - id: 'empty', - success: false, - timestamp: new Date().toISOString(), - stdout: '', - stderr: 'No output from execution', - exitCode: 0, - elapsedTime: 0, - command: '', - args: [], - }; - - static timeoutResponse: ExecuteResponse = { - id: 'timed-out', - success: false, - timestamp: new Date().toISOString(), - stdout: '', - stderr: 'Execution timed out. This may be due to an infinite loop or long-running code.', - exitCode: -1, - elapsedTime: 0, - command: '', - args: [], - }; - - constructor(protected sandbox: CustomSandbox, protected code: string) {} - - async setup() { - return; - } - - /** - * Abstract method that runners must implement - * This should contain the actual execution logic - */ - protected async executeInternal(): Promise { - return CodeRunner.emptyResponse; - } - - /** - * Public execute method that automatically applies timeout protection - */ - async execute(): Promise { - return this.executeInternal(); - // const start = Date.now(); - - // try { - // // Create a timeout promise - // const timeoutPromise = new Promise((_, reject) => { - // setTimeout(() => { - // reject(new Error(`Execution timed out after ${this.DEFAULT_TIMEOUT_MS}ms`)); - // }, this.DEFAULT_TIMEOUT_MS); - // }); - - // // Create the actual execution promise - // const executionPromise = this.executeInternal(); - - // // Race between execution and timeout - // const result = await Promise.race([executionPromise, timeoutPromise]); - // const duration = Date.now() - start; - - // // Check if the result indicates a timeout (from sandbox level) - // if (result && this.isTimeoutResponse(result)) { - // console.warn(`Execution timed out after ${duration}ms`); - // return { - // ...this.timeoutResponse, - // stderr: `Execution timed out after ${duration}ms. This may be due to an infinite loop or long-running code.`, - // command: result.command, - // args: result.args, - // }; - // } - - // return result; - // } catch (error) { - // const duration = Date.now() - start; - - // // Handle timeout errors - // if (error instanceof Error && error.message.includes('timed out')) { - // console.warn(`Execution timed out after ${duration}ms`); - // return { - // ...this.timeoutResponse, - // stderr: `Execution timed out after ${duration}ms. This may be due to an infinite loop or long-running code.`, - // command: '', - // args: [], - // }; - // } - - // // Handle other errors - // return { - // ...this.emptyResponse, - // stderr: error instanceof Error ? error.message : 'Unknown execution error', - // exitCode: -2, // Special exit code for other errors - // }; - // } - } - - async cleanup() { - return; - } - - /** - * Helper method to check if a response indicates a timeout - */ - protected isTimeoutResponse(response: ExecuteResponse): boolean { - return response.id === 'timed-out'; - } - - /** - * Helper method to create a timeout response with specific command info - */ - protected createTimeoutResponse(command: string, args: string[], duration: number): ExecuteResponse { - return { - ...CodeRunner.timeoutResponse, - stderr: `Execution timed out after ${duration}ms. This may be due to an infinite loop or long-running code.`, - command, - args, - }; - } + static emptyResponse: ExecuteResponse = { + id: 'empty', + success: false, + timestamp: new Date().toISOString(), + stdout: '', + stderr: 'No output from execution', + exitCode: 0, + elapsedTime: 0, + command: '', + args: [], + }; + + static timeoutResponse: ExecuteResponse = { + id: 'timed-out', + success: false, + timestamp: new Date().toISOString(), + stdout: '', + stderr: 'Execution timed out. This may be due to an infinite loop or long-running code.', + exitCode: -1, + elapsedTime: 0, + command: '', + args: [], + }; + + constructor( + protected sandbox: CustomSandbox, + protected code: string + ) {} + + async setup() { + return; + } + + /** + * Abstract method that runners must implement + * This should contain the actual execution logic + */ + protected async executeInternal(): Promise { + return CodeRunner.emptyResponse; + } + + /** + * Public execute method that automatically applies timeout protection + */ + async execute(): Promise { + return this.executeInternal(); + // const start = Date.now(); + + // try { + // // Create a timeout promise + // const timeoutPromise = new Promise((_, reject) => { + // setTimeout(() => { + // reject(new Error(`Execution timed out after ${this.DEFAULT_TIMEOUT_MS}ms`)); + // }, this.DEFAULT_TIMEOUT_MS); + // }); + + // // Create the actual execution promise + // const executionPromise = this.executeInternal(); + + // // Race between execution and timeout + // const result = await Promise.race([executionPromise, timeoutPromise]); + // const duration = Date.now() - start; + + // // Check if the result indicates a timeout (from sandbox level) + // if (result && this.isTimeoutResponse(result)) { + // console.warn(`Execution timed out after ${duration}ms`); + // return { + // ...this.timeoutResponse, + // stderr: `Execution timed out after ${duration}ms. This may be due to an infinite loop or long-running code.`, + // command: result.command, + // args: result.args, + // }; + // } + + // return result; + // } catch (error) { + // const duration = Date.now() - start; + + // // Handle timeout errors + // if (error instanceof Error && error.message.includes('timed out')) { + // console.warn(`Execution timed out after ${duration}ms`); + // return { + // ...this.timeoutResponse, + // stderr: `Execution timed out after ${duration}ms. This may be due to an infinite loop or long-running code.`, + // command: '', + // args: [], + // }; + // } + + // // Handle other errors + // return { + // ...this.emptyResponse, + // stderr: error instanceof Error ? error.message : 'Unknown execution error', + // exitCode: -2, // Special exit code for other errors + // }; + // } + } + + async cleanup() { + return; + } + + /** + * Helper method to check if a response indicates a timeout + */ + protected isTimeoutResponse(response: ExecuteResponse): boolean { + return response.id === 'timed-out'; + } + + /** + * Helper method to create a timeout response with specific command info + */ + protected createTimeoutResponse( + command: string, + args: string[], + duration: number + ): ExecuteResponse { + return { + ...CodeRunner.timeoutResponse, + stderr: `Execution timed out after ${duration}ms. This may be due to an infinite loop or long-running code.`, + command, + args, + }; + } } diff --git a/apps/api/src/containers/runners/bash.runner.ts b/apps/api/src/containers/runners/bash.runner.ts index bbaaa2a..176fbd8 100644 --- a/apps/api/src/containers/runners/bash.runner.ts +++ b/apps/api/src/containers/runners/bash.runner.ts @@ -1,23 +1,18 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class BashRunner extends CodeRunner { - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } + async setup() { + return; + } - async setup() { - return; - } + async executeInternal(): Promise { + const result = await this.sandbox.exec(this.code, []); - async executeInternal(): Promise { - const result = await this.sandbox.exec(this.code, []); + return result; + } - return result; - } - - async cleanup() { - return; - } + async cleanup() { + return; + } } diff --git a/apps/api/src/containers/runners/c.runner.ts b/apps/api/src/containers/runners/c.runner.ts index 3c4b553..ddab06a 100644 --- a/apps/api/src/containers/runners/c.runner.ts +++ b/apps/api/src/containers/runners/c.runner.ts @@ -1,46 +1,41 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class CRunner extends CodeRunner { - private sourceFilePath = 'tmp.c'; - private executablePath = 'tmp'; - - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } - - async setup() { - // Create a temp C source file - await this.sandbox.writeFile(this.sourceFilePath, this.code); - return; - } - - async executeInternal(): Promise { - // First compile the C code - const compileResult = await this.sandbox.exec('gcc', [ - '-o', - this.executablePath, - this.sourceFilePath, - '-Wall', // Enable all warnings - '-Wextra', // Enable extra warnings - '-std=c99', // Use C99 standard - ]); - - // If compilation failed, return the compilation error - if (compileResult && !compileResult.success) { - return compileResult; - } - - // If compilation succeeded, run the executable - const runResult = await this.sandbox.exec(`./${this.executablePath}`, []); - - return runResult; - } - - async cleanup() { - // Clean up both source file and executable - await this.sandbox.deleteFile(this.sourceFilePath); - await this.sandbox.deleteFile(this.executablePath); - } + private sourceFilePath = 'tmp.c'; + private executablePath = 'tmp'; + + async setup() { + // Create a temp C source file + await this.sandbox.writeFile(this.sourceFilePath, this.code); + return; + } + + async executeInternal(): Promise { + // First compile the C code + const compileResult = await this.sandbox.exec('gcc', [ + '-o', + this.executablePath, + this.sourceFilePath, + '-Wall', // Enable all warnings + '-Wextra', // Enable extra warnings + '-std=c99', // Use C99 standard + ]); + + // If compilation failed, return the compilation error + if (compileResult && !compileResult.success) { + return compileResult; + } + + // If compilation succeeded, run the executable + const runResult = await this.sandbox.exec(`./${this.executablePath}`, []); + + return runResult; + } + + async cleanup() { + // Clean up both source file and executable + await this.sandbox.deleteFile(this.sourceFilePath); + await this.sandbox.deleteFile(this.executablePath); + } } diff --git a/apps/api/src/containers/runners/cpp.runner.ts b/apps/api/src/containers/runners/cpp.runner.ts index 8ba8b92..0c87a1c 100644 --- a/apps/api/src/containers/runners/cpp.runner.ts +++ b/apps/api/src/containers/runners/cpp.runner.ts @@ -1,46 +1,41 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class CppRunner extends CodeRunner { - private sourceFilePath = 'tmp.cpp'; - private executablePath = 'tmp'; - - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } - - async setup() { - // Create a temp C++ source file - await this.sandbox.writeFile(this.sourceFilePath, this.code); - return; - } - - async executeInternal(): Promise { - // First compile the C++ code - const compileResult = await this.sandbox.exec('g++', [ - '-o', - this.executablePath, - this.sourceFilePath, - '-Wall', // Enable all warnings - '-Wextra', // Enable extra warnings - '-std=c++17', // Use C++17 standard - ]); - - // If compilation failed, return the compilation error - if (!compileResult.success) { - return compileResult; - } - - // If compilation succeeded, run the executable - const runResult = await this.sandbox.exec(`./${this.executablePath}`, []); - - return runResult; - } - - async cleanup() { - // Clean up both source file and executable - await this.sandbox.deleteFile(this.sourceFilePath); - await this.sandbox.deleteFile(this.executablePath); - } + private sourceFilePath = 'tmp.cpp'; + private executablePath = 'tmp'; + + async setup() { + // Create a temp C++ source file + await this.sandbox.writeFile(this.sourceFilePath, this.code); + return; + } + + async executeInternal(): Promise { + // First compile the C++ code + const compileResult = await this.sandbox.exec('g++', [ + '-o', + this.executablePath, + this.sourceFilePath, + '-Wall', // Enable all warnings + '-Wextra', // Enable extra warnings + '-std=c++17', // Use C++17 standard + ]); + + // If compilation failed, return the compilation error + if (!compileResult.success) { + return compileResult; + } + + // If compilation succeeded, run the executable + const runResult = await this.sandbox.exec(`./${this.executablePath}`, []); + + return runResult; + } + + async cleanup() { + // Clean up both source file and executable + await this.sandbox.deleteFile(this.sourceFilePath); + await this.sandbox.deleteFile(this.executablePath); + } } diff --git a/apps/api/src/containers/runners/go.runner.ts b/apps/api/src/containers/runners/go.runner.ts index 152a846..de36e9d 100644 --- a/apps/api/src/containers/runners/go.runner.ts +++ b/apps/api/src/containers/runners/go.runner.ts @@ -1,28 +1,23 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class GoRunner extends CodeRunner { - private sourceFilePath = 'tmp.go'; + private sourceFilePath = 'tmp.go'; - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } + async setup() { + // Create a temp Go source file + await this.sandbox.writeFile(this.sourceFilePath, this.code); + return; + } - async setup() { - // Create a temp Go source file - await this.sandbox.writeFile(this.sourceFilePath, this.code); - return; - } + async executeInternal(): Promise { + const result = await this.sandbox.exec('go', ['run', this.sourceFilePath]); - async executeInternal(): Promise { - const result = await this.sandbox.exec('go', ['run', this.sourceFilePath]); + return result; + } - return result; - } - - async cleanup() { - // Clean up the source file - await this.sandbox.deleteFile(this.sourceFilePath); - } + async cleanup() { + // Clean up the source file + await this.sandbox.deleteFile(this.sourceFilePath); + } } diff --git a/apps/api/src/containers/runners/java.runner.ts b/apps/api/src/containers/runners/java.runner.ts index 9f784df..733e028 100644 --- a/apps/api/src/containers/runners/java.runner.ts +++ b/apps/api/src/containers/runners/java.runner.ts @@ -1,39 +1,34 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class JavaRunner extends CodeRunner { - private sourceFilePath = 'Solution.java'; - private classFilePath = 'Solution.class'; - - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } - - async setup() { - // Create a temp Java source file - await this.sandbox.writeFile(this.sourceFilePath, this.code); - return; - } - - async executeInternal(): Promise { - // First compile the Java code - const compileResult = await this.sandbox.exec('javac', [this.sourceFilePath]); - - // If compilation failed, return the compilation error - if (!compileResult.success) { - return compileResult; - } - - // If compilation succeeded, run the Java class - const runResult = await this.sandbox.exec('java', ['Solution']); - - return runResult; - } - - async cleanup() { - // Clean up both source file and compiled class file - await this.sandbox.deleteFile(this.sourceFilePath); - await this.sandbox.deleteFile(this.classFilePath); - } + private sourceFilePath = 'Solution.java'; + private classFilePath = 'Solution.class'; + + async setup() { + // Create a temp Java source file + await this.sandbox.writeFile(this.sourceFilePath, this.code); + return; + } + + async executeInternal(): Promise { + // First compile the Java code + const compileResult = await this.sandbox.exec('javac', [this.sourceFilePath]); + + // If compilation failed, return the compilation error + if (!compileResult.success) { + return compileResult; + } + + // If compilation succeeded, run the Java class + const runResult = await this.sandbox.exec('java', ['Solution']); + + return runResult; + } + + async cleanup() { + // Clean up both source file and compiled class file + await this.sandbox.deleteFile(this.sourceFilePath); + await this.sandbox.deleteFile(this.classFilePath); + } } diff --git a/apps/api/src/containers/runners/js.runner.ts b/apps/api/src/containers/runners/js.runner.ts index 2a0f3e2..b51c8d4 100644 --- a/apps/api/src/containers/runners/js.runner.ts +++ b/apps/api/src/containers/runners/js.runner.ts @@ -1,27 +1,22 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class JavaScriptRunner extends CodeRunner { - private tmpFilePath = 'tmp.js'; + private tmpFilePath = 'tmp.js'; - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } + async setup() { + // Create a temp file + await this.sandbox.writeFile(this.tmpFilePath, this.code); + return; + } - async setup() { - // Create a temp file - await this.sandbox.writeFile(this.tmpFilePath, this.code); - return; - } + async executeInternal(): Promise { + const result = await this.sandbox.exec('node', [this.tmpFilePath]); - async executeInternal(): Promise { - const result = await this.sandbox.exec('node', [this.tmpFilePath]); + return result; + } - return result; - } - - async cleanup() { - await this.sandbox.deleteFile(this.tmpFilePath); - } + async cleanup() { + await this.sandbox.deleteFile(this.tmpFilePath); + } } diff --git a/apps/api/src/containers/runners/php.runner.ts b/apps/api/src/containers/runners/php.runner.ts index a1d9647..c1f32f5 100644 --- a/apps/api/src/containers/runners/php.runner.ts +++ b/apps/api/src/containers/runners/php.runner.ts @@ -1,29 +1,24 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class PhpRunner extends CodeRunner { - private sourceFilePath = 'tmp.php'; + private sourceFilePath = 'tmp.php'; - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } + async setup() { + // Create a temp PHP source file + await this.sandbox.writeFile(this.sourceFilePath, this.code); + return; + } - async setup() { - // Create a temp PHP source file - await this.sandbox.writeFile(this.sourceFilePath, this.code); - return; - } + async executeInternal(): Promise { + // Run the PHP code using the php interpreter + const result = await this.sandbox.exec('php', [this.sourceFilePath]); - async executeInternal(): Promise { - // Run the PHP code using the php interpreter - const result = await this.sandbox.exec('php', [this.sourceFilePath]); + return result; + } - return result; - } - - async cleanup() { - // Clean up the source file - await this.sandbox.deleteFile(this.sourceFilePath); - } + async cleanup() { + // Clean up the source file + await this.sandbox.deleteFile(this.sourceFilePath); + } } diff --git a/apps/api/src/containers/runners/python.runner.ts b/apps/api/src/containers/runners/python.runner.ts index 5b243e2..f2cfcaa 100644 --- a/apps/api/src/containers/runners/python.runner.ts +++ b/apps/api/src/containers/runners/python.runner.ts @@ -1,27 +1,22 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class PythonRunner extends CodeRunner { - private tmpFilePath = 'tmp.py'; + private tmpFilePath = 'tmp.py'; - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } + async setup() { + // Create a temp file + await this.sandbox.writeFile(this.tmpFilePath, this.code); + return; + } - async setup() { - // Create a temp file - await this.sandbox.writeFile(this.tmpFilePath, this.code); - return; - } + async executeInternal(): Promise { + const result = await this.sandbox.exec('python', [this.tmpFilePath]); - async executeInternal(): Promise { - const result = await this.sandbox.exec('python', [this.tmpFilePath]); + return result; + } - return result; - } - - async cleanup() { - await this.sandbox.deleteFile(this.tmpFilePath); - } + async cleanup() { + await this.sandbox.deleteFile(this.tmpFilePath); + } } diff --git a/apps/api/src/containers/runners/ruby.runner.ts b/apps/api/src/containers/runners/ruby.runner.ts index 30ff81a..cf55499 100644 --- a/apps/api/src/containers/runners/ruby.runner.ts +++ b/apps/api/src/containers/runners/ruby.runner.ts @@ -1,29 +1,24 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class RubyRunner extends CodeRunner { - private sourceFilePath = 'tmp.rb'; + private sourceFilePath = 'tmp.rb'; - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } + async setup() { + // Create a temp Ruby source file + await this.sandbox.writeFile(this.sourceFilePath, this.code); + return; + } - async setup() { - // Create a temp Ruby source file - await this.sandbox.writeFile(this.sourceFilePath, this.code); - return; - } + async executeInternal(): Promise { + // Run the Ruby code using the ruby interpreter + const result = await this.sandbox.exec('ruby', [this.sourceFilePath]); - async executeInternal(): Promise { - // Run the Ruby code using the ruby interpreter - const result = await this.sandbox.exec('ruby', [this.sourceFilePath]); + return result; + } - return result; - } - - async cleanup() { - // Clean up the source file - await this.sandbox.deleteFile(this.sourceFilePath); - } + async cleanup() { + // Clean up the source file + await this.sandbox.deleteFile(this.sourceFilePath); + } } diff --git a/apps/api/src/containers/runners/rust.runner.ts b/apps/api/src/containers/runners/rust.runner.ts index 3c9f4f9..4488933 100644 --- a/apps/api/src/containers/runners/rust.runner.ts +++ b/apps/api/src/containers/runners/rust.runner.ts @@ -1,39 +1,38 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class RustRunner extends CodeRunner { - private sourceFilePath = 'tmp.rs'; - private executablePath = 'tmp'; - - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } - - async setup() { - // Create a temp Rust source file - await this.sandbox.writeFile(this.sourceFilePath, this.code); - return; - } - - async executeInternal(): Promise { - // First compile the Rust code - const compileResult = await this.sandbox.exec('rustc', ['-o', this.executablePath, this.sourceFilePath]); - - // If compilation failed, return the compilation error - if (!compileResult.success) { - return compileResult; - } - - // If compilation succeeded, run the executable - const runResult = await this.sandbox.exec(`./${this.executablePath}`, []); - - return runResult; - } - - async cleanup() { - // Clean up both source file and executable - await this.sandbox.deleteFile(this.sourceFilePath); - await this.sandbox.deleteFile(this.executablePath); - } + private sourceFilePath = 'tmp.rs'; + private executablePath = 'tmp'; + + async setup() { + // Create a temp Rust source file + await this.sandbox.writeFile(this.sourceFilePath, this.code); + return; + } + + async executeInternal(): Promise { + // First compile the Rust code + const compileResult = await this.sandbox.exec('rustc', [ + '-o', + this.executablePath, + this.sourceFilePath, + ]); + + // If compilation failed, return the compilation error + if (!compileResult.success) { + return compileResult; + } + + // If compilation succeeded, run the executable + const runResult = await this.sandbox.exec(`./${this.executablePath}`, []); + + return runResult; + } + + async cleanup() { + // Clean up both source file and executable + await this.sandbox.deleteFile(this.sourceFilePath); + await this.sandbox.deleteFile(this.executablePath); + } } diff --git a/apps/api/src/containers/runners/ts.runner.ts b/apps/api/src/containers/runners/ts.runner.ts index 34c4c24..2419fc5 100644 --- a/apps/api/src/containers/runners/ts.runner.ts +++ b/apps/api/src/containers/runners/ts.runner.ts @@ -1,27 +1,22 @@ -import { CustomSandbox } from '@/containers/CustomSandbox'; import { CodeRunner } from '@/containers/runners/base'; import { ExecuteResponse } from '@/lib/sandbox'; export class TypescriptRunner extends CodeRunner { - private tmpFilePath = 'tmp.ts'; + private tmpFilePath = 'tmp.ts'; - constructor(sandbox: CustomSandbox, code: string) { - super(sandbox, code); - } + async setup() { + // Create a temp file + await this.sandbox.writeFile(this.tmpFilePath, this.code); + return; + } - async setup() { - // Create a temp file - await this.sandbox.writeFile(this.tmpFilePath, this.code); - return; - } + async executeInternal(): Promise { + const result = await this.sandbox.exec('ts-node', [this.tmpFilePath]); - async executeInternal(): Promise { - const result = await this.sandbox.exec('ts-node', [this.tmpFilePath]); + return result; + } - return result; - } - - async cleanup() { - await this.sandbox.deleteFile(this.tmpFilePath); - } + async cleanup() { + await this.sandbox.deleteFile(this.tmpFilePath); + } } diff --git a/apps/api/src/db/client.ts b/apps/api/src/db/client.ts index e844785..e0952e8 100644 --- a/apps/api/src/db/client.ts +++ b/apps/api/src/db/client.ts @@ -1,7 +1,7 @@ -import postgres from 'postgres'; import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js'; -import { AppContext } from '@/index'; import { Context } from 'hono'; +import postgres from 'postgres'; +import { AppContext } from '@/index'; const DATABASE_URL = process.env.DATABASE_URL; diff --git a/apps/api/src/durable-objects/whiteboard.do.ts b/apps/api/src/durable-objects/whiteboard.do.ts index ef5ef16..2f474a1 100644 --- a/apps/api/src/durable-objects/whiteboard.do.ts +++ b/apps/api/src/durable-objects/whiteboard.do.ts @@ -1,90 +1,95 @@ import { Id } from '@coderscreen/common/id'; import { RoomSnapshot, TLSocketRoom } from '@tldraw/sync-core'; -import { TLRecord, createTLSchema, defaultShapeSchemas } from '@tldraw/tlschema'; +import { createTLSchema, defaultShapeSchemas, TLRecord } from '@tldraw/tlschema'; import { Context, Hono } from 'hono'; import throttle from 'lodash.throttle'; const schema = createTLSchema({ - shapes: { ...defaultShapeSchemas }, + shapes: { ...defaultShapeSchemas }, }); export class WhiteboardDurableObject { - static PERSIST_INTERVAL = 10_000; - - private r2: R2Bucket; - private roomId: Id<'room'> | null = null; - private roomPromise: Promise> | null = null; - private app: Hono<{ Bindings: Env }>; - - constructor(private readonly ctx: DurableObjectState, env: Env) { - this.r2 = env.WHITEBOARD_ASSETS_BUCKET; - - ctx.blockConcurrencyWhile(async () => { - this.roomId = ((await this.ctx.storage.get('roomId')) ?? null) as Id<'room'> | null; - }); - - this.app = new Hono<{ Bindings: Env }>(); - - this.app.get('/rooms/:roomId/public/whiteboard/connect', async (c) => { - if (!this.roomId) { - await this.ctx.blockConcurrencyWhile(async () => { - await this.ctx.storage.put('roomId', c.req.param('roomId')); - this.roomId = c.req.param('roomId') as Id<'room'>; - }); - } - return this.handleConnect(c); - }); - } - - fetch(request: Request): Response | Promise { - return this.app.fetch(request); - } - - async handleConnect(ctx: Context): Promise { - const sessionId = ctx.req.query('sessionId'); - const isReadonly = ctx.req.query('isReadOnly') === 'true'; - if (!sessionId) return ctx.json({ error: 'Missing sessionId' }, 400); - - const { 0: clientWebSocket, 1: serverWebSocket } = new WebSocketPair(); - serverWebSocket.accept(); - - const room = await this.getRoom(); - - room.handleSocketConnect({ sessionId, socket: serverWebSocket, isReadonly }); - - return new Response(null, { status: 101, webSocket: clientWebSocket }); - } - - getRoom() { - const roomId = this.roomId; - if (!roomId) throw new Error('Missing roomId'); - - if (!this.roomPromise) { - this.roomPromise = (async () => { - const roomFromBucket = await this.r2.get(`rooms/${roomId}`); - - const initialSnapshot = roomFromBucket ? ((await roomFromBucket.json()) as RoomSnapshot) : undefined; - - return new TLSocketRoom({ - schema, - initialSnapshot, - onDataChange: this.schedulePersistToR2, - }); - })(); - } - - return this.roomPromise; - } - - // we throttle persistance so it only happens every 10 seconds - schedulePersistToR2: () => void = throttle(async () => { - if (!this.roomPromise || !this.roomId) return; - const room = await this.getRoom(); - - // convert the room to JSON and upload it to R2 - const snapshot = JSON.stringify(room.getCurrentSnapshot()); - await this.r2.put(`rooms/${this.roomId}`, snapshot); - - return; - }, WhiteboardDurableObject.PERSIST_INTERVAL); + static PERSIST_INTERVAL = 10_000; + + private r2: R2Bucket; + private roomId: Id<'room'> | null = null; + private roomPromise: Promise> | null = null; + private app: Hono<{ Bindings: Env }>; + + constructor( + private readonly ctx: DurableObjectState, + env: Env + ) { + this.r2 = env.WHITEBOARD_ASSETS_BUCKET; + + ctx.blockConcurrencyWhile(async () => { + this.roomId = ((await this.ctx.storage.get('roomId')) ?? null) as Id<'room'> | null; + }); + + this.app = new Hono<{ Bindings: Env }>(); + + this.app.get('/rooms/:roomId/public/whiteboard/connect', async (c) => { + if (!this.roomId) { + await this.ctx.blockConcurrencyWhile(async () => { + await this.ctx.storage.put('roomId', c.req.param('roomId')); + this.roomId = c.req.param('roomId') as Id<'room'>; + }); + } + return this.handleConnect(c); + }); + } + + fetch(request: Request): Response | Promise { + return this.app.fetch(request); + } + + async handleConnect(ctx: Context): Promise { + const sessionId = ctx.req.query('sessionId'); + const isReadonly = ctx.req.query('isReadOnly') === 'true'; + if (!sessionId) return ctx.json({ error: 'Missing sessionId' }, 400); + + const { 0: clientWebSocket, 1: serverWebSocket } = new WebSocketPair(); + serverWebSocket.accept(); + + const room = await this.getRoom(); + + room.handleSocketConnect({ sessionId, socket: serverWebSocket, isReadonly }); + + return new Response(null, { status: 101, webSocket: clientWebSocket }); + } + + getRoom() { + const roomId = this.roomId; + if (!roomId) throw new Error('Missing roomId'); + + if (!this.roomPromise) { + this.roomPromise = (async () => { + const roomFromBucket = await this.r2.get(`rooms/${roomId}`); + + const initialSnapshot = roomFromBucket + ? ((await roomFromBucket.json()) as RoomSnapshot) + : undefined; + + return new TLSocketRoom({ + schema, + initialSnapshot, + onDataChange: this.schedulePersistToR2, + }); + })(); + } + + return this.roomPromise; + } + + // we throttle persistance so it only happens every 10 seconds + schedulePersistToR2: () => void = throttle(async () => { + if (!this.roomPromise || !this.roomId) return; + const room = await this.getRoom(); + + // convert the room to JSON and upload it to R2 + const snapshot = JSON.stringify(room.getCurrentSnapshot()); + await this.r2.put(`rooms/${this.roomId}`, snapshot); + + return; + }, WhiteboardDurableObject.PERSIST_INTERVAL); } diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 46992d5..5b93ac3 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -1,26 +1,26 @@ +import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; import { Hono } from 'hono'; -import { openAPISpecs } from 'hono-openapi'; -import { roomRouter } from './routes/room.routes'; -import { publicRoomRouter } from './routes/room/publicRoom.routes'; -import { logger } from 'hono/logger'; +import { except } from 'hono/combine'; import { cors } from 'hono/cors'; -import { AppFactory, appFactoryMiddleware } from '@/services/AppFactory'; -import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; +import { HTTPException } from 'hono/http-exception'; +import { logger } from 'hono/logger'; +import { openAPISpecs } from 'hono-openapi'; import { useAuth } from '@/lib/auth'; -import { auth } from '../better-auth.config'; +import { getBilling } from '@/lib/session'; import { authMiddleware } from '@/middleware/auth.middleware'; -import { except } from 'hono/combine'; -import { assetRouter } from './routes/asset.routes'; -import { CustomSandbox as Sandbox } from './containers/CustomSandbox'; +import { RoomServer as PartyServer } from '@/partykit/room.do'; +import { billingRouter } from '@/routes/billing.routes'; import { templateRouter } from '@/routes/template.routes'; +import { webhookRouter } from '@/routes/webhook.routes'; import { PublicRoomSchema } from '@/schema/room.zod'; -import { RoomServer as PartyServer } from '@/partykit/room.do'; +import { AppFactory, appFactoryMiddleware } from '@/services/AppFactory'; +import { auth } from '../better-auth.config'; +import { CustomSandbox as Sandbox } from './containers/CustomSandbox'; import { WhiteboardDurableObject } from './durable-objects/whiteboard.do'; import { PrivateRoomServer } from './partykit/privateRoom.do'; -import { billingRouter } from '@/routes/billing.routes'; -import { webhookRouter } from '@/routes/webhook.routes'; -import { getBilling } from '@/lib/session'; -import { HTTPException } from 'hono/http-exception'; +import { assetRouter } from './routes/asset.routes'; +import { publicRoomRouter } from './routes/room/publicRoom.routes'; +import { roomRouter } from './routes/room.routes'; export interface AppContext { Variables: { diff --git a/apps/api/src/lib/auth.ts b/apps/api/src/lib/auth.ts index fb21d11..7be66cc 100644 --- a/apps/api/src/lib/auth.ts +++ b/apps/api/src/lib/auth.ts @@ -1,18 +1,18 @@ +import * as schema from '@coderscreen/db/user.db'; +import { BetterAuthOptions, betterAuth } from 'better-auth'; import { drizzleAdapter } from 'better-auth/adapters/drizzle'; -import { betterAuth, BetterAuthOptions } from 'better-auth'; import { APIError } from 'better-auth/api'; -import { AppContext } from '@/index'; -import { Context } from 'hono'; -import * as schema from '@coderscreen/db/user.db'; -import { betterAuthConfig } from '../../better-auth.config'; -import { useDb } from '@/db/client'; import { createAuthMiddleware, organization } from 'better-auth/plugins'; import { desc, eq } from 'drizzle-orm'; +import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; +import { Context } from 'hono'; +import { useDb } from '@/db/client'; +import { AppContext } from '@/index'; +import { retryable } from '@/lib/utils'; import { BillingService } from '@/services/billing/Billing.service'; import { UsageService } from '@/services/billing/Usage.service'; -import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; import { LoopsService } from '@/services/third-party/Loops.service'; -import { retryable } from '@/lib/utils'; +import { betterAuthConfig } from '../../better-auth.config'; export const useAuth: ( ctx: Context @@ -130,7 +130,7 @@ export const useAuth: ( before: createAuthMiddleware(async (authCtx) => { if ( authCtx.path === '/organization/invite-member' || - authCtx.path == '/organizaiton/accept-invitation' + authCtx.path === '/organizaiton/accept-invitation' ) { const sessionCookieToken = await authCtx.getSignedCookie( authCtx.context.authCookies.sessionToken.name, @@ -143,6 +143,7 @@ export const useAuth: ( } const session = await getSessionManual({ token: sessionCookieToken, db }); + // biome-ignore lint/suspicious/noExplicitAny: setting so we dont have to perform another db fetch ctx.set('user', {} as any); ctx.set('session', session); diff --git a/apps/api/src/lib/sandbox.ts b/apps/api/src/lib/sandbox.ts index b0b265d..b621a54 100644 --- a/apps/api/src/lib/sandbox.ts +++ b/apps/api/src/lib/sandbox.ts @@ -1,48 +1,48 @@ import { Id } from '@coderscreen/common/id'; -export const getSandboxId = (roomId: Id<'room'>, language?: string) => { - return `s_${roomId}`; +export const getSandboxId = (roomId: Id<'room'>) => { + return `s_${roomId}`; }; export interface ExecuteResponse { - id: string; - success: boolean; - stdout: string; - stderr: string; - exitCode: number; - command: string; - args: string[]; - timestamp: string; - elapsedTime: number; + id: string; + success: boolean; + stdout: string; + stderr: string; + exitCode: number; + command: string; + args: string[]; + timestamp: string; + elapsedTime: number; } export interface FormattedOutput { - success: boolean; - timestamp: string; - stdout: string; - stderr: string; - exitCode: number; - elapsedTime: number; + success: boolean; + timestamp: string; + stdout: string; + stderr: string; + exitCode: number; + elapsedTime: number; } -export const formatExecOutput = (output: void | ExecuteResponse): FormattedOutput => { - if (!output) { - return { - success: false, - timestamp: new Date().toISOString(), - stdout: '', - stderr: 'No output from execution', - exitCode: 0, - elapsedTime: 0, - }; - } +export const formatExecOutput = (output: ExecuteResponse): FormattedOutput => { + if (!output) { + return { + success: false, + timestamp: new Date().toISOString(), + stdout: '', + stderr: 'No output from execution', + exitCode: 0, + elapsedTime: 0, + }; + } - return { - success: output.success, - timestamp: output.timestamp, - stdout: output.stdout, - stderr: output.stderr, - exitCode: output.exitCode, - elapsedTime: output.elapsedTime, - }; + return { + success: output.success, + timestamp: output.timestamp, + stdout: output.stdout, + stderr: output.stderr, + exitCode: output.exitCode, + elapsedTime: output.elapsedTime, + }; }; diff --git a/apps/api/src/lib/session.ts b/apps/api/src/lib/session.ts index dec22c8..3fa5c8c 100644 --- a/apps/api/src/lib/session.ts +++ b/apps/api/src/lib/session.ts @@ -1,8 +1,8 @@ -import { Context } from 'hono'; -import { AppContext } from '../index'; -import { BillingService } from '@/services/billing/Billing.service'; import { PlanEntity, SubscriptionEntity } from '@coderscreen/db/billing.db'; +import { Context } from 'hono'; import { HTTPException } from 'hono/http-exception'; +import { BillingService } from '@/services/billing/Billing.service'; +import { AppContext } from '../index'; export const getSession = (ctx: Context, options?: { noActiveOrg?: boolean }) => { const user = ctx.get('user'); @@ -23,6 +23,7 @@ export const getSession = (ctx: Context, options?: { noActiveOrg?: b return { user, session, + // biome-ignore lint/style/noNonNullAssertion: needed for option orgId: session.activeOrganizationId!, }; }; diff --git a/apps/api/src/lib/utils.ts b/apps/api/src/lib/utils.ts index 6f3e34f..7436170 100644 --- a/apps/api/src/lib/utils.ts +++ b/apps/api/src/lib/utils.ts @@ -23,7 +23,11 @@ export const retryable = async (fn: () => Promise, retries = 3, delay = 10 * @param fn - The function to execute * @returns The result of the function */ -export const withContext = async (ctx: Context, key: string, fn: () => Promise) => { +export const withContext = async ( + ctx: Context, + key: string, + fn: () => Promise +): Promise => { const cache = await ctx.var.get(key); if (cache) { return cache; diff --git a/apps/api/src/middleware/auth.middleware.ts b/apps/api/src/middleware/auth.middleware.ts index 857a60e..9c479c7 100644 --- a/apps/api/src/middleware/auth.middleware.ts +++ b/apps/api/src/middleware/auth.middleware.ts @@ -1,19 +1,19 @@ -import { AppContext } from '@/index'; -import { useAuth } from '@/lib/auth'; import { createMiddleware } from 'hono/factory'; import { HTTPException } from 'hono/http-exception'; +import { AppContext } from '@/index'; +import { useAuth } from '@/lib/auth'; export const authMiddleware = createMiddleware(async (ctx, next) => { - const auth = useAuth(ctx); - const session = await auth.api.getSession({ headers: ctx.req.raw.headers }); + const auth = useAuth(ctx); + const session = await auth.api.getSession({ headers: ctx.req.raw.headers }); - if (!session) { - throw new HTTPException(401, { - message: 'Unauthorized', - }); - } + if (!session) { + throw new HTTPException(401, { + message: 'Unauthorized', + }); + } - ctx.set('user', session.user); - ctx.set('session', session.session); - return next(); + ctx.set('user', session.user); + ctx.set('session', session.session); + return next(); }); diff --git a/apps/api/src/middleware/partyKit.middleware.ts b/apps/api/src/middleware/partyKit.middleware.ts index cbeb7a4..d6adcd8 100644 --- a/apps/api/src/middleware/partyKit.middleware.ts +++ b/apps/api/src/middleware/partyKit.middleware.ts @@ -1,9 +1,9 @@ +import { Id } from '@coderscreen/common/id'; +import { createMiddleware } from 'hono/factory'; +import { HTTPException } from 'hono/http-exception'; import { partyserverMiddleware } from 'hono-party'; import { AppContext } from '@/index'; -import { HTTPException } from 'hono/http-exception'; -import { createMiddleware } from 'hono/factory'; import { RoomService } from '@/services/Room.service'; -import { Id } from '@coderscreen/common/id'; export const partyKitMiddleware = createMiddleware(async (ctx, next) => { const publicRoom = ctx.get('publicRoom'); diff --git a/apps/api/src/middleware/room.middleware.ts b/apps/api/src/middleware/room.middleware.ts index b868afe..a785abd 100644 --- a/apps/api/src/middleware/room.middleware.ts +++ b/apps/api/src/middleware/room.middleware.ts @@ -1,57 +1,57 @@ -import { AppContext } from '@/index'; -import { RoomService } from '@/services/Room.service'; import { Id } from '@coderscreen/common/id'; import { createMiddleware } from 'hono/factory'; import { HTTPException } from 'hono/http-exception'; +import { AppContext } from '@/index'; import { useAuth } from '@/lib/auth'; +import { RoomService } from '@/services/Room.service'; export const publicRoomMiddleware = createMiddleware(async (ctx, next) => { - const roomId = ctx.req.param('roomId'); - - if (!roomId) { - throw new HTTPException(413, { - message: 'roomId parameter not specified', - }); - } - - const room = await new RoomService(ctx).getPublicRoom(roomId as Id<'room'>); - if (!room) { - throw new HTTPException(404, { - message: 'Room not found', - }); - } - - ctx.set('publicRoom', room); - - // Check if this is a GET request to the root route (/:roomId) - const isGetRootRoute = ctx.req.method === 'GET' && ctx.req.path.endsWith(`/${roomId}/public`); - const publicCanConnect = room.status === 'active'; - - if (isGetRootRoute) { - // this route is always public - return next(); - } - - if (publicCanConnect) { - // if room is active, always allow new connections - return next(); - } - - // otherwise, only authed users with access to the room can connect - const auth = useAuth(ctx); - const session = await auth.api.getSession({ headers: ctx.req.raw.headers }); - - if (!session) { - throw new HTTPException(401, { - message: 'Room is no longer active, must be authenticated to connect', - }); - } - - if (session.session.activeOrganizationId !== room.organizationId) { - throw new HTTPException(401, { - message: 'Unauthorized to connect to this room', - }); - } - - return next(); + const roomId = ctx.req.param('roomId'); + + if (!roomId) { + throw new HTTPException(413, { + message: 'roomId parameter not specified', + }); + } + + const room = await new RoomService(ctx).getPublicRoom(roomId as Id<'room'>); + if (!room) { + throw new HTTPException(404, { + message: 'Room not found', + }); + } + + ctx.set('publicRoom', room); + + // Check if this is a GET request to the root route (/:roomId) + const isGetRootRoute = ctx.req.method === 'GET' && ctx.req.path.endsWith(`/${roomId}/public`); + const publicCanConnect = room.status === 'active'; + + if (isGetRootRoute) { + // this route is always public + return next(); + } + + if (publicCanConnect) { + // if room is active, always allow new connections + return next(); + } + + // otherwise, only authed users with access to the room can connect + const auth = useAuth(ctx); + const session = await auth.api.getSession({ headers: ctx.req.raw.headers }); + + if (!session) { + throw new HTTPException(401, { + message: 'Room is no longer active, must be authenticated to connect', + }); + } + + if (session.session.activeOrganizationId !== room.organizationId) { + throw new HTTPException(401, { + message: 'Unauthorized to connect to this room', + }); + } + + return next(); }); diff --git a/apps/api/src/partykit/internal/AI.service.ts b/apps/api/src/partykit/internal/AI.service.ts index f540500..d53b976 100644 --- a/apps/api/src/partykit/internal/AI.service.ts +++ b/apps/api/src/partykit/internal/AI.service.ts @@ -1,4 +1,3 @@ -import { AppContext } from '@/index'; import { generateId } from '@coderscreen/common/id'; import { LLMMessageEntity, llmMessageTable } from '@coderscreen/db/llmMessage.db'; import { RoomEntity } from '@coderscreen/db/room.db'; @@ -6,6 +5,7 @@ import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js'; import { OpenAI } from 'openai'; import postgres from 'postgres'; import * as Y from 'yjs'; +import { AppContext } from '@/index'; import { SupportedModels } from '@/schema/ai.zod'; export interface User { @@ -42,7 +42,8 @@ export class AIService { private db: PostgresJsDatabase | null = null; private room: RoomEntity; - static SYSTEM_PROMPT = `You are an AI assistant conducting a technical interview. You are helping evaluate a candidate's coding skills and problem-solving abilities. + static SYSTEM_PROMPT = + `You are an AI assistant conducting a technical interview. You are helping evaluate a candidate's coding skills and problem-solving abilities. Your role is to: - Ask clarifying questions about the candidate's approach diff --git a/apps/api/src/partykit/internal/Sandbox.service.ts b/apps/api/src/partykit/internal/Sandbox.service.ts index e10e084..c8f0bea 100644 --- a/apps/api/src/partykit/internal/Sandbox.service.ts +++ b/apps/api/src/partykit/internal/Sandbox.service.ts @@ -1,57 +1,57 @@ +import { Id } from '@coderscreen/common/id'; import { AppContext } from '@/index'; import { getSandboxId } from '@/lib/sandbox'; -import { Id } from '@coderscreen/common/id'; export class SandboxService { - constructor(private readonly env: AppContext['Bindings']) {} + constructor(private readonly env: AppContext['Bindings']) {} - async startSandbox(params: { roomId: Id<'room'>; language: string }) { - const sandbox = this.getSandbox(params.roomId, params.language); - sandbox.start(); - } + async startSandbox(params: { roomId: Id<'room'> }) { + const sandbox = this.getSandbox(params.roomId); + sandbox.start(); + } - private getSandbox(roomId: Id<'room'>, language: string) { - const sandboxId = this.getId(roomId, language); - return this.env.SANDBOX.get(sandboxId.durableObjectId); - } + private getSandbox(roomId: Id<'room'>) { + const sandboxId = this.getId(roomId); + return this.env.SANDBOX.get(sandboxId.durableObjectId); + } - private getId(roomId: Id<'room'>, language: string) { - const rawSandboxId = getSandboxId(roomId, language); - const sandboxId = this.env.SANDBOX.idFromName(rawSandboxId); + private getId(roomId: Id<'room'>) { + const rawSandboxId = getSandboxId(roomId); + const sandboxId = this.env.SANDBOX.idFromName(rawSandboxId); - return { - id: rawSandboxId, - durableObjectId: sandboxId, - }; - } + return { + id: rawSandboxId, + durableObjectId: sandboxId, + }; + } - // private getNamespace(language: RoomEntity['language']) { - // switch (language) { - // case 'typescript': - // return this.env.SANDBOX_NODE; - // case 'javascript': - // return this.env.SANDBOX_NODE; - // case 'python': - // return this.env.SANDBOX_PYTHON; - // case 'rust': - // return this.env.SANDBOX_RUST; - // case 'c++': - // return this.env.SANDBOX_CPP; - // case 'c': - // return this.env.SANDBOX_C; - // case 'java': - // return this.env.SANDBOX_JAVA; - // case 'go': - // return this.env.SANDBOX_GO; - // case 'php': - // return this.env.SANDBOX_PHP; - // case 'ruby': - // return this.env.SANDBOX_RUBY; - // case 'bash': - // // can use any sandbox and just run bash commands - // return this.env.SANDBOX_NODE; - // default: - // throw new Error(`Unsupported language: ${language}`); - // } - // } + // private getNamespace(language: RoomEntity['language']) { + // switch (language) { + // case 'typescript': + // return this.env.SANDBOX_NODE; + // case 'javascript': + // return this.env.SANDBOX_NODE; + // case 'python': + // return this.env.SANDBOX_PYTHON; + // case 'rust': + // return this.env.SANDBOX_RUST; + // case 'c++': + // return this.env.SANDBOX_CPP; + // case 'c': + // return this.env.SANDBOX_C; + // case 'java': + // return this.env.SANDBOX_JAVA; + // case 'go': + // return this.env.SANDBOX_GO; + // case 'php': + // return this.env.SANDBOX_PHP; + // case 'ruby': + // return this.env.SANDBOX_RUBY; + // case 'bash': + // // can use any sandbox and just run bash commands + // return this.env.SANDBOX_NODE; + // default: + // throw new Error(`Unsupported language: ${language}`); + // } + // } } diff --git a/apps/api/src/partykit/privateRoom.do.ts b/apps/api/src/partykit/privateRoom.do.ts index 966b4c7..2b85013 100644 --- a/apps/api/src/partykit/privateRoom.do.ts +++ b/apps/api/src/partykit/privateRoom.do.ts @@ -1,23 +1,18 @@ -import { AppContext } from '@/index'; -import { RoomContentEntity, roomContentTable } from '@coderscreen/db/roomContent.db'; +import { Id } from '@coderscreen/common/id'; import { RoomEntity, roomTable } from '@coderscreen/db/room.db'; +import { RoomContentEntity, roomContentTable } from '@coderscreen/db/roomContent.db'; import { eq } from 'drizzle-orm'; -import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; +import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js'; +import postgres from 'postgres'; import { YServer } from 'y-partyserver'; -import { Id } from '@coderscreen/common/id'; import * as Y from 'yjs'; -import postgres from 'postgres'; -import { drizzle } from 'drizzle-orm/postgres-js'; +import { AppContext } from '@/index'; export class PrivateRoomServer extends YServer { private db: PostgresJsDatabase | null = null; private room: RoomEntity | null = null; - constructor(ctx: DurableObjectState, env: Env) { - super(ctx, env); - } - /* control how often the onSave handler * is called with these options */ static callbackOptions = { diff --git a/apps/api/src/partykit/room.do.ts b/apps/api/src/partykit/room.do.ts index f6baa64..85f634e 100644 --- a/apps/api/src/partykit/room.do.ts +++ b/apps/api/src/partykit/room.do.ts @@ -1,14 +1,14 @@ -import { YServer } from 'y-partyserver'; -import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js'; -import { AppContext } from '@/index'; -import postgres from 'postgres'; import { Id } from '@coderscreen/common/id'; -import { eq } from 'drizzle-orm'; import { RoomEntity, roomTable } from '@coderscreen/db/room.db'; import { RoomContentEntity, roomContentTable } from '@coderscreen/db/roomContent.db'; +import { eq } from 'drizzle-orm'; +import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js'; +import postgres from 'postgres'; +import { YServer } from 'y-partyserver'; import * as Y from 'yjs'; -import { SandboxService } from './internal/Sandbox.service'; +import { AppContext } from '@/index'; import { AIService, ChatMessage, User } from './internal/AI.service'; +import { SandboxService } from './internal/Sandbox.service'; const KEYS = { trackedUsers: 'tracked-users', @@ -69,7 +69,7 @@ export class RoomServer extends YServer { } // warm up the sandbox - this.createNewSandbox(this.room.language); + this.createNewSandbox(); this.document.awareness.on( 'change', @@ -216,11 +216,11 @@ export class RoomServer extends YServer { return this.sandboxService; } - private createNewSandbox(language: RoomEntity['language']) { + private createNewSandbox() { const room = this.getRoom(); const roomId = room.id; - this.ctx.waitUntil(this.getSandbox().startSandbox({ roomId, language })); + this.ctx.waitUntil(this.getSandbox().startSandbox({ roomId })); } // AI Chat Methods diff --git a/apps/api/src/routes/asset.routes.ts b/apps/api/src/routes/asset.routes.ts index fd847ea..8a7a268 100644 --- a/apps/api/src/routes/asset.routes.ts +++ b/apps/api/src/routes/asset.routes.ts @@ -1,48 +1,48 @@ -import { AppContext } from '@/index'; -import { AssetSchema } from '@/schema/asset.zod'; -import { AssetService } from '@/services/Asset.service'; import { zValidator } from '@hono/zod-validator'; import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; import { describeRoute } from 'hono-openapi'; import { resolver } from 'hono-openapi/zod'; -import { HTTPException } from 'hono/http-exception'; import { z } from 'zod'; +import { AppContext } from '@/index'; +import { AssetSchema } from '@/schema/asset.zod'; +import { AssetService } from '@/services/Asset.service'; export const assetRouter = new Hono() - // PUT /assets/logo - Upload an organization logo - .put( - '/logo', - describeRoute({ - description: 'Upload an organization logo', - responses: { - 200: { - description: 'Logo uploaded successfully', - content: { - 'application/json': { - schema: resolver(AssetSchema), - }, - }, - }, - }, - }), - zValidator( - 'json', - z.object({ - data: z.string().describe('The base64 encoded image data'), - }), - ), - async (ctx) => { - const assetService = new AssetService(ctx); - const body = ctx.req.valid('json'); + // PUT /assets/logo - Upload an organization logo + .put( + '/logo', + describeRoute({ + description: 'Upload an organization logo', + responses: { + 200: { + description: 'Logo uploaded successfully', + content: { + 'application/json': { + schema: resolver(AssetSchema), + }, + }, + }, + }, + }), + zValidator( + 'json', + z.object({ + data: z.string().describe('The base64 encoded image data'), + }) + ), + async (ctx) => { + const assetService = new AssetService(ctx); + const body = ctx.req.valid('json'); - // if data is over 10mb, return a 413 error - if (body.data.length > 10 * 1024 * 1024) { - throw new HTTPException(413, { - message: 'Image is too large', - }); - } + // if data is over 10mb, return a 413 error + if (body.data.length > 10 * 1024 * 1024) { + throw new HTTPException(413, { + message: 'Image is too large', + }); + } - const result = await assetService.uploadImage(body.data); - return ctx.json(result, 201); - }, - ); + const result = await assetService.uploadImage(body.data); + return ctx.json(result, 201); + } + ); diff --git a/apps/api/src/routes/billing.routes.ts b/apps/api/src/routes/billing.routes.ts index 057bce5..fa91526 100644 --- a/apps/api/src/routes/billing.routes.ts +++ b/apps/api/src/routes/billing.routes.ts @@ -3,18 +3,18 @@ import { describeRoute } from 'hono-openapi'; import { resolver, validator as zValidator } from 'hono-openapi/zod'; import { z } from 'zod'; import { AppContext } from '@/index'; -import { BillingService } from '@/services/billing/Billing.service'; +import { getSession } from '@/lib/session'; import { - SubscriptionSchema, - PlanSchema, CheckoutSessionSchema, - PortalSessionSchema, CreateCheckoutSchema, CreatePortalSchema, + PlanSchema, + PortalSessionSchema, + SubscriptionSchema, } from '@/schema/billing.zod'; -import { getSession } from '@/lib/session'; -import { UsageService } from '@/services/billing/Usage.service'; import { UsageResultSchema } from '@/schema/usage.zod'; +import { BillingService } from '@/services/billing/Billing.service'; +import { UsageService } from '@/services/billing/Usage.service'; export const billingRouter = new Hono() // GET /billing/customer - Get customer and subscription info @@ -84,7 +84,7 @@ export const billingRouter = new Hono() zValidator('json', CreateCheckoutSchema), async (ctx) => { const { orgId } = getSession(ctx); - const { priceId, successUrl, cancelUrl } = ctx.req.valid('json'); + const { priceId, successUrl } = ctx.req.valid('json'); const billingService = new BillingService(ctx); // Get customer by organization diff --git a/apps/api/src/routes/room.routes.ts b/apps/api/src/routes/room.routes.ts index e51798f..8e7b9ed 100644 --- a/apps/api/src/routes/room.routes.ts +++ b/apps/api/src/routes/room.routes.ts @@ -1,15 +1,15 @@ +import { idString } from '@coderscreen/common/id'; import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; import { describeRoute } from 'hono-openapi'; import { resolver, validator as zValidator } from 'hono-openapi/zod'; import { z } from 'zod'; -import { AppContext } from '..'; -import { RoomService } from '@/services/Room.service'; +import { privatePartyKitMiddleware } from '@/middleware/partyKit.middleware'; import { RoomSchema } from '@/schema/room.zod'; -import { idString } from '@coderscreen/common/id'; import { useAppFactory } from '@/services/AppFactory'; +import { RoomService } from '@/services/Room.service'; import { TemplateService } from '@/services/Template.service'; -import { HTTPException } from 'hono/http-exception'; -import { privatePartyKitMiddleware } from '@/middleware/partyKit.middleware'; +import { AppContext } from '..'; export const roomRouter = new Hono() .use('/:id/connect/*', privatePartyKitMiddleware) @@ -229,10 +229,10 @@ export const roomRouter = new Hono() }); } - await roomService.loadTemplate({ - room, - template, - }); + // await roomService.loadTemplate({ + // room, + // template, + // }); // return room; } diff --git a/apps/api/src/routes/room/publicRoom.routes.ts b/apps/api/src/routes/room/publicRoom.routes.ts index 30ab020..8d20ae1 100644 --- a/apps/api/src/routes/room/publicRoom.routes.ts +++ b/apps/api/src/routes/room/publicRoom.routes.ts @@ -1,17 +1,17 @@ -import { z } from 'zod'; +import { idString } from '@coderscreen/common/id'; import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; import { describeRoute } from 'hono-openapi'; import { resolver, validator as zValidator } from 'hono-openapi/zod'; -import { AppContext } from '../..'; -import { idString } from '@coderscreen/common/id'; -import { RoomService } from '@/services/Room.service'; +import { z } from 'zod'; +import { partyKitMiddleware } from '@/middleware/partyKit.middleware'; import { publicRoomMiddleware } from '@/middleware/room.middleware'; -import { CodeRunService } from '@/services/CodeRun.service'; +import { whiteboardRouter } from '@/routes/room/whiteboard.router'; import { PublicRoomSchema, RoomLanguageSchema } from '@/schema/room.zod'; -import { partyKitMiddleware } from '@/middleware/partyKit.middleware'; import { ExecOutputSchema } from '@/schema/sandbox.zod'; -import { whiteboardRouter } from '@/routes/room/whiteboard.router'; -import { HTTPException } from 'hono/http-exception'; +import { CodeRunService } from '@/services/CodeRun.service'; +import { RoomService } from '@/services/Room.service'; +import { AppContext } from '../..'; export const publicRoomRouter = new Hono() .use(publicRoomMiddleware) diff --git a/apps/api/src/routes/room/whiteboard.router.ts b/apps/api/src/routes/room/whiteboard.router.ts index 5ec732e..4758fa9 100644 --- a/apps/api/src/routes/room/whiteboard.router.ts +++ b/apps/api/src/routes/room/whiteboard.router.ts @@ -1,231 +1,241 @@ -import { z } from 'zod'; +import { idString } from '@coderscreen/common/id'; import { Hono } from 'hono'; import { describeRoute } from 'hono-openapi'; import { resolver, validator as zValidator } from 'hono-openapi/zod'; +import { z } from 'zod'; import { AppContext } from '../..'; -import { idString } from '@coderscreen/common/id'; // Schema definitions for OpenAPI const UploadResponseSchema = z.object({ - success: z.boolean(), - url: z.string().optional(), - error: z.string().optional(), + success: z.boolean(), + url: z.string().optional(), + error: z.string().optional(), }); const UnfurlResponseSchema = z.object({ - title: z.string().optional(), - description: z.string().optional(), - image: z.string().optional(), - url: z.string(), + title: z.string().optional(), + description: z.string().optional(), + image: z.string().optional(), + url: z.string(), }); export const whiteboardRouter = new Hono() - // GET /whiteboard/connect - Connect to the whiteboard websocket - .get( - '/connect', - describeRoute({ - description: 'Connect to the whiteboard websocket for realtime syncing', - responses: { - 101: { - description: 'Websocket connected', - }, - }, - }), - zValidator( - 'param', - z.object({ - roomId: idString('room'), - }) - ), - async (ctx) => { - const { roomId } = ctx.req.valid('param'); - - // Route to the Whiteboard Durable Object for realtime websocket syncing - // Note: WHITEBOARD_DO needs to be added to the environment bindings - const whiteboardDo = ctx.env.WHITEBOARD_DO; - if (!whiteboardDo) { - return ctx.json({ error: 'Whiteboard service not available' }, 503); - } - - const id = whiteboardDo.idFromName(roomId); - const room = whiteboardDo.get(id); - - const isReadOnly = ctx.get('publicRoom')?.status !== 'active'; - - // attach new query params to the request - const newReqUrl = new URL(ctx.req.raw.url); - newReqUrl.searchParams.set('isReadOnly', isReadOnly ? 'true' : 'false'); - - return room.fetch(newReqUrl, { - headers: ctx.req.raw.headers, - body: ctx.req.raw.body, - }); - } - ) - // POST /whiteboard/uploads/:uploadId - Upload assets to the bucket - .post( - '/uploads/:uploadId', - describeRoute({ - description: 'Upload assets to the whiteboard bucket', - responses: { - 200: { - description: 'Asset uploaded successfully', - content: { - 'application/json': { - schema: resolver(UploadResponseSchema), - }, - }, - }, - }, - }), - zValidator( - 'param', - z.object({ - uploadId: z.string(), - }) - ), - async (ctx) => { - const { uploadId } = ctx.req.valid('param'); - - try { - // Get the file data from the request - const formData = await ctx.req.formData(); - const file = formData.get('file') as File; - - if (!file) { - return ctx.json({ success: false, error: 'No file provided' }, 400); - } - - // Upload to the whiteboard assets bucket - await ctx.env.WHITEBOARD_ASSETS_BUCKET.put(uploadId, file, { - httpMetadata: { - contentType: file.type, - }, - }); - - const url = `${ctx.env.ASSETS_URL}/whiteboard/uploads/${uploadId}`; - - return ctx.json({ success: true, url }); - } catch (error) { - console.error('Error uploading asset:', error); - return ctx.json({ success: false, error: 'Upload failed' }, 500); - } - } - ) - // GET /whiteboard/uploads/:uploadId - Download assets from the bucket - .get( - '/uploads/:uploadId', - describeRoute({ - description: 'Download assets from the whiteboard bucket', - responses: { - 200: { - description: 'Asset downloaded successfully', - content: { - 'application/octet-stream': { - schema: { - type: 'string', - format: 'binary', - }, - }, - }, - }, - 404: { - description: 'Asset not found', - }, - }, - }), - zValidator( - 'param', - z.object({ - uploadId: z.string(), - }) - ), - async (ctx) => { - const { uploadId } = ctx.req.valid('param'); - - try { - const object = await ctx.env.WHITEBOARD_ASSETS_BUCKET.get(uploadId); - - if (!object) { - return ctx.json({ error: 'Asset not found' }, 404); - } - - // Return the asset with appropriate headers - const headers = new Headers(); - if (object.httpMetadata?.contentType) { - headers.set('Content-Type', object.httpMetadata.contentType); - } - headers.set('Content-Length', object.size.toString()); - headers.set('Cache-Control', 'public, max-age=31536000'); // 1 year cache - - return new Response(object.body, { - headers, - status: 200, - }); - } catch (error) { - console.error('Error downloading asset:', error); - return ctx.json({ error: 'Download failed' }, 500); - } - } - ) - // GET /whiteboard/unfurl - Extract metadata from pasted URLs - .get( - '/unfurl', - describeRoute({ - description: 'Extract metadata from pasted URLs for bookmarks', - responses: { - 200: { - description: 'URL metadata extracted successfully', - content: { - 'application/json': { - schema: resolver(UnfurlResponseSchema), - }, - }, - }, - }, - }), - zValidator( - 'query', - z.object({ - url: z.string().url(), - }) - ), - async (ctx) => { - const { url } = ctx.req.valid('query'); - - try { - // Fetch the URL to extract metadata - const response = await fetch(url, { - headers: { - 'User-Agent': 'Mozilla/5.0 (compatible; WhiteboardBot/1.0)', - }, - }); - - if (!response.ok) { - return ctx.json({ error: 'Failed to fetch URL' }, 400); - } - - const html = await response.text(); - - // Extract metadata using regex patterns - const titleMatch = html.match(/]*>([^<]+)<\/title>/i); - const descriptionMatch = html.match(/]*name=["']description["'][^>]*content=["']([^"']+)["']/i); - const ogImageMatch = html.match(/]*property=["']og:image["'][^>]*content=["']([^"']+)["']/i); - const twitterImageMatch = html.match(/]*name=["']twitter:image["'][^>]*content=["']([^"']+)["']/i); - - const title = titleMatch ? titleMatch[1].trim() : undefined; - const description = descriptionMatch ? descriptionMatch[1].trim() : undefined; - const image = ogImageMatch ? ogImageMatch[1] : twitterImageMatch ? twitterImageMatch[1] : undefined; - - return ctx.json({ - title, - description, - image, - url, - }); - } catch (error) { - console.error('Error unfurling URL:', error); - return ctx.json({ error: 'Failed to extract metadata' }, 500); - } - } - ); + // GET /whiteboard/connect - Connect to the whiteboard websocket + .get( + '/connect', + describeRoute({ + description: 'Connect to the whiteboard websocket for realtime syncing', + responses: { + 101: { + description: 'Websocket connected', + }, + }, + }), + zValidator( + 'param', + z.object({ + roomId: idString('room'), + }) + ), + async (ctx) => { + const { roomId } = ctx.req.valid('param'); + + // Route to the Whiteboard Durable Object for realtime websocket syncing + // Note: WHITEBOARD_DO needs to be added to the environment bindings + const whiteboardDo = ctx.env.WHITEBOARD_DO; + if (!whiteboardDo) { + return ctx.json({ error: 'Whiteboard service not available' }, 503); + } + + const id = whiteboardDo.idFromName(roomId); + const room = whiteboardDo.get(id); + + const isReadOnly = ctx.get('publicRoom')?.status !== 'active'; + + // attach new query params to the request + const newReqUrl = new URL(ctx.req.raw.url); + newReqUrl.searchParams.set('isReadOnly', isReadOnly ? 'true' : 'false'); + + return room.fetch(newReqUrl, { + headers: ctx.req.raw.headers, + body: ctx.req.raw.body, + }); + } + ) + // POST /whiteboard/uploads/:uploadId - Upload assets to the bucket + .post( + '/uploads/:uploadId', + describeRoute({ + description: 'Upload assets to the whiteboard bucket', + responses: { + 200: { + description: 'Asset uploaded successfully', + content: { + 'application/json': { + schema: resolver(UploadResponseSchema), + }, + }, + }, + }, + }), + zValidator( + 'param', + z.object({ + uploadId: z.string(), + }) + ), + async (ctx) => { + const { uploadId } = ctx.req.valid('param'); + + try { + // Get the file data from the request + const formData = await ctx.req.formData(); + const file = formData.get('file') as File; + + if (!file) { + return ctx.json({ success: false, error: 'No file provided' }, 400); + } + + // Upload to the whiteboard assets bucket + await ctx.env.WHITEBOARD_ASSETS_BUCKET.put(uploadId, file, { + httpMetadata: { + contentType: file.type, + }, + }); + + const url = `${ctx.env.ASSETS_URL}/whiteboard/uploads/${uploadId}`; + + return ctx.json({ success: true, url }); + } catch (error) { + console.error('Error uploading asset:', error); + return ctx.json({ success: false, error: 'Upload failed' }, 500); + } + } + ) + // GET /whiteboard/uploads/:uploadId - Download assets from the bucket + .get( + '/uploads/:uploadId', + describeRoute({ + description: 'Download assets from the whiteboard bucket', + responses: { + 200: { + description: 'Asset downloaded successfully', + content: { + 'application/octet-stream': { + schema: { + type: 'string', + format: 'binary', + }, + }, + }, + }, + 404: { + description: 'Asset not found', + }, + }, + }), + zValidator( + 'param', + z.object({ + uploadId: z.string(), + }) + ), + async (ctx) => { + const { uploadId } = ctx.req.valid('param'); + + try { + const object = await ctx.env.WHITEBOARD_ASSETS_BUCKET.get(uploadId); + + if (!object) { + return ctx.json({ error: 'Asset not found' }, 404); + } + + // Return the asset with appropriate headers + const headers = new Headers(); + if (object.httpMetadata?.contentType) { + headers.set('Content-Type', object.httpMetadata.contentType); + } + headers.set('Content-Length', object.size.toString()); + headers.set('Cache-Control', 'public, max-age=31536000'); // 1 year cache + + return new Response(object.body, { + headers, + status: 200, + }); + } catch (error) { + console.error('Error downloading asset:', error); + return ctx.json({ error: 'Download failed' }, 500); + } + } + ) + // GET /whiteboard/unfurl - Extract metadata from pasted URLs + .get( + '/unfurl', + describeRoute({ + description: 'Extract metadata from pasted URLs for bookmarks', + responses: { + 200: { + description: 'URL metadata extracted successfully', + content: { + 'application/json': { + schema: resolver(UnfurlResponseSchema), + }, + }, + }, + }, + }), + zValidator( + 'query', + z.object({ + url: z.string().url(), + }) + ), + async (ctx) => { + const { url } = ctx.req.valid('query'); + + try { + // Fetch the URL to extract metadata + const response = await fetch(url, { + headers: { + 'User-Agent': 'Mozilla/5.0 (compatible; WhiteboardBot/1.0)', + }, + }); + + if (!response.ok) { + return ctx.json({ error: 'Failed to fetch URL' }, 400); + } + + const html = await response.text(); + + // Extract metadata using regex patterns + const titleMatch = html.match(/]*>([^<]+)<\/title>/i); + const descriptionMatch = html.match( + /]*name=["']description["'][^>]*content=["']([^"']+)["']/i + ); + const ogImageMatch = html.match( + /]*property=["']og:image["'][^>]*content=["']([^"']+)["']/i + ); + const twitterImageMatch = html.match( + /]*name=["']twitter:image["'][^>]*content=["']([^"']+)["']/i + ); + + const title = titleMatch ? titleMatch[1].trim() : undefined; + const description = descriptionMatch ? descriptionMatch[1].trim() : undefined; + const image = ogImageMatch + ? ogImageMatch[1] + : twitterImageMatch + ? twitterImageMatch[1] + : undefined; + + return ctx.json({ + title, + description, + image, + url, + }); + } catch (error) { + console.error('Error unfurling URL:', error); + return ctx.json({ error: 'Failed to extract metadata' }, 500); + } + } + ); diff --git a/apps/api/src/routes/template.routes.ts b/apps/api/src/routes/template.routes.ts index cd2dd78..c601d5a 100644 --- a/apps/api/src/routes/template.routes.ts +++ b/apps/api/src/routes/template.routes.ts @@ -1,157 +1,157 @@ +import { idString } from '@coderscreen/common/id'; import { Hono } from 'hono'; import { describeRoute } from 'hono-openapi'; import { resolver, validator as zValidator } from 'hono-openapi/zod'; import { z } from 'zod'; -import { AppContext } from '..'; -import { TemplateService } from '@/services/Template.service'; import { TemplateSchema } from '@/schema/template.zod'; -import { idString } from '@coderscreen/common/id'; +import { TemplateService } from '@/services/Template.service'; +import { AppContext } from '..'; export const templateRouter = new Hono() - // GET /templates - List all templates - .get( - '/', - describeRoute({ - description: 'Get all templates', - responses: { - 200: { - description: 'List of templates', - content: { - 'application/json': { - schema: resolver(z.array(TemplateSchema)), - }, - }, - }, - }, - }), - async (ctx) => { - const templateService = new TemplateService(ctx); - const templates = await templateService.listTemplates(); - return ctx.json(templates); - }, - ) - // POST /templates - Create a new template - .post( - '/', - describeRoute({ - description: 'Create a new template', - responses: { - 200: { - description: 'Template created successfully', - content: { - 'application/json': { - schema: resolver(TemplateSchema), - }, - }, - }, - }, - }), - zValidator('json', TemplateSchema.omit({ id: true, createdAt: true, updatedAt: true })), - async (ctx) => { - const templateService = new TemplateService(ctx); - const body = ctx.req.valid('json'); + // GET /templates - List all templates + .get( + '/', + describeRoute({ + description: 'Get all templates', + responses: { + 200: { + description: 'List of templates', + content: { + 'application/json': { + schema: resolver(z.array(TemplateSchema)), + }, + }, + }, + }, + }), + async (ctx) => { + const templateService = new TemplateService(ctx); + const templates = await templateService.listTemplates(); + return ctx.json(templates); + } + ) + // POST /templates - Create a new template + .post( + '/', + describeRoute({ + description: 'Create a new template', + responses: { + 200: { + description: 'Template created successfully', + content: { + 'application/json': { + schema: resolver(TemplateSchema), + }, + }, + }, + }, + }), + zValidator('json', TemplateSchema.omit({ id: true, createdAt: true, updatedAt: true })), + async (ctx) => { + const templateService = new TemplateService(ctx); + const body = ctx.req.valid('json'); - const result = await templateService.createTemplate({ - ...body, - }); + const result = await templateService.createTemplate({ + ...body, + }); - return ctx.json(result, 201); - }, - ) - // GET /templates/:id - Get a specific template - .get( - '/:id', - describeRoute({ - description: 'Get a specific template by ID', - responses: { - 200: { - description: 'Template details', - content: { - 'application/json': { - schema: resolver(TemplateSchema), - }, - }, - }, - 404: { - description: 'Template not found', - }, - }, - }), - zValidator( - 'param', - z.object({ - id: idString('template'), - }), - ), - async (ctx) => { - const templateService = new TemplateService(ctx); - const { id } = ctx.req.valid('param'); - const template = await templateService.getTemplate(id); + return ctx.json(result, 201); + } + ) + // GET /templates/:id - Get a specific template + .get( + '/:id', + describeRoute({ + description: 'Get a specific template by ID', + responses: { + 200: { + description: 'Template details', + content: { + 'application/json': { + schema: resolver(TemplateSchema), + }, + }, + }, + 404: { + description: 'Template not found', + }, + }, + }), + zValidator( + 'param', + z.object({ + id: idString('template'), + }) + ), + async (ctx) => { + const templateService = new TemplateService(ctx); + const { id } = ctx.req.valid('param'); + const template = await templateService.getTemplate(id); - if (!template) { - return ctx.json({ error: 'Template not found' }, 404); - } + if (!template) { + return ctx.json({ error: 'Template not found' }, 404); + } - return ctx.json(template); - }, - ) - // PATCH /templates/:id - Update a template - .patch( - '/:id', - describeRoute({ - description: 'Update a template', - responses: { - 200: { - description: 'Template updated successfully', - content: { - 'application/json': { - schema: resolver(TemplateSchema), - }, - }, - }, - 404: { - description: 'Template not found', - }, - }, - }), - zValidator( - 'param', - z.object({ - id: idString('template'), - }), - ), - zValidator('json', TemplateSchema.partial()), - async (ctx) => { - const templateService = new TemplateService(ctx); - const { id } = ctx.req.valid('param'); - const body = ctx.req.valid('json'); + return ctx.json(template); + } + ) + // PATCH /templates/:id - Update a template + .patch( + '/:id', + describeRoute({ + description: 'Update a template', + responses: { + 200: { + description: 'Template updated successfully', + content: { + 'application/json': { + schema: resolver(TemplateSchema), + }, + }, + }, + 404: { + description: 'Template not found', + }, + }, + }), + zValidator( + 'param', + z.object({ + id: idString('template'), + }) + ), + zValidator('json', TemplateSchema.partial()), + async (ctx) => { + const templateService = new TemplateService(ctx); + const { id } = ctx.req.valid('param'); + const body = ctx.req.valid('json'); - const result = await templateService.updateTemplate(id, body); - return ctx.json(result); - }, - ) - // DELETE /templates/:id - Delete a template - .delete( - '/:id', - describeRoute({ - description: 'Delete a template', - responses: { - 200: { - description: 'Template deleted successfully', - }, - }, - }), - zValidator( - 'param', - z.object({ - id: idString('template'), - }), - ), - async (ctx) => { - const templateService = new TemplateService(ctx); - const { id } = ctx.req.valid('param'); + const result = await templateService.updateTemplate(id, body); + return ctx.json(result); + } + ) + // DELETE /templates/:id - Delete a template + .delete( + '/:id', + describeRoute({ + description: 'Delete a template', + responses: { + 200: { + description: 'Template deleted successfully', + }, + }, + }), + zValidator( + 'param', + z.object({ + id: idString('template'), + }) + ), + async (ctx) => { + const templateService = new TemplateService(ctx); + const { id } = ctx.req.valid('param'); - await templateService.deleteTemplate(id); - return ctx.json(null, 200); - }, - ); + await templateService.deleteTemplate(id); + return ctx.json(null, 200); + } + ); diff --git a/apps/api/src/routes/webhook.routes.ts b/apps/api/src/routes/webhook.routes.ts index 75b370f..cff7e25 100644 --- a/apps/api/src/routes/webhook.routes.ts +++ b/apps/api/src/routes/webhook.routes.ts @@ -1,11 +1,11 @@ import { Hono } from 'hono'; -import { AppContext } from '@/index'; import { describeRoute } from 'hono-openapi'; import { validator as zValidator } from 'hono-openapi/zod'; +import Stripe from 'stripe'; import z from 'zod'; -import { StripeService } from '@/services/third-party/Stripe.service'; +import { AppContext } from '@/index'; import { BillingService } from '@/services/billing/Billing.service'; -import Stripe from 'stripe'; +import { StripeService } from '@/services/third-party/Stripe.service'; export const webhookRouter = new Hono().post( '/stripe', diff --git a/apps/api/src/schema/asset.zod.ts b/apps/api/src/schema/asset.zod.ts index 2b29e21..711ad44 100644 --- a/apps/api/src/schema/asset.zod.ts +++ b/apps/api/src/schema/asset.zod.ts @@ -2,12 +2,12 @@ import { idString } from '@coderscreen/common/id'; import { z } from 'zod'; export const AssetSchema = z.object({ - id: idString('asset'), - createdAt: z.string(), - organizationId: z.string(), - userId: z.string(), - url: z.string(), - type: z.string(), + id: idString('asset'), + createdAt: z.string(), + organizationId: z.string(), + userId: z.string(), + url: z.string(), + type: z.string(), }); export type AssetSchema = z.infer; diff --git a/apps/api/src/schema/room.zod.ts b/apps/api/src/schema/room.zod.ts index f04d5af..7daf3b3 100644 --- a/apps/api/src/schema/room.zod.ts +++ b/apps/api/src/schema/room.zod.ts @@ -1,26 +1,38 @@ -import { z } from 'zod'; import { idString } from '@coderscreen/common/id'; +import { z } from 'zod'; -export const RoomLanguageSchema = z.enum(['typescript', 'javascript', 'python', 'bash', 'rust', 'c++', 'c', 'java', 'go', 'php', 'ruby']); +export const RoomLanguageSchema = z.enum([ + 'typescript', + 'javascript', + 'python', + 'bash', + 'rust', + 'c++', + 'c', + 'java', + 'go', + 'php', + 'ruby', +]); export const RoomSchema = z.object({ - id: idString('room'), - createdAt: z.string().datetime(), - updatedAt: z.string().datetime(), - title: z.string(), - language: RoomLanguageSchema, - status: z.enum(['active', 'scheduled', 'completed', 'archived']), - notes: z.string(), + id: idString('room'), + createdAt: z.string().datetime(), + updatedAt: z.string().datetime(), + title: z.string(), + language: RoomLanguageSchema, + status: z.enum(['active', 'scheduled', 'completed', 'archived']), + notes: z.string(), }); // Public room schema is strict and only includes the fields that are safe to expose export const PublicRoomSchema = RoomSchema.omit({ - notes: true, + notes: true, }) - .extend({ - organizationId: z.string(), - }) - .strict(); + .extend({ + organizationId: z.string(), + }) + .strict(); export type RoomSchema = z.infer; export type PublicRoomSchema = z.infer; diff --git a/apps/api/src/schema/sandbox.zod.ts b/apps/api/src/schema/sandbox.zod.ts index fb8de4c..7029e4d 100644 --- a/apps/api/src/schema/sandbox.zod.ts +++ b/apps/api/src/schema/sandbox.zod.ts @@ -1,10 +1,10 @@ import { z } from 'zod'; export const ExecOutputSchema = z.object({ - success: z.boolean(), - timestamp: z.string(), - stdout: z.string(), - stderr: z.string(), - exitCode: z.number(), - elapsedTime: z.number(), + success: z.boolean(), + timestamp: z.string(), + stdout: z.string(), + stderr: z.string(), + exitCode: z.number(), + elapsedTime: z.number(), }); diff --git a/apps/api/src/schema/template.zod.ts b/apps/api/src/schema/template.zod.ts index f1e10a9..492ae05 100644 --- a/apps/api/src/schema/template.zod.ts +++ b/apps/api/src/schema/template.zod.ts @@ -1,14 +1,14 @@ -import { z } from 'zod'; import { idString } from '@coderscreen/common/id'; +import { z } from 'zod'; export const TemplateSchema = z.object({ - id: idString('template'), - createdAt: z.string().datetime(), - updatedAt: z.string().datetime(), - title: z.string(), - code: z.string(), - language: z.enum(['typescript', 'javascript', 'python', 'rust', 'c++']), - instructions: z.record(z.any()), + id: idString('template'), + createdAt: z.string().datetime(), + updatedAt: z.string().datetime(), + title: z.string(), + code: z.string(), + language: z.enum(['typescript', 'javascript', 'python', 'rust', 'c++']), + instructions: z.record(z.any()), }); export type TemplateSchema = z.infer; diff --git a/apps/api/src/services/AppFactory.ts b/apps/api/src/services/AppFactory.ts index 071c930..0d956b6 100644 --- a/apps/api/src/services/AppFactory.ts +++ b/apps/api/src/services/AppFactory.ts @@ -1,9 +1,9 @@ import { Context } from 'hono'; -import { AppContext } from '..'; -import { RoomService } from './Room.service'; import { createMiddleware } from 'hono/factory'; -import { CodeRunService } from './CodeRun.service'; +import { AppContext } from '..'; import { AssetService } from './Asset.service'; +import { CodeRunService } from './CodeRun.service'; +import { RoomService } from './Room.service'; export interface AppFactory { roomService: RoomService; diff --git a/apps/api/src/services/Asset.service.ts b/apps/api/src/services/Asset.service.ts index 9d81303..949b5c5 100644 --- a/apps/api/src/services/Asset.service.ts +++ b/apps/api/src/services/Asset.service.ts @@ -1,10 +1,10 @@ -import { AppContext } from '@/index'; +import { generateId } from '@coderscreen/common/id'; import { AssetEntity, assetTable } from '@coderscreen/db/asset.db'; -import { useDb } from '@/db/client'; +import { eq } from 'drizzle-orm'; import { Context } from 'hono'; +import { useDb } from '@/db/client'; +import { AppContext } from '@/index'; import { getSession } from '@/lib/session'; -import { generateId } from '@coderscreen/common/id'; -import { eq } from 'drizzle-orm'; export class AssetService { constructor(private readonly ctx: Context) {} diff --git a/apps/api/src/services/CodeRun.service.ts b/apps/api/src/services/CodeRun.service.ts index e59515d..c67aa13 100644 --- a/apps/api/src/services/CodeRun.service.ts +++ b/apps/api/src/services/CodeRun.service.ts @@ -1,40 +1,44 @@ -import { AppContext } from '..'; import { Id } from '@coderscreen/common/id'; -import { Context } from 'hono'; import { RoomEntity } from '@coderscreen/db/room.db'; -import { formatExecOutput, FormattedOutput, getSandboxId } from '@/lib/sandbox'; +import { Context } from 'hono'; +import { FormattedOutput, formatExecOutput, getSandboxId } from '@/lib/sandbox'; +import { AppContext } from '..'; export class CodeRunService { - private ctx: Context; - - constructor(ctx: Context) { - this.ctx = ctx; - } - - async runCode(params: { roomId: Id<'room'>; code: string; language: RoomEntity['language'] }): Promise { - const { roomId, code, language } = params; - - // Get the durable object to broadcast execution status - // const id = this.ctx.env.ROOM_DO.idFromName(roomId); - // const roomDo = this.ctx.env.ROOM_DO.get(id); - - // this.ctx.executionCtx.waitUntil(roomDo.handleCodeExecutioMessage({ type: 'start' })); - - const sandbox = await this.getSandbox(roomId, language); - const raw = await sandbox.runCode({ language, code }); - const result = formatExecOutput(raw); - - // // Broadcast execution complete - // this.ctx.executionCtx.waitUntil( - // roomDo.handleCodeExecutioMessage({ type: 'complete', output: result?.stdout || result?.stderr || 'No output from execution' }), - // ); - - return result; - } - - private async getSandbox(roomId: Id<'room'>, language: RoomEntity['language']) { - const sandboxId = getSandboxId(roomId, language); - const sandbox = this.ctx.env.SANDBOX.get(this.ctx.env.SANDBOX.idFromName(sandboxId)); - return sandbox; - } + private ctx: Context; + + constructor(ctx: Context) { + this.ctx = ctx; + } + + async runCode(params: { + roomId: Id<'room'>; + code: string; + language: RoomEntity['language']; + }): Promise { + const { roomId, code, language } = params; + + // Get the durable object to broadcast execution status + // const id = this.ctx.env.ROOM_DO.idFromName(roomId); + // const roomDo = this.ctx.env.ROOM_DO.get(id); + + // this.ctx.executionCtx.waitUntil(roomDo.handleCodeExecutioMessage({ type: 'start' })); + + const sandbox = await this.getSandbox(roomId); + const raw = await sandbox.runCode({ language, code }); + const result = formatExecOutput(raw); + + // // Broadcast execution complete + // this.ctx.executionCtx.waitUntil( + // roomDo.handleCodeExecutioMessage({ type: 'complete', output: result?.stdout || result?.stderr || 'No output from execution' }), + // ); + + return result; + } + + private async getSandbox(roomId: Id<'room'>) { + const sandboxId = getSandboxId(roomId); + const sandbox = this.ctx.env.SANDBOX.get(this.ctx.env.SANDBOX.idFromName(sandboxId)); + return sandbox; + } } diff --git a/apps/api/src/services/Room.service.ts b/apps/api/src/services/Room.service.ts index 3a30af5..158795c 100644 --- a/apps/api/src/services/Room.service.ts +++ b/apps/api/src/services/Room.service.ts @@ -1,17 +1,15 @@ +import { generateId, Id } from '@coderscreen/common/id'; import { RoomEntity, roomTable } from '@coderscreen/db/room.db'; -import { useDb } from '@/db/client'; +import { and, desc, eq } from 'drizzle-orm'; +import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; import { Context } from 'hono'; +import { HTTPException } from 'hono/http-exception'; +import { useDb } from '@/db/client'; import { AppContext } from '@/index'; -import { PublicRoomSchema } from '@/schema/room.zod'; -import { generateId, Id } from '@coderscreen/common/id'; - -import { eq, desc, and } from 'drizzle-orm'; -import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; import { getSession } from '@/lib/session'; -import { TemplateEntity } from '@coderscreen/db/template.db'; import { ChatMessage, User } from '@/partykit/internal/AI.service'; +import { PublicRoomSchema } from '@/schema/room.zod'; import { UsageService } from '@/services/billing/Usage.service'; -import { HTTPException } from 'hono/http-exception'; export class RoomService { private readonly db: PostgresJsDatabase; @@ -150,13 +148,11 @@ export class RoomService { await roomStub.handleStatusUpdate(status); } - async loadTemplate(params: { room: RoomEntity; template: TemplateEntity }) { - const { room, template } = params; - + async loadTemplate() { + // const { room, template } = params; // // Get the durable object to load new information // const id = this.ctx.env.ROOM_DO.idFromName(room.id); // const roomDo = this.ctx.env.ROOM_DO.get(id); - // roomDo.handleLoadTemplate(template); } diff --git a/apps/api/src/services/Template.service.ts b/apps/api/src/services/Template.service.ts index 8036881..35c62ab 100644 --- a/apps/api/src/services/Template.service.ts +++ b/apps/api/src/services/Template.service.ts @@ -1,67 +1,69 @@ -import { useDb } from '@/db/client'; -import { AppContext } from '@/index'; +import { generateId, Id } from '@coderscreen/common/id'; +import { TemplateEntity, templateTable } from '@coderscreen/db/template.db'; +import { and, eq } from 'drizzle-orm'; import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; import { Context } from 'hono'; -import { TemplateEntity, templateTable } from '@coderscreen/db/template.db'; +import { useDb } from '@/db/client'; +import { AppContext } from '@/index'; import { getSession } from '@/lib/session'; -import { generateId, Id } from '@coderscreen/common/id'; -import { and, eq } from 'drizzle-orm'; export class TemplateService { - private readonly db: PostgresJsDatabase; + private readonly db: PostgresJsDatabase; - constructor(private readonly ctx: Context) { - this.db = useDb(ctx); - } + constructor(private readonly ctx: Context) { + this.db = useDb(ctx); + } - async createTemplate(values: Omit) { - const { user, orgId } = getSession(this.ctx); + async createTemplate( + values: Omit + ) { + const { user, orgId } = getSession(this.ctx); - return this.db - .insert(templateTable) - .values({ - id: generateId('template'), - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - organizationId: orgId, - userId: user.id, - ...values, - }) - .returning() - .then((t) => t[0]); - } + return this.db + .insert(templateTable) + .values({ + id: generateId('template'), + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + organizationId: orgId, + userId: user.id, + ...values, + }) + .returning() + .then((t) => t[0]); + } - async getTemplate(id: Id<'template'>) { - const { orgId } = getSession(this.ctx); - return this.db - .select() - .from(templateTable) - .where(and(eq(templateTable.id, id), eq(templateTable.organizationId, orgId))) - .then((t) => t[0]); - } + async getTemplate(id: Id<'template'>) { + const { orgId } = getSession(this.ctx); + return this.db + .select() + .from(templateTable) + .where(and(eq(templateTable.id, id), eq(templateTable.organizationId, orgId))) + .then((t) => t[0]); + } - async listTemplates() { - const { orgId } = getSession(this.ctx); - return this.db.select().from(templateTable).where(eq(templateTable.organizationId, orgId)); - } + async listTemplates() { + const { orgId } = getSession(this.ctx); + return this.db.select().from(templateTable).where(eq(templateTable.organizationId, orgId)); + } - async updateTemplate(id: Id<'template'>, values: Partial) { - const { orgId } = getSession(this.ctx); + async updateTemplate(id: Id<'template'>, values: Partial) { + const { orgId } = getSession(this.ctx); - return this.db - .update(templateTable) - .set(values) - .where(and(eq(templateTable.id, id), eq(templateTable.organizationId, orgId))) - .returning() - .then((t) => t[0]); - } + return this.db + .update(templateTable) + .set(values) + .where(and(eq(templateTable.id, id), eq(templateTable.organizationId, orgId))) + .returning() + .then((t) => t[0]); + } - async deleteTemplate(id: Id<'template'>) { - const { orgId } = getSession(this.ctx); - return this.db - .delete(templateTable) - .where(and(eq(templateTable.id, id), eq(templateTable.organizationId, orgId))) - .returning() - .then((t) => t[0]); - } + async deleteTemplate(id: Id<'template'>) { + const { orgId } = getSession(this.ctx); + return this.db + .delete(templateTable) + .where(and(eq(templateTable.id, id), eq(templateTable.organizationId, orgId))) + .returning() + .then((t) => t[0]); + } } diff --git a/apps/api/src/services/billing/Billing.service.ts b/apps/api/src/services/billing/Billing.service.ts index fb74143..c8d0e13 100644 --- a/apps/api/src/services/billing/Billing.service.ts +++ b/apps/api/src/services/billing/Billing.service.ts @@ -1,6 +1,4 @@ -import { Context } from 'hono'; -import { AppContext } from '@/index'; -import { useDb } from '@/db/client'; +import { generateId, Id } from '@coderscreen/common/id'; import { customerTable, PlanEntity, @@ -8,13 +6,15 @@ import { SubscriptionEntity, subscriptionTable, } from '@coderscreen/db/billing.db'; -import { eq, and } from 'drizzle-orm'; -import { generateId, Id } from '@coderscreen/common/id'; +import { and, eq } from 'drizzle-orm'; +import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; +import { Context } from 'hono'; import { Stripe } from 'stripe'; -import { StripeService } from '@/services/third-party/Stripe.service'; +import { useDb } from '@/db/client'; +import { AppContext } from '@/index'; import { getBilling } from '@/lib/session'; +import { StripeService } from '@/services/third-party/Stripe.service'; import { UsageService } from './Usage.service'; -import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; export class BillingService { private stripeService: StripeService; diff --git a/apps/api/src/services/billing/Usage.service.ts b/apps/api/src/services/billing/Usage.service.ts index efef730..b8c07ab 100644 --- a/apps/api/src/services/billing/Usage.service.ts +++ b/apps/api/src/services/billing/Usage.service.ts @@ -1,19 +1,19 @@ -import { eq, and, sql, count } from 'drizzle-orm'; import { generateId } from '@coderscreen/common/id'; -import { useDb } from '@/db/client'; -import { Context } from 'hono'; -import { AppContext } from '@/index'; -import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; +import { PlanEntity, SubscriptionEntity } from '@coderscreen/db/billing.db'; import { - eventLogTable, EventLogEntity, EventType, - eventUsageTable, EventUsageEntity, + eventLogTable, + eventUsageTable, } from '@coderscreen/db/usage.db'; -import { getBilling, getSession } from '@/lib/session'; import { member } from '@coderscreen/db/user.db'; -import { PlanEntity, SubscriptionEntity } from '@coderscreen/db/billing.db'; +import { and, count, eq, sql } from 'drizzle-orm'; +import { PostgresJsDatabase } from 'drizzle-orm/postgres-js'; +import { Context } from 'hono'; +import { useDb } from '@/db/client'; +import { AppContext } from '@/index'; +import { getBilling, getSession } from '@/lib/session'; /** * Simplified Usage Tracking Service @@ -50,7 +50,7 @@ export interface TrackEventParams { type?: string; }; amount?: number; - metadata?: Record; + metadata?: Record; } export interface UsageResult { @@ -137,9 +137,7 @@ export class UsageService { try { result[eventType] = await this.getOrCreateUsage(eventType); } catch (err) { - // Optionally log error, fallback to default - // console.error(`Failed to get usage for ${eventType}:`, err); - // Leave the fallback value as is + console.error(`Failed to get usage for ${eventType}:`, err); } }) ); @@ -256,7 +254,7 @@ export class UsageService { private async getCustomUsage(eventType: CustomUsageType): Promise { const { plan: currentPlan } = await getBilling(this.ctx); switch (eventType) { - case 'team_members': + case 'team_members': { const { orgId } = getSession(this.ctx); const memberCount = await this.db .select({ @@ -266,7 +264,7 @@ export class UsageService { .where(eq(member.organizationId, orgId)) .then((res) => res[0]); - const limit = currentPlan.limits['team_members']; + const limit = currentPlan.limits.team_members; return { eventType: 'team_members', @@ -274,6 +272,7 @@ export class UsageService { limit, exceeded: memberCount.count >= limit, }; + } default: throw new Error(`Unknown custom usage type: ${eventType}`); } diff --git a/apps/api/src/services/third-party/Loops.service.ts b/apps/api/src/services/third-party/Loops.service.ts index 1ab7062..3b33b40 100644 --- a/apps/api/src/services/third-party/Loops.service.ts +++ b/apps/api/src/services/third-party/Loops.service.ts @@ -1,6 +1,6 @@ -import { AppContext } from '@/index'; import { Context } from 'hono'; import { LoopsClient } from 'loops'; +import { AppContext } from '@/index'; type TransactionalEmailTypes = 'verification_code' | 'org_invitation'; type TransactionEmailParams = { @@ -44,10 +44,9 @@ export class LoopsService { type: T, email: string, params: TransactionEmailPayload - ): Promise { - //@ts-expect-error - this is a hack to get the environment variable + ): Promise { if (this.ctx.env.NODE_ENV !== 'development') { - return this.client.sendTransactionalEmail({ + await this.client.sendTransactionalEmail({ transactionalId: TRANSACTIONAL_EMAIL_IDS[type], email, dataVariables: params, diff --git a/apps/api/src/services/third-party/Stripe.service.ts b/apps/api/src/services/third-party/Stripe.service.ts index 9e3f7da..2b05873 100644 --- a/apps/api/src/services/third-party/Stripe.service.ts +++ b/apps/api/src/services/third-party/Stripe.service.ts @@ -1,20 +1,25 @@ -import { AppContext } from '@/index'; import { SubscriptionEntity } from '@coderscreen/db/billing.db'; import { Context } from 'hono'; import { Stripe } from 'stripe'; +import { AppContext } from '@/index'; -const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY!; +const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY; if (!STRIPE_SECRET_KEY) { throw new Error('STRIPE_SECRET_KEY is not set'); } +const STRIPE_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET; +if (!STRIPE_WEBHOOK_SECRET) { + throw new Error('STRIPE_WEBHOOK_SECRET is not set'); +} + /** * Wraps Stripe API */ export class StripeService { private stripe: Stripe; - constructor(private readonly ctx: Context) { + constructor(readonly ctx: Context) { this.stripe = new Stripe(STRIPE_SECRET_KEY); } @@ -76,13 +81,8 @@ export class StripeService { async constructEvent(params: { payload: string; signature: string }) { const { payload, signature } = params; - const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!; - - if (!webhookSecret) { - throw new Error('STRIPE_WEBHOOK_SECRET is not set'); - } - return this.stripe.webhooks.constructEventAsync(payload, signature, webhookSecret); + return this.stripe.webhooks.constructEventAsync(payload, signature, STRIPE_WEBHOOK_SECRET); } async getLineItems(params: { sessionId: string; ctx: Context }) { diff --git a/apps/api/worker-configuration.d.ts b/apps/api/worker-configuration.d.ts new file mode 100644 index 0000000..b0aa21f --- /dev/null +++ b/apps/api/worker-configuration.d.ts @@ -0,0 +1,7359 @@ +/* eslint-disable */ +// Generated by Wrangler by running `wrangler types` (hash: f871f0bb7812599a823fbf1908f4876c) +// Runtime types generated with workerd@1.20250617.0 2025-06-01 nodejs_compat,nodejs_compat_populate_process_env +declare namespace Cloudflare { + interface Env { + ASSETS_URL: "https://assets.coderscreen.com"; + NODE_ENV: string; + FE_APP_URL: string; + BETTER_AUTH_URL: string; + FREE_PLAN_ID: string; + STRIPE_PUBLISHABLE_KEY: string; + STRIPE_SECRET_KEY: string; + STRIPE_WEBHOOK_SECRET: string; + DATABASE_URL: string; + LOOPS_API_KEY: string; + OPENROUTER_API_KEY: string; + BETTER_AUTH_SECRET: string; + GOOGLE_CLIENT_ID: string; + GOOGLE_CLIENT_SECRET: string; + GITHUB_CLIENT_ID: string; + GITHUB_CLIENT_SECRET: string; + SANDBOX: DurableObjectNamespace; + Room: DurableObjectNamespace; + PrivateRoom: DurableObjectNamespace; + WHITEBOARD_DO: DurableObjectNamespace; + ASSETS_BUCKET: R2Bucket; + WHITEBOARD_ASSETS_BUCKET: R2Bucket; + } +} +interface Env extends Cloudflare.Env {} +type StringifyValues> = { + [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; +}; +declare namespace NodeJS { + interface ProcessEnv extends StringifyValues> {} +} + +// 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; +/** + * An abnormal event (called an exception) which 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); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @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; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /* [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; +} +/** + * This ServiceWorker API interface 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; + 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; +/** + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * + * [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; + props: any; +} +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | 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; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +interface StructuredSerializeOptions { + transfer?: any[]; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */ +declare abstract class PromiseRejectionEvent extends Event { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +declare abstract class Navigator { + sendBeacon(url: string, body?: (ReadableStream | string | (ArrayBuffer | ArrayBufferView) | Blob | FormData | URLSearchParams | URLSearchParams)): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; + readonly language: string; + readonly languages: string[]; +} +/** +* 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/) +*/ +interface Performance { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ + readonly timeOrigin: number; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ + now(): number; +} +interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +interface Cloudflare { + readonly compatibilityFlags: Record; +} +interface DurableObject { + fetch(request: Request): Response | 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; +} +interface DurableObjectNamespace { + newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get(id: DurableObjectId, 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"; +interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + container?: Container; + 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; + 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 AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +/** + * An event which takes place in the DOM. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) + */ +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * Returns the object to which event is dispatched (its target). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) + */ + get target(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [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; +/** + * EventTarget is a DOM interface 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(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; + /** + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * + * [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; +} +/** + * A controller object that allows you to abort one or more DOM requests as and when desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) + */ +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get signal(): AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +/** + * A signal object that allows you to communicate with a DOM request (such as a Fetch) 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 { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) */ + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /* [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); + /* [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; +} +/** + * Extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) + */ +declare abstract class ExtendableEvent extends Event { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +/** + * A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) + */ +declare class Blob { + constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +interface BlobOptions { + type?: string; +} +/** + * 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); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /* [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 { + /* [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 { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +/** + * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) + */ +declare abstract class SubtleCrypto { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) */ + encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) */ + decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) */ + sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) */ + verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) */ + digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /* [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; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) */ + deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; + /* [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; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) */ + exportKey(format: string, key: CryptoKey): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) */ + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; + /* [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 dictionary of the Web Crypto API represents a cryptographic key. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) + */ +declare abstract class CryptoKey { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; + /* [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; +} +/** + * A decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) + */ +declare class TextDecoder { + constructor(label?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [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; +} +/** + * TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) + */ +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto(input: string, buffer: ArrayBuffer | ArrayBufferView): TextEncoderEncodeIntoResult; + get encoding(): string; +} +interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +interface TextDecoderDecodeOptions { + stream: boolean; +} +interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +/** + * 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); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /* [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; +} +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) + */ +declare class FormData { + constructor(); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ + append(name: string, value: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ + append(name: string, value: Blob, filename?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) */ + delete(name: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) */ + get(name: string): (File | string) | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) */ + getAll(name: string): (File | string)[]; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ + has(name: string): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ + set(name: string, value: string): void; + /* [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 service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) + */ +declare abstract class FetchEvent extends ExtendableEvent { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +type HeadersInit = Headers | Iterable> | Record; +/** + * This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) + */ +declare class Headers { + constructor(init?: HeadersInit); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */ + get(name: string): string | null; + getAll(name: string): string[]; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */ + getSetCookie(): string[]; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) */ + has(name: string): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */ + set(name: string, value: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */ + append(name: string, value: string): void; + /* [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; +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; +} +/** + * This Fetch API interface 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; +}; +/** + * This Fetch API interface represents the response to a request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) + */ +interface Response extends Body { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + status: number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + statusText: string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + headers: Headers; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + ok: boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + redirected: boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + url: string; + webSocket: WebSocket | null; + cf: any | undefined; + /* [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; +/** + * This Fetch API interface 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; +}; +/** + * This Fetch API interface represents a resource request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) + */ +interface Request> extends Body { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + method: string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + url: string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + redirect: string; + fetcher: Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + signal: AbortSignal; + cf: Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + integrity: string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + keepalive: boolean; + /** + * Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) + */ + cache?: "no-store"; +} +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"; + /* 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 = 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 { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; +} +interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +interface QueueSendBatchOptions { + delaySeconds?: number; +} +interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +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; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + 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")[]; +} +declare abstract class 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 { + /** + * 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; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +type ReadableStreamReadResult = { + done: false; + value: R; +} | { + done: true; + value?: undefined; +}; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +interface ReadableStream { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ + ReadableStream, + ReadableStream + ]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; +} +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare const ReadableStream: { + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; +}; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read(view: T): Promise>; + /* [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"; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +declare abstract class ReadableStreamBYOBRequest { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +declare abstract class ReadableStreamDefaultController { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +declare abstract class ReadableByteStreamController { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare abstract class WritableStreamDefaultController { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare abstract class TransformStreamDefaultController { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +interface ReadableWritablePair { + /** + * 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; + readable: ReadableStream; +} +/** + * This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) + */ +declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +/** + * This Streams API interface 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); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ +declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /* [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; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ +declare class CompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ +declare class DecompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) */ +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +/* [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; +} +/** + * This Streams API interface 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); + /* [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; +} +/** + * This Streams API interface provides a built-in byte length 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); + /* [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 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 | 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 outcome: string; + readonly executionModel: string; + readonly truncated: boolean; + readonly cpuTime: number; + readonly wallTime: number; +} +interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +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 represents an object providing static methods used for creating object URLs. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) + */ +declare class URL { + constructor(url: string | URL, base?: string | URL); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + /*function toString() { [native code] }*/ + toString(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) */ + static parse(url: string, base?: string): URL | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) */ + static createObjectURL(object: File | Blob): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) */ + static revokeObjectURL(object_url: string): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */ +declare class URLSearchParams { + constructor(init?: (Iterable> | Record | string)); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) */ + get size(): number; + /** + * 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; + /** + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) + */ + delete(name: string, value?: string): void; + /** + * 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; + /** + * Returns all the values association with a given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) + */ + getAll(name: string): string[]; + /** + * Returns a Boolean indicating if such a search parameter exists. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) + */ + has(name: string, value?: string): boolean; + /** + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) + */ + set(name: string, value: string): void; + /* [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] } Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ + 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. This is delivered to the listener indicated by the WebSocket object's onclose attribute. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) + */ +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +/** + * 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); + /** + * Returns the data of the message. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: ArrayBuffer | string; +} +interface MessageEventInit { + data: ArrayBuffer | string; +} +type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +/** + * 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; +}; +/** + * 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(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readyState: number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + url: string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + protocol: string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + extensions: string | null; +} +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; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ +declare class EventSource extends EventTarget { + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * Returns the URL providing the event stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * Returns the state of this EventSource object's connection. It can have the values described below. + * + * [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; +} +interface ContainerStartupOptions { + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; +} +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 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 AiTextGenerationOutput = { + response?: string; + tool_calls?: { + name: string; + arguments: unknown; + }[]; +}; +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; +} +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"; +} | AsyncResponse; +interface 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; +} | AsyncResponse; +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"; +} | AsyncResponse; +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"; +} | AsyncResponse; +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 { + /** + * Base64 encoded value of the audio data. + */ + audio: 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 it appended the the beginning of the output of the transcription and can guide the transcription result. + */ + prefix?: string; +} +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 = BGEM3InputQueryAndContexts | BGEM3InputEmbedding | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[]; +}; +interface BGEM3InputQueryAndContexts { + /** + * 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 BGEM3InputEmbedding { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface BGEM3InputQueryAndContexts1 { + /** + * 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 BGEM3InputEmbedding1 { + 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 = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding | AsyncResponse; +interface BGEM3OuputQuery { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +interface BGEM3OutputEmbeddingForContexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface BGEM3OuputEmbedding { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +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 = Prompt | Messages; +interface 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 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; + }; + }; + }[]; + 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 = Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | AsyncBatch; +interface 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?: JSONMode; + /** + * 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 JSONMode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface 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; + /** + * 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?: JSONMode; + /** + * 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 AsyncBatch { + 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?: JSONMode; + }[]; +} +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; + }[]; +} | AsyncResponse; +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. + */ + query: string; + /** + * 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 = Qwen2_5_Coder_32B_Instruct_Prompt | Qwen2_5_Coder_32B_Instruct_Messages; +interface 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?: JSONMode; + /** + * 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 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?: JSONMode; + /** + * 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_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 = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages; +interface 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 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. 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_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 = Mistral_Small_3_1_24B_Instruct_Prompt | Mistral_Small_3_1_24B_Instruct_Messages; +interface 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 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 = Google_Gemma_3_12B_It_Prompt | Google_Gemma_3_12B_It_Messages; +interface 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 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; + }; + }[] | { + /** + * 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_Prompt | Ai_Cf_Meta_Llama_4_Messages; +interface Ai_Cf_Meta_Llama_4_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?: JSONMode; + /** + * 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_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?: JSONMode; + /** + * 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; +} +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/microsoft/resnet-50": BaseAiImageClassification; + "@cf/facebook/detr-resnet-50": BaseAiObjectDetection; + "@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/llamaguard-7b-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; + "@hf/meta-llama/meta-llama-3-8b-instruct": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct": 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/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; +} +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; + gateway?: GatewayOptions; + returnRawResponse?: boolean; + prefix?: string; + extraHeaders?: object; +}; +type ConversionResponse = { + name: string; + mimeType: string; + format: "markdown"; + tokens: number; + data: string; +}; +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; + }[]; +}; +interface InferenceUpstreamError extends Error { +} +interface AiInternalError extends Error { +} +type AiModelListType = Record; +declare abstract class Ai { + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + autorag(autoragId: string): AutoRAG; + run(model: Name, inputs: InputOptions, options?: Options): Promise; + models(params?: AiModelsSearchParams): Promise; + toMarkdown(files: { + name: string; + blob: Blob; + }[], options?: { + gateway?: GatewayOptions; + extraHeaders?: object; + }): Promise; + toMarkdown(files: { + name: string; + blob: Blob; + }, options?: { + gateway?: GatewayOptions; + extraHeaders?: object; + }): 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 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?: GatewayOptions; + extraHeaders?: object; + }): Promise; + getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line +} +interface AutoRAGInternalError extends Error { +} +interface AutoRAGNotFoundError extends Error { +} +interface AutoRAGUnauthorizedError extends Error { +} +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[]; +}; +type AutoRagSearchRequest = { + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + rewrite_query?: boolean; +}; +type AutoRagAiSearchRequest = AutoRagSearchRequest & { + stream?: boolean; +}; +type AutoRagAiSearchRequestStreaming = Omit & { + stream: true; +}; +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; +}; +type AutoRagListResponse = { + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; +}[]; +type AutoRagAiSearchResponse = AutoRagSearchResponse & { + response: string; +}; +declare abstract class AutoRAG { + list(): Promise; + search(params: AutoRagSearchRequest): Promise; + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + aiSearch(params: AutoRagAiSearchRequest): Promise; + 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"; + /** + * 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?: '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; + 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; + /** + * 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; + }; +} +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 { +} +/** + * 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 binding that allows a Worker to send email messages. + */ +interface SendEmail { + send(message: EmailMessage): 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 }; +} +interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential 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; + gravity?: '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 ImageOutputOptions = { + format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; + quality?: number; + background?: string; +}; +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): Promise; + /** + * Begin applying a series of transformations to an image + * @param stream The image bytes + * @returns A transform handle + */ + input(stream: ReadableStream): ImageTransformer; +} +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; +} +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(): ReadableStream; +} +interface ImagesError extends Error { + readonly code: number; + readonly message: string; + readonly stack?: string; +} +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 recieves 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 & { + [K in Exclude>]: MethodOrProperty; + }; +} +declare namespace Cloudflare { + interface Env { + } +} +declare module 'cloudflare:workers' { + 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); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): 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); + fetch?(request: Request): Response | 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; + } + 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 abstract class WorkflowStep { + do>(name: string, callback: () => Promise): Promise; + do>(name: string, config: WorkflowStepConfig, callback: () => 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 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 const env: Cloudflare.Env; +} +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 }; +} +declare namespace TailStream { + interface Header { + readonly name: string; + readonly value: string; + } + interface FetchEventInfo { + readonly type: "fetch"; + readonly method: string; + readonly url: string; + readonly cfJson: string; + readonly headers: Header[]; + } + interface JsRpcEventInfo { + readonly type: "jsrpc"; + readonly methodName: string; + } + 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 Resume { + readonly type: "resume"; + readonly attachment?: any; + } + interface CustomEventInfo { + readonly type: "custom"; + } + interface FetchResponseInfo { + readonly type: "fetch"; + readonly statusCode: number; + } + type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound"; + interface ScriptVersion { + readonly id: string; + readonly tag?: string; + readonly message?: string; + } + interface Trigger { + readonly traceId: string; + readonly invocationId: string; + readonly spanId: string; + } + interface Onset { + readonly type: "onset"; + readonly dispatchNamespace?: string; + readonly entrypoint?: string; + readonly executionModel: string; + readonly scriptName?: string; + readonly scriptTags?: string[]; + readonly scriptVersion?: ScriptVersion; + readonly trigger?: Trigger; + readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | Resume | CustomEventInfo; + } + interface Outcome { + readonly type: "outcome"; + readonly outcome: EventOutcome; + readonly cpuTime: number; + readonly wallTime: number; + } + interface Hibernate { + readonly type: "hibernate"; + } + interface SpanOpen { + readonly type: "spanOpen"; + readonly name: 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: string; + } + interface Return { + readonly type: "return"; + readonly info?: FetchResponseInfo; + } + interface Link { + readonly type: "link"; + readonly label?: string; + readonly traceId: string; + readonly invocationId: string; + readonly spanId: string; + } + interface Attribute { + readonly name: string; + readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; + } + interface Attributes { + readonly type: "attributes"; + readonly info: Attribute[]; + } + interface TailEvent { + readonly traceId: string; + readonly invocationId: string; + readonly spanId: string; + readonly timestamp: Date; + readonly sequence: number; + readonly event: Onset | Outcome | Hibernate | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Link | Attributes; + } + type TailEventHandler = (event: TailEvent) => void | Promise; + type TailEventHandlerName = "outcome" | "hibernate" | "spanOpen" | "spanClose" | "diagnosticChannel" | "exception" | "log" | "return" | "link" | "attributes"; + type TailEventHandlerObject = Record; + 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"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +type VectorizeVectorMetadataFilter = { + [field: string]: Exclude | null | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; + }; +}; +/** + * 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?: string; + output?: object; +}; +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/apps/api/wrangler.example.jsonc b/apps/api/wrangler.example.jsonc deleted file mode 100644 index af995ea..0000000 --- a/apps/api/wrangler.example.jsonc +++ /dev/null @@ -1,85 +0,0 @@ -{ - "$schema": "node_modules/wrangler/config-schema.json", - "name": "coderscreen-api", - "compatibility_date": "2025-06-01", - "main": "./src/index.ts", - "compatibility_flags": ["nodejs_compat", "nodejs_compat_populate_process_env"], - "observability": { - "enabled": true - }, - "dev": { - "port": 8000 - }, - "upload_source_maps": true, - "vars": { - "NODE_ENV": "production", // production or development - "FE_APP_URL": "", // url of web app - "FREE_PLAN_ID": "", // id of free plan (billing.db.ts) - "BETTER_AUTH_URL": "", // web app url + /auth - "STRIPE_PUBLISHABLE_KEY": "", // stripe publishable key - "STRIPE_SECRET_KEY": "", // stripe secret key - "STRIPE_WEBHOOK_SECRET": "", // stripe webhook secret - - // Constant Vars - "DATABASE_URL": "", // database url - "LOOPS_API_KEY": "", // loops api key - "OPENROUTER_API_KEY": "", // openrouter api key - "ASSETS_URL": "", // public url of r2 bucket - "BETTER_AUTH_SECRET": "", // better auth secret - "GOOGLE_CLIENT_ID": "", // google client id - "GOOGLE_CLIENT_SECRET": "", // google client secret - "GITHUB_CLIENT_ID": "", // github client id - "GITHUB_CLIENT_SECRET": "" // github client secret - }, - "containers": [ - { - "max_instances": 10, - "name": "sandbox", - "class_name": "Sandbox", - "image": "registry.cloudflare.com/f05272c4cd62dae246414c758986da79/sandbox-image:production", - // registry.cloudflare.com/f05272c4cd62dae246414c758986da79/sandbox-image:latest - "instance_type": "standard" - } - ], - "durable_objects": { - "bindings": [ - { - "name": "SANDBOX", - "class_name": "Sandbox" - }, - { - "name": "Room", - "class_name": "PartyServer" - }, - { - "name": "PrivateRoom", - "class_name": "PrivateRoomServer" - }, - { - "name": "WHITEBOARD_DO", - "class_name": "WhiteboardDurableObject" - } - ] - }, - "migrations": [ - { - "tag": "v1", - "new_sqlite_classes": [ - "Sandbox", - "PartyServer", - "PrivateRoomServer", - "WhiteboardDurableObject" - ] - } - ], - "r2_buckets": [ - { - "binding": "ASSETS_BUCKET", - "bucket_name": "coderscreen-assets" - }, - { - "binding": "WHITEBOARD_ASSETS_BUCKET", - "bucket_name": "coderscreen-whiteboard" - } - ] -} diff --git a/apps/api/wrangler.jsonc b/apps/api/wrangler.jsonc new file mode 100644 index 0000000..695e47c --- /dev/null +++ b/apps/api/wrangler.jsonc @@ -0,0 +1,81 @@ +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "coderscreen-api", + "compatibility_date": "2025-06-01", + "main": "./src/index.ts", + "compatibility_flags": [ + "nodejs_compat", + "nodejs_compat_populate_process_env", + ], + "observability": { + "enabled": true, + }, + "dev": { + "port": 8000, + }, + "upload_source_maps": true, + "routes": [ + { + "pattern": "api.coderscreen.com", + "custom_domain": true, + }, + ], + "vars": { + "NODE_ENV": "production", + "FE_APP_URL": "https://app.coderscreen.com", + "FREE_PLAN_ID": "free", + "BETTER_AUTH_URL": "https://api.coderscreen.com/auth", + "ASSETS_URL": "https://assets.coderscreen.com", + }, + "containers": [ + { + "max_instances": 10, + "name": "sandbox", + "class_name": "Sandbox", + "image": "registry.cloudflare.com/f05272c4cd62dae246414c758986da79/sandbox-image:production", + // registry.cloudflare.com/f05272c4cd62dae246414c758986da79/sandbox-image:latest + "instance_type": "standard", + }, + ], + "durable_objects": { + "bindings": [ + { + "name": "SANDBOX", + "class_name": "Sandbox", + }, + { + "name": "Room", + "class_name": "PartyServer", + }, + { + "name": "PrivateRoom", + "class_name": "PrivateRoomServer", + }, + { + "name": "WHITEBOARD_DO", + "class_name": "WhiteboardDurableObject", + }, + ], + }, + "migrations": [ + { + "tag": "v1", + "new_sqlite_classes": [ + "Sandbox", + "PartyServer", + "PrivateRoomServer", + "WhiteboardDurableObject", + ], + }, + ], + "r2_buckets": [ + { + "binding": "ASSETS_BUCKET", + "bucket_name": "coderscreen-assets", + }, + { + "binding": "WHITEBOARD_ASSETS_BUCKET", + "bucket_name": "coderscreen-whiteboard", + }, + ], +} diff --git a/apps/marketing/eslint.config.mjs b/apps/marketing/eslint.config.mjs deleted file mode 100644 index 2e5b8e6..0000000 --- a/apps/marketing/eslint.config.mjs +++ /dev/null @@ -1,16 +0,0 @@ -import { dirname } from 'path'; -import { fileURLToPath } from 'url'; -import { FlatCompat } from '@eslint/eslintrc'; - -// const __filename = fileURLToPath(import.meta.url); -// const __dirname = dirname(__filename); - -// const compat = new FlatCompat({ -// baseDirectory: __dirname, -// }); - -const eslintConfig = [ - // ...compat.extends("next/core-web-vitals", "next/typescript"), -]; - -export default eslintConfig; diff --git a/apps/marketing/package.json b/apps/marketing/package.json index 52a789a..1ab4536 100644 --- a/apps/marketing/package.json +++ b/apps/marketing/package.json @@ -6,7 +6,9 @@ "dev": "next dev", "build": "next build", "start": "next start", - "lint": "echo" + "lint": "biome check src", + "lint:fix": "biome check src --write", + "format": "biome format --write src" }, "dependencies": { "@coderscreen/ui": "workspace:^", diff --git a/apps/marketing/src/app/globals.css b/apps/marketing/src/app/globals.css index 12d8be5..dc319f0 100644 --- a/apps/marketing/src/app/globals.css +++ b/apps/marketing/src/app/globals.css @@ -1,5 +1,5 @@ -@import 'tailwindcss'; -@import '@coderscreen/ui/styles.css'; +@import "tailwindcss"; +@import "@coderscreen/ui/styles.css"; @source '../../node_modules/@coderscreen/ui'; diff --git a/apps/marketing/src/app/layout.tsx b/apps/marketing/src/app/layout.tsx index 8390584..f6f1aa9 100644 --- a/apps/marketing/src/app/layout.tsx +++ b/apps/marketing/src/app/layout.tsx @@ -1,7 +1,7 @@ import type { Metadata } from 'next'; import { Geist, Geist_Mono } from 'next/font/google'; -import { MarketingHeader } from '@/components/common/MarketingHeader'; import { MarketingFooter } from '@/components/common/MarketingFooter'; +import { MarketingHeader } from '@/components/common/MarketingHeader'; import './globals.css'; import Script from 'next/script'; diff --git a/apps/marketing/src/components/common/Logo.tsx b/apps/marketing/src/components/common/Logo.tsx index b1af221..17e6857 100644 --- a/apps/marketing/src/components/common/Logo.tsx +++ b/apps/marketing/src/components/common/Logo.tsx @@ -1,4 +1,4 @@ -const defaultColor = '#1860fb'; +// const defaultColor = '#1860fb'; export const Logo = ({ className }: { className?: string }) => { return ( @@ -8,6 +8,7 @@ export const Logo = ({ className }: { className?: string }) => { xmlns='http://www.w3.org/2000/svg' className={className} > + CoderScreen Logo { const scrollToSection = (sectionId: string) => { @@ -62,6 +62,7 @@ export const MarketingFooter: React.FC = () => { @@ -70,6 +71,7 @@ export const MarketingFooter: React.FC = () => { diff --git a/apps/marketing/src/components/common/MarketingHeader.tsx b/apps/marketing/src/components/common/MarketingHeader.tsx index af613b6..bc01511 100644 --- a/apps/marketing/src/components/common/MarketingHeader.tsx +++ b/apps/marketing/src/components/common/MarketingHeader.tsx @@ -1,11 +1,11 @@ 'use client'; -import { useState } from 'react'; import { Button } from '@coderscreen/ui/button'; -import { RiCloseLine, RiMenuLine, RiGithubLine } from '@remixicon/react'; +import { RiCloseLine, RiGithubLine, RiMenuLine } from '@remixicon/react'; +import Link from 'next/link'; +import { useState } from 'react'; import { Logo } from '@/components/common/Logo'; import { siteConfig } from '@/lib/siteConfig'; -import Link from 'next/link'; export const MarketingHeader = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); @@ -36,24 +36,28 @@ export const MarketingHeader = () => { @@ -96,30 +100,35 @@ export const MarketingHeader = () => { diff --git a/apps/marketing/src/components/landing/Conway.tsx b/apps/marketing/src/components/landing/Conway.tsx deleted file mode 100644 index 17b0be7..0000000 --- a/apps/marketing/src/components/landing/Conway.tsx +++ /dev/null @@ -1,199 +0,0 @@ -'use client'; - -import React, { useEffect, useRef } from 'react'; - -const ConwayBg: React.FC = () => { - const canvasRef = useRef(null); - - useEffect(() => { - const canvas = canvasRef.current; - if (!canvas) return; - - const ctx = canvas.getContext('2d'); - if (!ctx) return; - - // Set canvas size - const resizeCanvas = () => { - const rect = canvas.getBoundingClientRect(); - canvas.width = rect.width * window.devicePixelRatio; - canvas.height = rect.height * window.devicePixelRatio; - ctx.scale(window.devicePixelRatio, window.devicePixelRatio); - }; - - resizeCanvas(); - window.addEventListener('resize', resizeCanvas); - - // Game of Life parameters - const cellSize = 8; - const cols = Math.ceil(canvas.width / window.devicePixelRatio / cellSize); - const rows = Math.ceil(canvas.height / window.devicePixelRatio / cellSize); - - // Initialize grid - let grid: boolean[][] = []; - let nextGrid: boolean[][] = []; - - const initializeGrid = () => { - grid = []; - nextGrid = []; - for (let i = 0; i < rows; i++) { - grid[i] = []; - nextGrid[i] = []; - for (let j = 0; j < cols; j++) { - // Random initial state with lower density for subtlety - grid[i][j] = Math.random() < 0.15; - nextGrid[i][j] = false; - } - } - }; - - const countNeighbors = (row: number, col: number): number => { - let count = 0; - for (let i = -1; i <= 1; i++) { - for (let j = -1; j <= 1; j++) { - if (i === 0 && j === 0) continue; - const newRow = (row + i + rows) % rows; - const newCol = (col + j + cols) % cols; - if (grid[newRow][newCol]) count++; - } - } - return count; - }; - - const updateGrid = () => { - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const neighbors = countNeighbors(i, j); - if (grid[i][j]) { - // Live cell - nextGrid[i][j] = neighbors === 2 || neighbors === 3; - } else { - // Dead cell - nextGrid[i][j] = neighbors === 3; - } - } - } - - // Swap grids - [grid, nextGrid] = [nextGrid, grid]; - }; - - const drawGrid = () => { - // Clear canvas with subtle background - ctx.fillStyle = 'rgba(255, 255, 255, 0.95)'; - ctx.fillRect( - 0, - 0, - canvas.width / window.devicePixelRatio, - canvas.height / window.devicePixelRatio - ); - - // Draw live cells with gradient colors - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (grid[i][j]) { - const x = j * cellSize; - const y = i * cellSize; - - // Create gradient based on position for visual interest - const gradient = ctx.createRadialGradient( - x + cellSize / 2, - y + cellSize / 2, - 0, - x + cellSize / 2, - y + cellSize / 2, - cellSize / 2 - ); - - // Alternate between two colors for variety - const isEven = (i + j) % 2 === 0; - if (isEven) { - gradient.addColorStop(0, 'rgba(99, 102, 241, 0.5)'); // Indigo - gradient.addColorStop(1, 'rgba(99, 102, 241, 0.2)'); - } else { - gradient.addColorStop(0, 'rgba(139, 92, 246, 0.5)'); // Purple - gradient.addColorStop(1, 'rgba(139, 92, 246, 0.2)'); - } - - ctx.fillStyle = gradient; - ctx.fillRect(x, y, cellSize - 1, cellSize - 1); - } - } - } - }; - - // Initialize and start animation - initializeGrid(); - let animationId: number; - - const animate = () => { - updateGrid(); - drawGrid(); - // Slow down animation by using setTimeout instead of immediate requestAnimationFrame - setTimeout(() => { - animationId = requestAnimationFrame(animate); - }, 200); // 100ms delay = 10x slower (roughly 10 FPS instead of 60 FPS) - }; - - animate(); - - // Cleanup - return () => { - window.removeEventListener('resize', resizeCanvas); - if (animationId) { - cancelAnimationFrame(animationId); - } - }; - }, []); - - return ( -

- {/* Clean white background */} -
- - {/* Conway's Game of Life Canvas */} - - - {/* Subtle dot pattern for texture */} -
- - {/* Clean accent lines */} -
- {/* Top accent line */} -
- - {/* Bottom accent line */} -
-
- - {/* Subtle noise texture */} -
-
- ); -}; diff --git a/apps/marketing/src/components/landing/FeatureVisuals.tsx b/apps/marketing/src/components/landing/FeatureVisuals.tsx index 61187a3..579ddf7 100644 --- a/apps/marketing/src/components/landing/FeatureVisuals.tsx +++ b/apps/marketing/src/components/landing/FeatureVisuals.tsx @@ -21,7 +21,7 @@ export const AssessmentVisual = () => { `} {candidates.map((candidate, index) => ( -
+
{candidate.name}
Score: diff --git a/apps/marketing/src/components/landing/HeroBg.tsx b/apps/marketing/src/components/landing/HeroBg.tsx index f61847c..9a921ae 100644 --- a/apps/marketing/src/components/landing/HeroBg.tsx +++ b/apps/marketing/src/components/landing/HeroBg.tsx @@ -1,52 +1,3 @@ -export const HeroBg2 = () => { - const radius = 500; - - const colorVal = 150; - const color = `rgba(${colorVal},${colorVal},${colorVal},0.12)`; - const color2 = `rgba(${colorVal},${colorVal},${colorVal},0.08)`; - - return ( -
- {/* - - - - */} - -
- -
- -
-
- ); -}; - export const HeroBg = () => { return (
@@ -56,6 +7,7 @@ export const HeroBg = () => { className='absolute inset-0 w-full h-full' preserveAspectRatio='none' > + Hero Background {/* Grid pattern definition */} diff --git a/apps/marketing/src/components/landing/LandingCanvas.tsx b/apps/marketing/src/components/landing/LandingCanvas.tsx deleted file mode 100644 index da6f833..0000000 --- a/apps/marketing/src/components/landing/LandingCanvas.tsx +++ /dev/null @@ -1,156 +0,0 @@ -'use client'; - -import React, { useRef, useEffect } from 'react'; - -const BG_COLOR = '#fff'; -const CHAR_SET = [' ', '.', '-', '~', '*', '=', '%', '#', '@']; -const FONT_SIZE = 16; -const LINE_HEIGHT = 18; -const COL_WIDTH = 10; -const NUM_RIBBONS = 4; -const DOT_CHAR = '.'; - -function getAsciiChar(intensity: number) { - const idx = Math.floor(intensity * (CHAR_SET.length - 1)); - return CHAR_SET[idx]; -} - -// Function to check if a point is inside a rounded rectangle -function isInsideOval( - x: number, - y: number, - centerX: number, - centerY: number, - width: number, - height: number -): boolean { - const normalizedX = (x - centerX) / (width / 2); - const normalizedY = (y - centerY) / (height / 2); - return Math.pow(Math.abs(normalizedX), 4) + Math.pow(Math.abs(normalizedY), 4) <= 1; -} - -const LandingCanvas: React.FC = () => { - const canvasRef = useRef(null); - const animationRef = useRef(0); - const sizeRef = useRef<{ width: number; height: number }>({ width: 800, height: 400 }); - - // Responsive resize - useEffect(() => { - function handleResize() { - const canvas = canvasRef.current; - if (!canvas) return; - let width = canvas.parentElement?.clientWidth || 800; - let height = canvas.parentElement?.clientHeight || 400; - canvas.width = width; - canvas.height = height; - sizeRef.current = { width, height }; - } - handleResize(); - window.addEventListener('resize', handleResize); - return () => window.removeEventListener('resize', handleResize); - }, []); - - useEffect(() => { - const canvas = canvasRef.current; - if (!canvas) return; - const ctx = canvas.getContext('2d'); - if (!ctx) return; - - let time = 0; - - function draw() { - if (!ctx) return; - const { width, height } = sizeRef.current; - - // Clear canvas - ctx.clearRect(0, 0, width, height); - ctx.fillStyle = BG_COLOR; - ctx.fillRect(0, 0, width, height); - - // Set font - ctx.font = `${FONT_SIZE}px monospace`; - ctx.textBaseline = 'top'; - - // Define the oval parameters - const centerX = width / 2; - const centerY = height / 2; - const ovalWidth = width * 0.75; - const ovalHeight = height * 0.6; - - // Calculate grid size - const cols = Math.floor(width / COL_WIDTH); - const rows = Math.floor(height / LINE_HEIGHT); - - // Create moving ribbons that travel across the screen - for (let y = 0; y < rows; y++) { - for (let x = 0; x < cols; x++) { - // Map cell to canvas coordinates - const px = x * COL_WIDTH + COL_WIDTH / 2; - const py = y * LINE_HEIGHT + LINE_HEIGHT / 2; - - // Skip if inside the oval - if (isInsideOval(px, py, centerX, centerY, ovalWidth, ovalHeight)) { - continue; - } - - // Calculate intensity from moving ribbons - let intensity = 0; - - // Create 4 ribbons that move horizontally across the screen - for (let i = 0; i < NUM_RIBBONS; i++) { - const ribbonY = (height / (NUM_RIBBONS + 1)) * (i + 1); - const ribbonSpeed = 0.5 + i * 0.3; // Different speeds for each ribbon - const ribbonWidth = 300 + i * 50; // Different widths - - // Calculate the ribbon's current position (moves from left to right) - const ribbonX = ((time * ribbonSpeed * 50) % (width + ribbonWidth)) - ribbonWidth / 2; - - // Calculate distance from current pixel to the ribbon - const distX = Math.abs(px - ribbonX); - const distY = Math.abs(py - ribbonY); - - // Create a soft ribbon effect - const ribbonInfluence = - Math.max(0, 1 - distX / (ribbonWidth / 2)) * Math.max(0, 1 - distY / 30); - - intensity += ribbonInfluence * 0.8; - } - - // Add some vertical wave motion - const waveIntensity = Math.sin(time * 0.5 + px * 0.02) * 0.3 + 0.3; - intensity += waveIntensity; - - // Normalize and enhance intensity - intensity = Math.min(1, Math.max(0, intensity)); - intensity = Math.pow(intensity, 0.8); - - // Map intensity to color - const shade = Math.floor(250 - 150 * intensity); - ctx.fillStyle = `rgb(${shade},${shade},${shade})`; - ctx.fillText(DOT_CHAR, px - COL_WIDTH / 2, py - LINE_HEIGHT / 2); - } - } - - // Update time for animation - time += 0.05; - animationRef.current = requestAnimationFrame(draw); - } - - draw(); - return () => { - if (animationRef.current) { - cancelAnimationFrame(animationRef.current); - } - }; - }, []); - - return ( - - ); -}; - -export default LandingCanvas; diff --git a/apps/marketing/src/components/landing/LandingFAQ.tsx b/apps/marketing/src/components/landing/LandingFAQ.tsx index 05adb22..b1a2669 100644 --- a/apps/marketing/src/components/landing/LandingFAQ.tsx +++ b/apps/marketing/src/components/landing/LandingFAQ.tsx @@ -1,5 +1,4 @@ 'use client'; -import { Button } from '@coderscreen/ui/button'; import { Accordion, AccordionContent, @@ -59,7 +58,7 @@ export const LandingFAQ = () => {
{FAQ_ITEMS.map((item, index) => ( - + {item.question} {item.answer} diff --git a/apps/marketing/src/components/landing/LandingFeatures.tsx b/apps/marketing/src/components/landing/LandingFeatures.tsx index 31753c1..375da44 100644 --- a/apps/marketing/src/components/landing/LandingFeatures.tsx +++ b/apps/marketing/src/components/landing/LandingFeatures.tsx @@ -1,7 +1,8 @@ 'use client'; -import { useState } from 'react'; import { motion } from 'motion/react'; +import Image from 'next/image'; +import { useState } from 'react'; import { cn } from '@/lib/utils'; interface Feature { @@ -83,7 +84,7 @@ export const LandingFeatures = () => { {/* Right Side - Feature Content */}
- {selectedFeature.imageAlt} { return ( diff --git a/apps/marketing/src/components/landing/LandingPageView.tsx b/apps/marketing/src/components/landing/LandingPageView.tsx index 478752e..08e84b0 100644 --- a/apps/marketing/src/components/landing/LandingPageView.tsx +++ b/apps/marketing/src/components/landing/LandingPageView.tsx @@ -1,10 +1,10 @@ -import { LandingHero } from './LandingHero'; -import { LandingUseCases } from './LandingUseCases'; import { MarketingCTA } from '@/components/common/MarketingCTA'; -import { LandingPricing } from '@/components/landing/LandingPricing'; import { LandingFAQ } from '@/components/landing/LandingFAQ'; -import { LandingWorkflow } from '@/components/landing/LandingWorkflow'; import { LandingFeatures } from '@/components/landing/LandingFeatures'; +import { LandingPricing } from '@/components/landing/LandingPricing'; +import { LandingWorkflow } from '@/components/landing/LandingWorkflow'; +import { LandingHero } from './LandingHero'; +import { LandingUseCases } from './LandingUseCases'; export const LandingPageView = () => { return ( diff --git a/apps/marketing/src/components/landing/LandingPricing.tsx b/apps/marketing/src/components/landing/LandingPricing.tsx index 49159b1..088ce35 100644 --- a/apps/marketing/src/components/landing/LandingPricing.tsx +++ b/apps/marketing/src/components/landing/LandingPricing.tsx @@ -1,26 +1,26 @@ 'use client'; -import { cx } from '@/lib/utils'; -import { Button } from '@coderscreen/ui/button'; -import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@coderscreen/ui/card'; import { Badge } from '@coderscreen/ui/badge'; +import { Button } from '@coderscreen/ui/button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@coderscreen/ui/card'; +import { ToggleGroup, ToggleGroupItem } from '@coderscreen/ui/toggle-group'; import { - RiStarLine, - RiTeamLine, + RemixiconComponentType, + RiArrowRightLine, + RiBaseStationLine, RiCustomerServiceLine, RiGlobalLine, RiHistoryLine, - RiSwap2Line, + RiLockPasswordLine, RiPaletteLine, + RiStarLine, + RiSwap2Line, + RiTeamLine, RiTerminalWindowFill, - RiBaseStationLine, - RiLockPasswordLine, - RiArrowRightLine, - RemixiconComponentType, } from '@remixicon/react'; import { useState } from 'react'; -import { ToggleGroup, ToggleGroupItem } from '@coderscreen/ui/toggle-group'; import { siteConfig } from '@/lib/siteConfig'; +import { cx } from '@/lib/utils'; const LIMIT_MAP = { live_interviews: { @@ -377,32 +377,30 @@ export const LandingPricing = () => { } )} - {PLAN_FEATURE_MAP[plan.group as keyof typeof PLAN_FEATURE_MAP].map( - (feature, index) => { - const IconComponent = feature.icon; - return ( -
  • { + const IconComponent = feature.icon; + return ( +
  • +
    + +
    +
    + {feature.label} + {feature.subText && ( + + {feature.subText} + )} - > -
    - -
    -
    - {feature.label} - {feature.subText && ( - - {feature.subText} - - )} -
    -
  • - ); - } - )} +
    + + ); + })} diff --git a/apps/marketing/src/components/landing/LandingTrustedBy.tsx b/apps/marketing/src/components/landing/LandingTrustedBy.tsx index d01d2a7..b7106c7 100644 --- a/apps/marketing/src/components/landing/LandingTrustedBy.tsx +++ b/apps/marketing/src/components/landing/LandingTrustedBy.tsx @@ -1,3 +1,5 @@ +import Image from 'next/image'; + const TRUSTED_COMPANIES: { name: string; logo: string; @@ -23,9 +25,9 @@ export const LandingTrustedBy = () => {

    Built by engineers from

    - {TRUSTED_COMPANIES.map((company, index) => ( -
    - ( +
    + {`${company.name} { const [activeStage, setActiveStage] = useState(0); @@ -140,6 +141,7 @@ const IntegrationsVisual = () => { version='1.1' className='pointer-events-none absolute inset-0 size-full' > + Background circle @@ -148,6 +150,7 @@ const IntegrationsVisual = () => { version='1.1' className='pointer-events-none absolute inset-0 size-full' > + Second background circle { } className='absolute flex size-[var(--icon-size)] transform-gpu animate-orbit items-center justify-center rounded-full bg-white shadow-sm' > - {logo.name} { } className='absolute flex size-[var(--icon-size)] transform-gpu animate-orbit items-center justify-center rounded-full bg-white shadow-sm' > - {logo.name}; - -export const AvailableBgColors: string[] = Object.values(chartColors).map((color) => color.bg); - -export const constructCategoryColors = ( - categories: string[], - colors: AvailableChartColorsKeys[] -): Map => { - const categoryColors = new Map(); - categories.forEach((category, index) => { - categoryColors.set(category, colors[index % colors.length]); - }); - return categoryColors; -}; - -export const getColorClassName = (color: AvailableChartColorsKeys, type: ColorUtility): string => { - const fallbackColor = { - bg: 'bg-gray-500', - stroke: 'stroke-gray-500', - fill: 'fill-gray-500', - text: 'text-gray-500', - }; - return chartColors[color]?.[type] ?? fallbackColor[type]; -}; - -// Tremor Raw getYAxisDomain [v0.0.0] - -export const getYAxisDomain = ( - autoMinValue: boolean, - minValue: number | undefined, - maxValue: number | undefined -) => { - const minDomain = autoMinValue ? 'auto' : minValue ?? 0; - const maxDomain = maxValue ?? 'auto'; - return [minDomain, maxDomain]; -}; - -// Tremor Raw hasOnlyOneValueForKey [v0.1.0] - -export function hasOnlyOneValueForKey(array: any[], keyToCheck: string): boolean { - const val: any[] = []; - - for (const obj of array) { - if (Object.prototype.hasOwnProperty.call(obj, keyToCheck)) { - val.push(obj[keyToCheck]); - if (val.length > 1) { - return false; - } - } - } - - return true; -} diff --git a/apps/marketing/src/lib/dateUtils.ts b/apps/marketing/src/lib/dateUtils.ts index dbae99c..8a0c837 100644 --- a/apps/marketing/src/lib/dateUtils.ts +++ b/apps/marketing/src/lib/dateUtils.ts @@ -1,6 +1,6 @@ import dayjs from 'dayjs'; -import utc from 'dayjs/plugin/utc'; import tz from 'dayjs/plugin/timezone'; +import utc from 'dayjs/plugin/utc'; dayjs.extend(utc); dayjs.extend(tz); diff --git a/apps/marketing/src/lib/gaugeUtils.ts b/apps/marketing/src/lib/gaugeUtils.ts index 6643179..6d1eb29 100644 --- a/apps/marketing/src/lib/gaugeUtils.ts +++ b/apps/marketing/src/lib/gaugeUtils.ts @@ -139,10 +139,10 @@ export const calculatePrimaryStroke = ( return strokePercent <= 25 ? 'hsl(358 75% 59%)' : strokePercent <= 50 - ? 'hsl(39 100% 57%)' - : strokePercent <= 75 - ? 'hsl(212 100% 48%)' - : 'hsl(131 41% 46%)'; + ? 'hsl(39 100% 57%)' + : strokePercent <= 75 + ? 'hsl(212 100% 48%)' + : 'hsl(131 41% 46%)'; } else if (typeof primary === 'string') { // Specific default color or custom color return primary; diff --git a/apps/marketing/src/lib/useOnWindowResize.ts b/apps/marketing/src/lib/useOnWindowResize.ts index 51b2f42..8813734 100644 --- a/apps/marketing/src/lib/useOnWindowResize.ts +++ b/apps/marketing/src/lib/useOnWindowResize.ts @@ -2,7 +2,7 @@ import * as React from 'react'; -export const useOnWindowResize = (handler: { (): void }) => { +export const useOnWindowResize = (handler: () => void) => { React.useEffect(() => { const handleResize = () => { handler(); diff --git a/apps/marketing/src/lib/utils.ts b/apps/marketing/src/lib/utils.ts index 5c2ca84..4d26ae4 100644 --- a/apps/marketing/src/lib/utils.ts +++ b/apps/marketing/src/lib/utils.ts @@ -9,8 +9,7 @@ export const cx = (...args: ClassValue[]) => { export const cn = cx; // Sleep utility function -export const sleep = (ms: number) => - new Promise((resolve) => setTimeout(resolve, ms)); +export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); // Tremor Raw focusInput [v0.0.1] diff --git a/apps/web/src/components/common/LanguageIcon.tsx b/apps/web/src/components/common/LanguageIcon.tsx index 02c7e6d..37b49ca 100644 --- a/apps/web/src/components/common/LanguageIcon.tsx +++ b/apps/web/src/components/common/LanguageIcon.tsx @@ -1,17 +1,17 @@ -import { cn } from '@/lib/utils'; import { RoomSchema } from '@coderscreen/api/schema/room'; -import JavascriptPlain from 'devicons-react/icons/JavascriptPlain'; -import TypescriptPlain from 'devicons-react/icons/TypescriptPlain'; -import PythonPlain from 'devicons-react/icons/PythonPlain'; -import RustOriginal from 'devicons-react/icons/RustOriginal'; -import CPlusPlusPlain from 'devicons-react/icons/CPlusPlusPlain'; +import BashPlain from 'devicons-react/icons/BashPlain'; import CPlain from 'devicons-react/icons/CPlain'; +import CplusplusPlain from 'devicons-react/icons/CplusplusPlain'; import GoPlain from 'devicons-react/icons/GoPlain'; import JavaPlain from 'devicons-react/icons/JavaPlain'; +import JavascriptPlain from 'devicons-react/icons/JavascriptPlain'; import PhpPlain from 'devicons-react/icons/PhpPlain'; +import PythonPlain from 'devicons-react/icons/PythonPlain'; import RubyPlain from 'devicons-react/icons/RubyPlain'; -import BashPlain from 'devicons-react/icons/BashPlain'; +import RustOriginal from 'devicons-react/icons/RustOriginal'; +import TypescriptPlain from 'devicons-react/icons/TypescriptPlain'; import { useMemo } from 'react'; +import { cn } from '@/lib/utils'; const BASE_ICON_STYLE = 'h-4 w-4'; @@ -37,7 +37,7 @@ export const LanguageIcon = ({ // need to manually set the color to gray return ; case 'c++': - return ; + return ; case 'c': return ; case 'java': @@ -55,7 +55,5 @@ export const LanguageIcon = ({ } })(); - return ( -
    {icon}
    - ); + return
    {icon}
    ; }; diff --git a/apps/web/wrangler.example.jsonc b/apps/web/wrangler.jsonc similarity index 67% rename from apps/web/wrangler.example.jsonc rename to apps/web/wrangler.jsonc index 8a07a0d..0032593 100644 --- a/apps/web/wrangler.example.jsonc +++ b/apps/web/wrangler.jsonc @@ -14,5 +14,15 @@ "assets": { "binding": "ASSETS", "not_found_handling": "single-page-application" + }, + "routes": [ + { + "pattern": "app.coderscreen.com", + "custom_domain": true + } + ], + "vars": { + "VITE_APP_URL": "https://app.coderscreen.com", + "VITE_API_URL": "https://api.coderscreen.com" } } diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..7a07b60 --- /dev/null +++ b/biome.json @@ -0,0 +1,31 @@ +{ + "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", + "linter": { + "enabled": true, + "rules": { + "recommended": true, + "style": { + "useImportType": "off" + } + } + }, + "formatter": { + "lineWidth": 100, + "indentStyle": "space", + "indentWidth": 2, + "lineEnding": "lf", + "enabled": true + }, + "javascript": { + "formatter": { + "quoteStyle": "single", + "jsxQuoteStyle": "single", + "trailingCommas": "es5", + "semicolons": "always", + "arrowParentheses": "always", + "bracketSpacing": true, + "bracketSameLine": false, + "quoteProperties": "asNeeded" + } + } +} diff --git a/package.json b/package.json index 9927ddf..1d87c1d 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,13 @@ "packages/*" ], "scripts": { + "nx:lint": "npx nx run-many --target=lint", + "nx:build": "npx nx run-many --target=build", + "build": "nx next:build && echo 'Build complete'", "sandbox:build": "docker build -t sandbox-image -f ./apps/api/src/containers/images/Dockerfile ." + }, + "devDependencies": { + "@biomejs/biome": "2.1.2", + "nx": "21.3.7" } } diff --git a/packages/common/package.json b/packages/common/package.json index 5a927ba..64531b3 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,9 +1,12 @@ { "name": "@coderscreen/common", "version": "1.0.0", + "type": "module", "description": "", - "main": "index.js", "scripts": { + "lint": "biome check", + "lint:fix": "biome check --write", + "format": "biome format --write", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], diff --git a/packages/common/src/id.ts b/packages/common/src/id.ts index e2dcca5..85534bb 100644 --- a/packages/common/src/id.ts +++ b/packages/common/src/id.ts @@ -1,5 +1,5 @@ -import { z } from 'zod'; import { nanoid } from 'nanoid'; +import { z } from 'zod'; export const Entities = { room: 'r', diff --git a/packages/db/drizzle.config.ts b/packages/db/drizzle.config.ts index cc08a18..63329d9 100644 --- a/packages/db/drizzle.config.ts +++ b/packages/db/drizzle.config.ts @@ -1,15 +1,21 @@ -import { defineConfig } from 'drizzle-kit'; +import path from 'node:path'; import dotenv from 'dotenv'; +import { defineConfig } from 'drizzle-kit'; -const result = dotenv.config({ - path: __dirname + '/.env', +dotenv.config({ + path: path.join(__dirname, '.env'), }); +const DATABASE_URL = process.env.DATABASE_URL; +if (!DATABASE_URL) { + throw new Error('DATABASE_URL is not set'); +} + export default defineConfig({ dialect: 'postgresql', schema: './src/**/*.db.ts', out: './drizzle', dbCredentials: { - url: process.env.DATABASE_URL!, + url: DATABASE_URL, }, }); diff --git a/packages/db/package.json b/packages/db/package.json index 30ab295..a5aaaa0 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -3,8 +3,11 @@ "version": "1.0.0", "description": "", "main": "index.js", + "type": "module", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", + "lint": "biome check", + "lint:fix": "biome check --write", + "format": "biome format --write", "db:generate": "drizzle-kit generate", "db:migrate": "drizzle-kit migrate", "db:studio": "drizzle-kit studio", diff --git a/packages/db/src/asset.db.ts b/packages/db/src/asset.db.ts index 7e82879..0899420 100644 --- a/packages/db/src/asset.db.ts +++ b/packages/db/src/asset.db.ts @@ -7,9 +7,7 @@ type AssetStatus = 'active' | 'deleted'; export const assetTable = pgTable('assets', { id: text('id').primaryKey().$type>(), - createdAt: timestamp('created_at', { mode: 'string' }) - .default(sql`now()`) - .notNull(), + createdAt: timestamp('created_at', { mode: 'string' }).default(sql`now()`).notNull(), userId: text('user_id') .notNull() .references(() => user.id, { onDelete: 'cascade' }), diff --git a/packages/db/src/billing.db.ts b/packages/db/src/billing.db.ts index 940a424..081c3f0 100644 --- a/packages/db/src/billing.db.ts +++ b/packages/db/src/billing.db.ts @@ -1,6 +1,6 @@ -import { pgTable, text, timestamp, boolean, integer, jsonb } from 'drizzle-orm/pg-core'; -import { organization } from './user.db'; import { Id } from '@coderscreen/common/id'; +import { boolean, integer, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'; +import { organization } from './user.db'; export const customerTable = pgTable('customers', { organizationId: text('organization_id') diff --git a/packages/db/src/llmMessage.db.ts b/packages/db/src/llmMessage.db.ts index 8e741e5..33c9d8f 100644 --- a/packages/db/src/llmMessage.db.ts +++ b/packages/db/src/llmMessage.db.ts @@ -1,16 +1,14 @@ import { Id } from '@coderscreen/common/id'; import { sql } from 'drizzle-orm'; import { boolean, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'; -import { organization } from './user.db'; import { roomTable } from './room.db'; +import { organization } from './user.db'; type LLMRole = 'user' | 'assistant' | 'system'; export const llmMessageTable = pgTable('llm_messages', { id: text('id').primaryKey().$type>(), - createdAt: timestamp('created_at', { mode: 'string' }) - .default(sql`now()`) - .notNull(), + createdAt: timestamp('created_at', { mode: 'string' }).default(sql`now()`).notNull(), organizationId: text('organization_id') .notNull() .references(() => organization.id, { onDelete: 'cascade' }), diff --git a/packages/db/src/room.db.ts b/packages/db/src/room.db.ts index 74adc35..b236f7f 100644 --- a/packages/db/src/room.db.ts +++ b/packages/db/src/room.db.ts @@ -1,6 +1,6 @@ -import { Id } from '@coderscreen/common/id'; +import type { Id } from '@coderscreen/common/id'; import { sql } from 'drizzle-orm'; -import { jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'; +import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'; import { organization, user } from './user.db'; type RoomLanguage = @@ -20,12 +20,8 @@ type RoomStatus = 'active' | 'scheduled' | 'completed' | 'archived'; export const roomTable = pgTable('rooms', { id: text('id').primaryKey().$type>(), title: text('title').notNull(), - createdAt: timestamp('created_at', { mode: 'string' }) - .default(sql`now()`) - .notNull(), - updatedAt: timestamp('updated_at', { mode: 'string' }) - .default(sql`now()`) - .notNull(), + createdAt: timestamp('created_at', { mode: 'string' }).default(sql`now()`).notNull(), + updatedAt: timestamp('updated_at', { mode: 'string' }).default(sql`now()`).notNull(), language: text('language').$type().notNull(), status: text('status').$type().notNull(), notes: text('notes').notNull().default(''), diff --git a/packages/db/src/roomContent.db.ts b/packages/db/src/roomContent.db.ts index 083939b..02e422f 100644 --- a/packages/db/src/roomContent.db.ts +++ b/packages/db/src/roomContent.db.ts @@ -1,8 +1,8 @@ import { Id } from '@coderscreen/common/id'; import { sql } from 'drizzle-orm'; import { jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'; -import { organization, user } from './user.db'; import { RoomEntity, roomTable } from './room.db'; +import { organization, user } from './user.db'; type TrackerUsers = { id: string; @@ -16,12 +16,8 @@ export const roomContentTable = pgTable('room_contents', { .primaryKey() .$type>() .references(() => roomTable.id, { onDelete: 'cascade' }), - createdAt: timestamp('created_at', { mode: 'string' }) - .default(sql`now()`) - .notNull(), - updatedAt: timestamp('updated_at', { mode: 'string' }) - .default(sql`now()`) - .notNull(), + createdAt: timestamp('created_at', { mode: 'string' }).default(sql`now()`).notNull(), + updatedAt: timestamp('updated_at', { mode: 'string' }).default(sql`now()`).notNull(), organizationId: text('organization_id') .notNull() .references(() => organization.id, { onDelete: 'cascade' }), diff --git a/packages/db/src/template.db.ts b/packages/db/src/template.db.ts index 88fbce6..0d6730f 100644 --- a/packages/db/src/template.db.ts +++ b/packages/db/src/template.db.ts @@ -1,18 +1,14 @@ import { Id } from '@coderscreen/common/id'; import { sql } from 'drizzle-orm'; import { jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core'; -import { organization, user } from './user.db'; import { RoomEntity } from './room.db'; +import { organization, user } from './user.db'; export const templateTable = pgTable('templates', { id: text('id').primaryKey().$type>(), title: text('title').notNull(), - createdAt: timestamp('created_at', { mode: 'string' }) - .default(sql`now()`) - .notNull(), - updatedAt: timestamp('updated_at', { mode: 'string' }) - .default(sql`now()`) - .notNull(), + createdAt: timestamp('created_at', { mode: 'string' }).default(sql`now()`).notNull(), + updatedAt: timestamp('updated_at', { mode: 'string' }).default(sql`now()`).notNull(), organizationId: text('organization_id') .notNull() .references(() => organization.id, { onDelete: 'cascade' }), diff --git a/packages/db/src/usage.db.ts b/packages/db/src/usage.db.ts index a217d0b..a91abb0 100644 --- a/packages/db/src/usage.db.ts +++ b/packages/db/src/usage.db.ts @@ -1,6 +1,6 @@ -import { pgTable, text, timestamp, integer, uniqueIndex, jsonb } from 'drizzle-orm/pg-core'; -import { organization } from './user.db'; import { Id } from '@coderscreen/common/id'; +import { integer, jsonb, pgTable, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'; +import { organization } from './user.db'; export type EventType = 'live_interview'; diff --git a/packages/db/src/user.db.ts b/packages/db/src/user.db.ts index 3ad8b50..483769f 100644 --- a/packages/db/src/user.db.ts +++ b/packages/db/src/user.db.ts @@ -1,77 +1,95 @@ -import { pgTable, text, timestamp, boolean, integer } from "drizzle-orm/pg-core"; +import { boolean, pgTable, text, timestamp } from 'drizzle-orm/pg-core'; -export const user = pgTable("user", { - id: text('id').primaryKey(), - name: text('name').notNull(), - email: text('email').notNull().unique(), - emailVerified: boolean('email_verified').$defaultFn(() => false).notNull(), - image: text('image'), - createdAt: timestamp('created_at').$defaultFn(() => /* @__PURE__ */ new Date()).notNull(), - updatedAt: timestamp('updated_at').$defaultFn(() => /* @__PURE__ */ new Date()).notNull(), - isOnboarded: boolean('is_onboarded').notNull(), - persona: text('persona') - }); +export const user = pgTable('user', { + id: text('id').primaryKey(), + name: text('name').notNull(), + email: text('email').notNull().unique(), + emailVerified: boolean('email_verified') + .$defaultFn(() => false) + .notNull(), + image: text('image'), + createdAt: timestamp('created_at') + .$defaultFn(() => /* @__PURE__ */ new Date()) + .notNull(), + updatedAt: timestamp('updated_at') + .$defaultFn(() => /* @__PURE__ */ new Date()) + .notNull(), + isOnboarded: boolean('is_onboarded').notNull(), + persona: text('persona'), +}); -export const session = pgTable("session", { - id: text('id').primaryKey(), - expiresAt: timestamp('expires_at').notNull(), - token: text('token').notNull().unique(), - createdAt: timestamp('created_at').notNull(), - updatedAt: timestamp('updated_at').notNull(), - ipAddress: text('ip_address'), - userAgent: text('user_agent'), - userId: text('user_id').notNull().references(()=> user.id, { onDelete: 'cascade' }), - activeOrganizationId: text('active_organization_id') - }); +export const session = pgTable('session', { + id: text('id').primaryKey(), + expiresAt: timestamp('expires_at').notNull(), + token: text('token').notNull().unique(), + createdAt: timestamp('created_at').notNull(), + updatedAt: timestamp('updated_at').notNull(), + ipAddress: text('ip_address'), + userAgent: text('user_agent'), + userId: text('user_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + activeOrganizationId: text('active_organization_id'), +}); -export const account = pgTable("account", { - id: text('id').primaryKey(), - accountId: text('account_id').notNull(), - providerId: text('provider_id').notNull(), - userId: text('user_id').notNull().references(()=> user.id, { onDelete: 'cascade' }), - accessToken: text('access_token'), - refreshToken: text('refresh_token'), - idToken: text('id_token'), - accessTokenExpiresAt: timestamp('access_token_expires_at'), - refreshTokenExpiresAt: timestamp('refresh_token_expires_at'), - scope: text('scope'), - password: text('password'), - createdAt: timestamp('created_at').notNull(), - updatedAt: timestamp('updated_at').notNull() - }); +export const account = pgTable('account', { + id: text('id').primaryKey(), + accountId: text('account_id').notNull(), + providerId: text('provider_id').notNull(), + userId: text('user_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + accessToken: text('access_token'), + refreshToken: text('refresh_token'), + idToken: text('id_token'), + accessTokenExpiresAt: timestamp('access_token_expires_at'), + refreshTokenExpiresAt: timestamp('refresh_token_expires_at'), + scope: text('scope'), + password: text('password'), + createdAt: timestamp('created_at').notNull(), + updatedAt: timestamp('updated_at').notNull(), +}); -export const verification = pgTable("verification", { - id: text('id').primaryKey(), - identifier: text('identifier').notNull(), - value: text('value').notNull(), - expiresAt: timestamp('expires_at').notNull(), - createdAt: timestamp('created_at').$defaultFn(() => /* @__PURE__ */ new Date()), - updatedAt: timestamp('updated_at').$defaultFn(() => /* @__PURE__ */ new Date()) - }); +export const verification = pgTable('verification', { + id: text('id').primaryKey(), + identifier: text('identifier').notNull(), + value: text('value').notNull(), + expiresAt: timestamp('expires_at').notNull(), + createdAt: timestamp('created_at').$defaultFn(() => /* @__PURE__ */ new Date()), + updatedAt: timestamp('updated_at').$defaultFn(() => /* @__PURE__ */ new Date()), +}); -export const organization = pgTable("organization", { - id: text('id').primaryKey(), - name: text('name').notNull(), - slug: text('slug').unique(), - logo: text('logo'), - createdAt: timestamp('created_at').notNull(), - metadata: text('metadata') - }); +export const organization = pgTable('organization', { + id: text('id').primaryKey(), + name: text('name').notNull(), + slug: text('slug').unique(), + logo: text('logo'), + createdAt: timestamp('created_at').notNull(), + metadata: text('metadata'), +}); -export const member = pgTable("member", { - id: text('id').primaryKey(), - organizationId: text('organization_id').notNull().references(()=> organization.id, { onDelete: 'cascade' }), - userId: text('user_id').notNull().references(()=> user.id, { onDelete: 'cascade' }), - role: text('role').default("member").notNull(), - createdAt: timestamp('created_at').notNull() - }); +export const member = pgTable('member', { + id: text('id').primaryKey(), + organizationId: text('organization_id') + .notNull() + .references(() => organization.id, { onDelete: 'cascade' }), + userId: text('user_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), + role: text('role').default('member').notNull(), + createdAt: timestamp('created_at').notNull(), +}); -export const invitation = pgTable("invitation", { - id: text('id').primaryKey(), - organizationId: text('organization_id').notNull().references(()=> organization.id, { onDelete: 'cascade' }), - email: text('email').notNull(), - role: text('role'), - status: text('status').default("pending").notNull(), - expiresAt: timestamp('expires_at').notNull(), - inviterId: text('inviter_id').notNull().references(()=> user.id, { onDelete: 'cascade' }) - }); +export const invitation = pgTable('invitation', { + id: text('id').primaryKey(), + organizationId: text('organization_id') + .notNull() + .references(() => organization.id, { onDelete: 'cascade' }), + email: text('email').notNull(), + role: text('role'), + status: text('status').default('pending').notNull(), + expiresAt: timestamp('expires_at').notNull(), + inviterId: text('inviter_id') + .notNull() + .references(() => user.id, { onDelete: 'cascade' }), +}); diff --git a/packages/sandbox-sdk/package.json b/packages/sandbox-sdk/package.json index f1b65ed..a441a50 100644 --- a/packages/sandbox-sdk/package.json +++ b/packages/sandbox-sdk/package.json @@ -4,7 +4,7 @@ "description": "an api for computers", "scripts": { "check": "biome check && tsc --noEmit", - "build": "npm run build -w @cloudflare/sandbox", + "build": "cd packages/sandbox && npm run build", "test": "echo 'No tests'", "postinstall": "patch-package" }, @@ -34,6 +34,5 @@ "typescript": "^5.8.3", "wrangler": "^4.21.2" }, - "private": true, "packageManager": "npm@11.4.2" } diff --git a/packages/ui/package.json b/packages/ui/package.json index 8673d75..02ace42 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -3,6 +3,9 @@ "version": "1.0.0", "description": "", "scripts": { + "lint": "biome check", + "lint:fix": "biome check --write", + "format": "biome format --write", "build:styles": "tailwindcss -i ./src/styles.css -o ./dist/index.css", "test": "echo \"Error: no test specified\" && exit 1" }, @@ -31,7 +34,9 @@ "@radix-ui/react-toggle-group": "^1.1.2", "@radix-ui/react-tooltip": "^1.1.8", "@remixicon/react": "^4.6.0", + "clsx": "^2.1.1", "react": "^19.1.0", + "tailwind-merge": "^3.0.2", "tailwind-variants": "^0.3.1" }, "devDependencies": { diff --git a/packages/ui/src/components/accordion.tsx b/packages/ui/src/components/accordion.tsx index 8b6ef05..e5373f4 100644 --- a/packages/ui/src/components/accordion.tsx +++ b/packages/ui/src/components/accordion.tsx @@ -1,10 +1,10 @@ // Tremor Raw Accordion [v0.0.0] -import React from 'react'; import * as AccordionPrimitives from '@radix-ui/react-accordion'; import { RiAddLine } from '@remixicon/react'; +import React from 'react'; -import { cx } from '@/lib/utils'; +import { cx } from '../lib/utils'; const Accordion = AccordionPrimitives.Root; diff --git a/packages/ui/src/components/areachart.tsx b/packages/ui/src/components/areachart.tsx deleted file mode 100644 index 35e5955..0000000 --- a/packages/ui/src/components/areachart.tsx +++ /dev/null @@ -1,1004 +0,0 @@ -// Tremor Raw AreaChart [v0.1.0] - -'use client'; - -import React from 'react'; -import { RiArrowLeftSLine, RiArrowRightSLine } from '@remixicon/react'; -import { - Area, - CartesianGrid, - Dot, - Label, - Line, - AreaChart as RechartsAreaChart, - Legend as RechartsLegend, - ResponsiveContainer, - Tooltip, - XAxis, - YAxis, -} from 'recharts'; -import { type AxisDomain } from 'recharts/types/util/types'; - -import { - AvailableChartColors, - type AvailableChartColorsKeys, - constructCategoryColors, - getColorClassName, - getYAxisDomain, - hasOnlyOneValueForKey, -} from '@/lib/chartUtils'; -import { useOnWindowResize } from '@/lib/useOnWindowResize'; -import { cx } from '@/lib/utils'; - -//#region Legend - -interface LegendItemProps { - name: string; - color: AvailableChartColorsKeys; - onClick?: (name: string, color: AvailableChartColorsKeys) => void; - activeLegend?: string; -} - -const LegendItem = ({ - name, - color, - onClick, - activeLegend, -}: LegendItemProps) => { - const hasOnValueChange = !!onClick; - return ( -
  • { - e.stopPropagation(); - onClick?.(name, color); - }} - > - -

    - {name} -

    -
  • - ); -}; - -interface ScrollButtonProps { - icon: React.ElementType; - onClick?: () => void; - disabled?: boolean; -} - -const ScrollButton = ({ icon, onClick, disabled }: ScrollButtonProps) => { - const Icon = icon; - const [isPressed, setIsPressed] = React.useState(false); - const intervalRef = React.useRef(null); - - React.useEffect(() => { - if (isPressed) { - intervalRef.current = window.setInterval(() => { - onClick?.(); - }, 300); - } else { - if (intervalRef.current) { - window.clearInterval(intervalRef.current); - } - } - return () => { - if (intervalRef.current) { - window.clearInterval(intervalRef.current); - } - }; - }, [isPressed, onClick]); - - React.useEffect(() => { - if (disabled) { - if (intervalRef.current) { - window.clearInterval(intervalRef.current); - } - setIsPressed(false); - } - }, [disabled]); - - return ( - - ); -}; - -interface LegendProps extends React.OlHTMLAttributes { - categories: string[]; - colors?: AvailableChartColorsKeys[]; - onClickLegendItem?: (category: string, color: string) => void; - activeLegend?: string; - enableLegendSlider?: boolean; -} - -type HasScrollProps = { - left: boolean; - right: boolean; -}; - -const Legend = React.forwardRef((props, ref) => { - const { - categories, - colors = AvailableChartColors, - className, - onClickLegendItem, - activeLegend, - enableLegendSlider = false, - ...other - } = props; - const scrollableRef = React.useRef(null); - const [hasScroll, setHasScroll] = React.useState(null); - const [isKeyDowned, setIsKeyDowned] = React.useState(null); - const intervalRef = React.useRef | undefined>( - undefined - ); - - const checkScroll = React.useCallback(() => { - const scrollable = scrollableRef?.current; - if (!scrollable) return; - - const hasLeftScroll = scrollable.scrollLeft > 0; - const hasRightScroll = - scrollable.scrollWidth - scrollable.clientWidth > scrollable.scrollLeft; - - setHasScroll({ left: hasLeftScroll, right: hasRightScroll }); - }, [setHasScroll]); - - const scrollToTest = React.useCallback( - (direction: 'left' | 'right') => { - const element = scrollableRef?.current; - const width = element?.clientWidth ?? 0; - - if (element && enableLegendSlider) { - element.scrollTo({ - left: - direction === 'left' - ? element.scrollLeft - width - : element.scrollLeft + width, - behavior: 'smooth', - }); - setTimeout(() => { - checkScroll(); - }, 400); - } - }, - [enableLegendSlider, checkScroll] - ); - - React.useEffect(() => { - const keyDownHandler = (key: string) => { - if (key === 'ArrowLeft') { - scrollToTest('left'); - } else if (key === 'ArrowRight') { - scrollToTest('right'); - } - }; - if (isKeyDowned) { - keyDownHandler(isKeyDowned); - intervalRef.current = setInterval(() => { - keyDownHandler(isKeyDowned); - }, 300); - } else { - clearInterval(intervalRef.current); - } - return () => clearInterval(intervalRef.current); - }, [isKeyDowned, scrollToTest]); - - const keyDown = (e: KeyboardEvent) => { - e.stopPropagation(); - if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { - e.preventDefault(); - setIsKeyDowned(e.key); - } - }; - const keyUp = (e: KeyboardEvent) => { - e.stopPropagation(); - setIsKeyDowned(null); - }; - - React.useEffect(() => { - const scrollable = scrollableRef?.current; - if (enableLegendSlider) { - checkScroll(); - scrollable?.addEventListener('keydown', keyDown); - scrollable?.addEventListener('keyup', keyUp); - } - - return () => { - scrollable?.removeEventListener('keydown', keyDown); - scrollable?.removeEventListener('keyup', keyUp); - }; - }, [checkScroll, enableLegendSlider]); - - return ( -
      -
      - {categories.map((category, index) => ( - - ))} -
      - {enableLegendSlider && (hasScroll?.right || hasScroll?.left) ? ( - <> -
      - { - setIsKeyDowned(null); - scrollToTest('left'); - }} - disabled={!hasScroll?.left} - /> - { - setIsKeyDowned(null); - scrollToTest('right'); - }} - disabled={!hasScroll?.right} - /> -
      - - ) : null} -
    - ); -}); - -Legend.displayName = 'Legend'; - -const ChartLegend = ( - { payload }: any, - categoryColors: Map, - setLegendHeight: React.Dispatch>, - activeLegend: string | undefined, - onClick?: (category: string, color: string) => void, - enableLegendSlider?: boolean, - legendPosition?: 'left' | 'center' | 'right', - yAxisWidth?: number -) => { - const legendRef = React.useRef(null); - - useOnWindowResize(() => { - const calculateHeight = (height: number | undefined) => - height ? Number(height) + 15 : 60; - setLegendHeight(calculateHeight(legendRef.current?.clientHeight)); - }); - - const filteredPayload = payload.filter((item: any) => item.type !== 'none'); - - const paddingLeft = - legendPosition === 'left' && yAxisWidth ? yAxisWidth - 8 : 0; - - return ( -
    - entry.value)} - colors={filteredPayload.map((entry: any) => - categoryColors.get(entry.value) - )} - onClickLegendItem={onClick} - activeLegend={activeLegend} - enableLegendSlider={enableLegendSlider} - /> -
    - ); -}; - -//#region Tooltip - -interface ChartTooltipRowProps { - value: string; - name: string; - color: string; -} - -const ChartTooltipRow = ({ value, name, color }: ChartTooltipRowProps) => ( -
    -
    -
    -

    - {value} -

    -
    -); - -interface ChartTooltipProps { - active: boolean | undefined; - payload: any; - label: string; - categoryColors: Map; - valueFormatter: (value: number) => string; -} - -const ChartTooltip = ({ - active, - payload, - label, - categoryColors, - valueFormatter, -}: ChartTooltipProps) => { - if (active && payload) { - const filteredPayload = payload.filter((item: any) => item.type !== 'none'); - - return ( -
    -
    -

    - {label} -

    -
    - -
    - {filteredPayload.map( - ( - { value, name }: { value: number; name: string }, - index: number - ) => ( - - ) - )} -
    -
    - ); - } - return null; -}; - -//#region AreaChart - -interface ActiveDot { - index?: number; - dataKey?: string; -} - -type BaseEventProps = { - eventType: 'dot' | 'category'; - categoryClicked: string; - [key: string]: number | string; -}; - -type AreaChartEventProps = BaseEventProps | null | undefined; - -interface AreaChartProps extends React.HTMLAttributes { - data: Record[]; - index: string; - categories: string[]; - colors?: AvailableChartColorsKeys[]; - valueFormatter?: (value: number) => string; - startEndOnly?: boolean; - showXAxis?: boolean; - showYAxis?: boolean; - showGridLines?: boolean; - yAxisWidth?: number; - intervalType?: 'preserveStartEnd' | 'equidistantPreserveStart'; - showTooltip?: boolean; - showLegend?: boolean; - autoMinValue?: boolean; - minValue?: number; - maxValue?: number; - allowDecimals?: boolean; - onValueChange?: (value: AreaChartEventProps) => void; - enableLegendSlider?: boolean; - tickGap?: number; - connectNulls?: boolean; - xAxisLabel?: string; - yAxisLabel?: string; - type?: 'default' | 'stacked' | 'percent'; - legendPosition?: 'left' | 'center' | 'right'; - showPulsingDot?: boolean; -} - -const AreaChart = React.forwardRef( - (props, ref) => { - const { - data = [], - categories = [], - index, - colors = AvailableChartColors, - valueFormatter = (value: number) => value.toString(), - startEndOnly = false, - showXAxis = true, - showYAxis = true, - showGridLines = true, - yAxisWidth = 56, - intervalType = 'equidistantPreserveStart', - showTooltip = true, - showLegend = true, - autoMinValue = false, - minValue, - maxValue, - allowDecimals = true, - connectNulls = false, - className, - onValueChange, - enableLegendSlider = false, - tickGap = 5, - xAxisLabel, - yAxisLabel, - type = 'default', - legendPosition = 'right', - showPulsingDot = false, - ...other - } = props; - const paddingValue = !showXAxis && !showYAxis ? 0 : 20; - const [legendHeight, setLegendHeight] = React.useState(60); - const [activeDot, setActiveDot] = React.useState( - undefined - ); - const [activeLegend, setActiveLegend] = React.useState( - undefined - ); - const categoryColors = constructCategoryColors(categories, colors); - - const yAxisDomain = getYAxisDomain(autoMinValue, minValue, maxValue); - const hasOnValueChange = !!onValueChange; - const stacked = type === 'stacked' || type === 'percent'; - function valueToPercent(value: number) { - return `${(value * 100).toFixed(0)}%`; - } - - function onDotClick(itemData: any, event: React.MouseEvent) { - event.stopPropagation(); - - if (!hasOnValueChange) return; - if ( - (itemData.index === activeDot?.index && - itemData.dataKey === activeDot?.dataKey) || - (hasOnlyOneValueForKey(data, itemData.dataKey) && - activeLegend && - activeLegend === itemData.dataKey) - ) { - setActiveLegend(undefined); - setActiveDot(undefined); - onValueChange?.(null); - } else { - setActiveLegend(itemData.dataKey); - setActiveDot({ - index: itemData.index, - dataKey: itemData.dataKey, - }); - onValueChange?.({ - eventType: 'dot', - categoryClicked: itemData.dataKey, - ...itemData.payload, - }); - } - } - - function onCategoryClick(dataKey: string) { - if (!hasOnValueChange) return; - if ( - (dataKey === activeLegend && !activeDot) || - (hasOnlyOneValueForKey(data, dataKey) && - activeDot && - activeDot.dataKey === dataKey) - ) { - setActiveLegend(undefined); - onValueChange?.(null); - } else { - setActiveLegend(dataKey); - onValueChange?.({ - eventType: 'category', - categoryClicked: dataKey, - }); - } - setActiveDot(undefined); - } - - // Custom pulsing dot component - const PulsingDot = ({ - cx, - cy, - color, - }: { - cx: number; - cy: number; - color: string; - }) => ( - - - - - ); - - return ( -
    - - { - setActiveDot(undefined); - setActiveLegend(undefined); - onValueChange?.(null); - } - : undefined - } - margin={{ - bottom: xAxisLabel ? 30 : undefined, - left: yAxisLabel ? 20 : undefined, - right: yAxisLabel ? 5 : undefined, - top: 5, - }} - stackOffset={type === 'percent' ? 'expand' : undefined} - > - {showGridLines ? ( - - ) : null} - - {xAxisLabel && ( - - )} - - - {yAxisLabel && ( - - )} - - - {showTooltip && ( - ( - - )} - /> - )} - {showLegend ? ( - - ChartLegend( - { payload }, - categoryColors, - setLegendHeight, - activeLegend, - hasOnValueChange - ? (clickedLegendItem: string) => - onCategoryClick(clickedLegendItem) - : undefined, - enableLegendSlider, - legendPosition, - yAxisWidth - ) - } - /> - ) : null} - {categories.map((category) => ( - - - - - - - ))} - {categories.map((category) => ( - { - const { - cx: cxCoord, - cy: cyCoord, - stroke, - strokeLinecap, - strokeLinejoin, - strokeWidth, - dataKey, - } = props; - return ( - onDotClick(props, event)} - /> - ); - }} - dot={(props: any) => { - const { - stroke, - strokeLinecap, - strokeLinejoin, - strokeWidth, - cx: cxCoord, - cy: cyCoord, - dataKey, - index, - } = props; - - if ( - (hasOnlyOneValueForKey(data, category) && - !( - activeDot || - (activeLegend && activeLegend !== category) - )) || - (activeDot?.index === index && - activeDot?.dataKey === category) - ) { - return ( - - ); - } - return ; - }} - key={category} - name={category} - type='bump' - dataKey={category} - stroke='' - strokeWidth={2} - strokeLinejoin='round' - strokeLinecap='round' - isAnimationActive={false} - connectNulls={connectNulls} - stackId={stacked ? 'stack' : undefined} - fill={`url(#${ - categoryColors.get(category) as AvailableChartColorsKeys - })`} - /> - ))} - - {/* Pulsing dots at the end of each line */} - {showPulsingDot && - categories.map((category) => { - const lastDataPoint = data[data.length - 1]; - const value = lastDataPoint?.[category]; - - // Skip if no value for this category in the last data point - if (value === undefined || value === null) return null; - - return ( - { - const { cx, cy } = props; - return ( - - - - - ); - }} - /> - ); - })} - - {/* hidden lines to increase clickable target area */} - {onValueChange - ? categories.map((category) => ( - { - event.stopPropagation(); - const { name } = props; - onCategoryClick(name); - }} - /> - )) - : null} - - -
    - ); - } -); - -AreaChart.displayName = 'AreaChart'; - -export { AreaChart, type AreaChartEventProps }; diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsx index a33710a..711a432 100644 --- a/packages/ui/src/components/badge.tsx +++ b/packages/ui/src/components/badge.tsx @@ -3,12 +3,10 @@ import React from 'react'; import { tv, type VariantProps } from 'tailwind-variants'; -import { cx } from '@/lib/utils'; +import { cx } from '../lib/utils'; const badgeVariants = tv({ - base: cx( - 'inline-flex items-center gap-x-1 whitespace-nowrap rounded-md px-2 py-0.5 text-xs' - ), + base: cx('inline-flex items-center gap-x-1 whitespace-nowrap rounded-md px-2 py-0.5 text-xs'), variants: { variant: { default: ['bg-primary text-primary-foreground', ''], @@ -30,11 +28,7 @@ interface BadgeProps const Badge = React.forwardRef( ({ className, variant, ...props }: BadgeProps, forwardedRef) => { return ( - + ); } ); diff --git a/packages/ui/src/components/barchart.tsx b/packages/ui/src/components/barchart.tsx deleted file mode 100644 index 6c7e916..0000000 --- a/packages/ui/src/components/barchart.tsx +++ /dev/null @@ -1,884 +0,0 @@ -// Tremor Raw BarChart [v0.2.0] - -'use client'; - -import React from 'react'; -import { RiArrowLeftSLine, RiArrowRightSLine } from '@remixicon/react'; -import { - Bar, - CartesianGrid, - Label, - BarChart as RechartsBarChart, - Legend as RechartsLegend, - ResponsiveContainer, - Tooltip, - XAxis, - YAxis, -} from 'recharts'; -import type { AxisDomain } from 'recharts/types/util/types'; - -import { - AvailableChartColors, - type AvailableChartColorsKeys, - constructCategoryColors, - getColorClassName, - getYAxisDomain, -} from '@/lib/chartUtils'; -import { useOnWindowResize } from '@/lib/useOnWindowResize'; -import { cx } from '@/lib/utils'; - -//#region Shape - -function deepEqual(obj1: T, obj2: T): boolean { - if (obj1 === obj2) return true; - - if ( - typeof obj1 !== 'object' || - typeof obj2 !== 'object' || - obj1 === null || - obj2 === null - ) { - return false; - } - - const keys1 = Object.keys(obj1) as Array; - const keys2 = Object.keys(obj2) as Array; - - if (keys1.length !== keys2.length) return false; - - for (const key of keys1) { - if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) return false; - } - - return true; -} - -const renderShape = ( - props: any, - activeBar: any | undefined, - activeLegend: string | undefined, - layout: string -) => { - const { fillOpacity, name, payload, value } = props; - let { x, width, y, height } = props; - - if (layout === 'horizontal' && height < 0) { - y += height; - height = Math.abs(height); // height must be a positive number - } else if (layout === 'vertical' && width < 0) { - x += width; - width = Math.abs(width); // width must be a positive number - } - - return ( - - ); -}; - -//#region Legend - -interface LegendItemProps { - name: string; - color: AvailableChartColorsKeys; - onClick?: (name: string, color: AvailableChartColorsKeys) => void; - activeLegend?: string; -} - -const LegendItem = ({ - name, - color, - onClick, - activeLegend, -}: LegendItemProps) => { - const hasOnValueChange = !!onClick; - return ( -
  • { - e.stopPropagation(); - onClick?.(name, color); - }} - > - -

    - {name} -

    -
  • - ); -}; - -interface ScrollButtonProps { - icon: React.ElementType; - onClick?: () => void; - disabled?: boolean; -} - -const ScrollButton = ({ icon, onClick, disabled }: ScrollButtonProps) => { - const Icon = icon; - const [isPressed, setIsPressed] = React.useState(false); - const intervalRef = React.useRef | undefined>( - undefined - ); - - React.useEffect(() => { - if (isPressed) { - intervalRef.current = setInterval(() => { - onClick?.(); - }, 300); - } else { - clearInterval(intervalRef.current); - } - return () => clearInterval(intervalRef.current); - }, [isPressed, onClick]); - - React.useEffect(() => { - if (disabled) { - clearInterval(intervalRef.current); - setIsPressed(false); - } - }, [disabled]); - - return ( - - ); -}; - -interface LegendProps extends React.OlHTMLAttributes { - categories: string[]; - colors?: AvailableChartColorsKeys[]; - onClickLegendItem?: (category: string, color: string) => void; - activeLegend?: string; - enableLegendSlider?: boolean; -} - -type HasScrollProps = { - left: boolean; - right: boolean; -}; - -const Legend = React.forwardRef((props, ref) => { - const { - categories, - colors = AvailableChartColors, - className, - onClickLegendItem, - activeLegend, - enableLegendSlider = false, - ...other - } = props; - const scrollableRef = React.useRef(null); - const scrollButtonsRef = React.useRef(null); - const [hasScroll, setHasScroll] = React.useState(null); - const [isKeyDowned, setIsKeyDowned] = React.useState(null); - const intervalRef = React.useRef | undefined>( - undefined - ); - - const checkScroll = React.useCallback(() => { - const scrollable = scrollableRef?.current; - if (!scrollable) return; - - const hasLeftScroll = scrollable.scrollLeft > 0; - const hasRightScroll = - scrollable.scrollWidth - scrollable.clientWidth > scrollable.scrollLeft; - - setHasScroll({ left: hasLeftScroll, right: hasRightScroll }); - }, [setHasScroll]); - - const scrollToTest = React.useCallback( - (direction: 'left' | 'right') => { - const element = scrollableRef?.current; - const scrollButtons = scrollButtonsRef?.current; - const scrollButtonsWith = scrollButtons?.clientWidth ?? 0; - const width = element?.clientWidth ?? 0; - - if (element && enableLegendSlider) { - element.scrollTo({ - left: - direction === 'left' - ? element.scrollLeft - width + scrollButtonsWith - : element.scrollLeft + width - scrollButtonsWith, - behavior: 'smooth', - }); - setTimeout(() => { - checkScroll(); - }, 400); - } - }, - [enableLegendSlider, checkScroll] - ); - - React.useEffect(() => { - const keyDownHandler = (key: string) => { - if (key === 'ArrowLeft') { - scrollToTest('left'); - } else if (key === 'ArrowRight') { - scrollToTest('right'); - } - }; - if (isKeyDowned) { - keyDownHandler(isKeyDowned); - intervalRef.current = setInterval(() => { - keyDownHandler(isKeyDowned); - }, 300); - } else { - clearInterval(intervalRef.current); - } - return () => clearInterval(intervalRef.current); - }, [isKeyDowned, scrollToTest]); - - const keyDown = (e: KeyboardEvent) => { - e.stopPropagation(); - if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { - e.preventDefault(); - setIsKeyDowned(e.key); - } - }; - const keyUp = (e: KeyboardEvent) => { - e.stopPropagation(); - setIsKeyDowned(null); - }; - - React.useEffect(() => { - const scrollable = scrollableRef?.current; - if (enableLegendSlider) { - checkScroll(); - scrollable?.addEventListener('keydown', keyDown); - scrollable?.addEventListener('keyup', keyUp); - } - - return () => { - scrollable?.removeEventListener('keydown', keyDown); - scrollable?.removeEventListener('keyup', keyUp); - }; - }, [checkScroll, enableLegendSlider]); - - return ( -
      -
      - {categories.map((category, index) => ( - - ))} -
      - {enableLegendSlider && (hasScroll?.right || hasScroll?.left) ? ( - <> -
      - { - setIsKeyDowned(null); - scrollToTest('left'); - }} - disabled={!hasScroll?.left} - /> - { - setIsKeyDowned(null); - scrollToTest('right'); - }} - disabled={!hasScroll?.right} - /> -
      - - ) : null} -
    - ); -}); - -Legend.displayName = 'Legend'; - -const ChartLegend = ( - { payload }: any, - categoryColors: Map, - setLegendHeight: React.Dispatch>, - activeLegend: string | undefined, - onClick?: (category: string, color: string) => void, - enableLegendSlider?: boolean, - legendPosition?: 'left' | 'center' | 'right', - yAxisWidth?: number -) => { - const legendRef = React.useRef(null); - - useOnWindowResize(() => { - const calculateHeight = (height: number | undefined) => - height ? Number(height) + 15 : 60; - setLegendHeight(calculateHeight(legendRef.current?.clientHeight)); - }); - - const filteredPayload = payload.filter((item: any) => item.type !== 'none'); - - return ( -
    - entry.value)} - colors={filteredPayload.map((entry: any) => - categoryColors.get(entry.value) - )} - onClickLegendItem={onClick} - activeLegend={activeLegend} - enableLegendSlider={enableLegendSlider} - /> -
    - ); -}; - -//#region Tooltip - -type TooltipProps = Pick; - -type PayloadItem = { - category: string; - value: number; - index: string; - color: AvailableChartColorsKeys; - type?: string; - payload: any; -}; - -interface ChartTooltipProps { - active: boolean | undefined; - payload: PayloadItem[]; - label: string; - valueFormatter: (value: number) => string; -} - -const ChartTooltip = ({ - active, - payload, - label, - valueFormatter, -}: ChartTooltipProps) => { - if (active && payload && payload.length) { - return ( -
    -
    -

    - {label} -

    -
    -
    - {payload.map(({ value, category, color }, index) => ( -
    -
    -
    -

    - {valueFormatter(value)} -

    -
    - ))} -
    -
    - ); - } - return null; -}; - -//#region BarChart - -type BaseEventProps = { - eventType: 'category' | 'bar'; - categoryClicked: string; - [key: string]: number | string; -}; - -type BarChartEventProps = BaseEventProps | null | undefined; - -interface BarChartProps extends React.HTMLAttributes { - data: Record[]; - index: string; - categories: string[]; - colors?: AvailableChartColorsKeys[]; - valueFormatter?: (value: number) => string; - startEndOnly?: boolean; - showXAxis?: boolean; - showYAxis?: boolean; - showGridLines?: boolean; - yAxisWidth?: number; - intervalType?: 'preserveStartEnd' | 'equidistantPreserveStart'; - showTooltip?: boolean; - showLegend?: boolean; - autoMinValue?: boolean; - minValue?: number; - maxValue?: number; - allowDecimals?: boolean; - onValueChange?: (value: BarChartEventProps) => void; - enableLegendSlider?: boolean; - tickGap?: number; - barCategoryGap?: string | number; - xAxisLabel?: string; - yAxisLabel?: string; - layout?: 'vertical' | 'horizontal'; - type?: 'default' | 'stacked' | 'percent'; - legendPosition?: 'left' | 'center' | 'right'; - tooltipCallback?: (tooltipCallbackContent: TooltipProps) => void; - customTooltip?: React.ComponentType; -} - -const BarChart = React.forwardRef( - (props, forwardedRef) => { - const { - data = [], - categories = [], - index, - colors = AvailableChartColors, - valueFormatter = (value: number) => value.toString(), - startEndOnly = false, - showXAxis = true, - showYAxis = true, - showGridLines = true, - yAxisWidth = 56, - intervalType = 'equidistantPreserveStart', - showTooltip = true, - showLegend = true, - autoMinValue = false, - minValue, - maxValue, - allowDecimals = true, - className, - onValueChange, - enableLegendSlider = false, - barCategoryGap, - tickGap = 5, - xAxisLabel, - yAxisLabel, - layout = 'horizontal', - type = 'default', - legendPosition = 'right', - tooltipCallback, - customTooltip, - ...other - } = props; - const CustomTooltip = customTooltip; - const paddingValue = - (!showXAxis && !showYAxis) || (startEndOnly && !showYAxis) ? 0 : 20; - const [legendHeight, setLegendHeight] = React.useState(60); - const [activeLegend, setActiveLegend] = React.useState( - undefined - ); - const categoryColors = constructCategoryColors(categories, colors); - const [activeBar, setActiveBar] = React.useState( - undefined - ); - const yAxisDomain = getYAxisDomain(autoMinValue, minValue, maxValue); - const hasOnValueChange = !!onValueChange; - const stacked = type === 'stacked' || type === 'percent'; - - const prevActiveRef = React.useRef(undefined); - const prevLabelRef = React.useRef(undefined); - - function valueToPercent(value: number) { - return `${(value * 100).toFixed(0)}%`; - } - - function onBarClick(data: any, _: any, event: React.MouseEvent) { - event.stopPropagation(); - if (!onValueChange) return; - if (deepEqual(activeBar, { ...data.payload, value: data.value })) { - setActiveLegend(undefined); - setActiveBar(undefined); - onValueChange?.(null); - } else { - setActiveLegend(data.tooltipPayload?.[0]?.dataKey); - setActiveBar({ - ...data.payload, - value: data.value, - }); - onValueChange?.({ - eventType: 'bar', - categoryClicked: data.tooltipPayload?.[0]?.dataKey, - ...data.payload, - }); - } - } - - function onCategoryClick(dataKey: string) { - if (!hasOnValueChange) return; - if (dataKey === activeLegend && !activeBar) { - setActiveLegend(undefined); - onValueChange?.(null); - } else { - setActiveLegend(dataKey); - onValueChange?.({ - eventType: 'category', - categoryClicked: dataKey, - }); - } - setActiveBar(undefined); - } - - return ( -
    - - { - setActiveBar(undefined); - setActiveLegend(undefined); - onValueChange?.(null); - } - : undefined - } - margin={{ - bottom: xAxisLabel ? 30 : undefined, - left: yAxisLabel ? 20 : undefined, - right: yAxisLabel ? 5 : undefined, - top: 5, - }} - stackOffset={type === 'percent' ? 'expand' : undefined} - layout={layout} - barCategoryGap={barCategoryGap} - > - {showGridLines ? ( - - ) : null} - - {xAxisLabel && ( - - )} - - - {yAxisLabel && ( - - )} - - { - const cleanPayload: TooltipProps['payload'] = payload - ? payload.map((item: any) => ({ - category: item.dataKey, - value: item.value, - index: item.payload[index], - color: categoryColors.get( - item.dataKey - ) as AvailableChartColorsKeys, - type: item.type, - payload: item.payload, - })) - : []; - - if ( - tooltipCallback && - (active !== prevActiveRef.current || - label !== prevLabelRef.current) - ) { - tooltipCallback({ active, payload: cleanPayload, label }); - prevActiveRef.current = active; - prevLabelRef.current = label; - } - - return showTooltip && active ? ( - CustomTooltip ? ( - - ) : ( - - ) - ) : null; - }} - /> - {showLegend ? ( - - ChartLegend( - { payload }, - categoryColors, - setLegendHeight, - activeLegend, - hasOnValueChange - ? (clickedLegendItem: string) => - onCategoryClick(clickedLegendItem) - : undefined, - enableLegendSlider, - legendPosition, - yAxisWidth - ) - } - iconType='square' - /> - ) : null} - {categories.map((category) => ( - - renderShape(props, activeBar, activeLegend, layout) - } - onClick={onBarClick} - /> - ))} - - -
    - ); - } -); - -BarChart.displayName = 'BarChart'; - -export { BarChart, type BarChartEventProps, type TooltipProps }; diff --git a/packages/ui/src/components/barlist.tsx b/packages/ui/src/components/barlist.tsx deleted file mode 100644 index 1c22af8..0000000 --- a/packages/ui/src/components/barlist.tsx +++ /dev/null @@ -1,174 +0,0 @@ -// Tremor Raw BarList [v0.1.0] - -import React from 'react'; - -import { cx, focusRing } from '@/lib/utils'; - -type Bar = T & { - key?: string; - href?: string; - value: number; - name: string; -}; - -interface BarListProps - extends React.HTMLAttributes { - data: Bar[]; - valueFormatter?: (value: number) => string; - showAnimation?: boolean; - onValueChange?: (payload: Bar) => void; - sortOrder?: 'ascending' | 'descending' | 'none'; - noHover?: boolean; -} - -function BarListInner( - { - data = [], - valueFormatter = (value) => value.toLocaleString(), - showAnimation = false, - onValueChange, - sortOrder = 'descending', - noHover = false, - className, - ...props - }: BarListProps, - forwardedRef: React.ForwardedRef -) { - const Component = onValueChange ? 'button' : 'div'; - const sortedData = React.useMemo(() => { - if (sortOrder === 'none') { - return data; - } - return [...data].sort((a, b) => { - return sortOrder === 'ascending' ? a.value - b.value : b.value - a.value; - }); - }, [data, sortOrder]); - - const widths = React.useMemo(() => { - const maxValue = Math.max(...sortedData.map((item) => item.value), 0); - return sortedData.map((item) => - item.value === 0 ? 0 : Math.max((item.value / maxValue) * 100, 2) - ); - }, [sortedData]); - - const rowHeight = 'h-8'; - - return ( -
    -
    - {sortedData.map((item, index) => ( - { - // onValueChange?.(item); - // }} - className={cx( - // base - 'relative h-8 group w-full rounded', - // focus - focusRing, - onValueChange - ? [ - '!-m-0 cursor-pointer', - // hover - !noHover ? 'hover:bg-gray-50 ' : '', - ] - : '' - )} - > -
    -
    -
    - {item.href ? ( - event.stopPropagation()} - > - {item.name} - - ) : ( -

    - {item.name} -

    - )} -
    -
    - - ))} -
    -
    - {sortedData.map((item, index) => ( -
    -

    - {valueFormatter(item.value)} -

    -
    - ))} -
    -
    - ); -} - -BarListInner.displayName = 'BarList'; - -const BarList = React.forwardRef(BarListInner) as ( - p: BarListProps & { ref?: React.ForwardedRef } -) => ReturnType; - -export { BarList, type BarListProps }; diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsx index 39211ea..44bc585 100644 --- a/packages/ui/src/components/button.tsx +++ b/packages/ui/src/components/button.tsx @@ -1,11 +1,11 @@ // Tremor Raw Button [v0.0.0] -import React from 'react'; import { Slot } from '@radix-ui/react-slot'; import { RemixiconComponentType, RiLoader2Fill } from '@remixicon/react'; +import React from 'react'; import { tv, type VariantProps } from 'tailwind-variants'; -import { cx, focusRing } from '@/lib/utils'; +import { cx, focusRing } from '../lib/utils'; const buttonVariants = tv({ base: [ diff --git a/packages/ui/src/components/card.tsx b/packages/ui/src/components/card.tsx index 26b647c..9792ec5 100644 --- a/packages/ui/src/components/card.tsx +++ b/packages/ui/src/components/card.tsx @@ -1,79 +1,55 @@ import * as React from 'react'; -import { cn } from '@/lib/utils'; - -const Card = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
    -)); +import { cn } from '../lib/utils'; + +const Card = React.forwardRef>( + ({ className, ...props }, ref) => ( +
    + ) +); Card.displayName = 'Card'; -const CardHeader = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
    -)); +const CardHeader = React.forwardRef>( + ({ className, ...props }, ref) => ( +
    + ) +); CardHeader.displayName = 'CardHeader'; -const CardTitle = React.forwardRef< - HTMLParagraphElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -

    -)); +const CardTitle = React.forwardRef>( + ({ className, ...props }, ref) => ( +

    + ) +); CardTitle.displayName = 'CardTitle'; const CardDescription = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( -

    +

    )); CardDescription.displayName = 'CardDescription'; -const CardContent = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -

    -)); +const CardContent = React.forwardRef>( + ({ className, ...props }, ref) => ( +
    + ) +); CardContent.displayName = 'CardContent'; -const CardFooter = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(({ className, ...props }, ref) => ( -
    -)); +const CardFooter = React.forwardRef>( + ({ className, ...props }, ref) => ( +
    + ) +); CardFooter.displayName = 'CardFooter'; -export { - Card, - CardHeader, - CardFooter, - CardTitle, - CardDescription, - CardContent, -}; +export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }; diff --git a/packages/ui/src/components/categorybarcard.tsx b/packages/ui/src/components/categorybarcard.tsx deleted file mode 100644 index f13ce90..0000000 --- a/packages/ui/src/components/categorybarcard.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import { cx } from '@/lib/utils'; -import { Badge } from './badge'; -import { type ReactNode } from 'react'; -import { SmallHeader } from '@/components/ui/heading'; - -export type CardProps = { - className?: string; - title: string; - change?: string | null; - value: string; - subtitle: string; - emptyText?: string | ReactNode; - // ctaDescription: string; - // ctaText: string; - // ctaLink: string | null; - data?: { - title: string; - value: string; - percentage: number; - color: string; - }[]; -}; - -export function CategoryBarCard({ - className, - title, - change, - value, - subtitle, - emptyText, - // ctaDescription, - // ctaText, - // ctaLink, - data, -}: CardProps) { - const emptyNode = - emptyText === undefined ? ( -
    -
    - ) : typeof emptyText !== 'string' ? ( - emptyText - ) : ( - {emptyText} - ); - - const isLoading = data === undefined; - const isEmpty = data && data.length === 0; - - return ( -
    -
    -
    - - {title} - -
    -

    - {value} - {change ? {change} : null} -

    -
    -

    {subtitle}

    -
    - {isLoading ? ( -
    - ) : isEmpty ? ( -
    - ) : ( - data.map((item) => ( -
    - )) - )} -
    -
    -
      - {isLoading ? ( -
    • -
    • - ) : isEmpty ? ( -
    • {emptyNode}
    • - ) : ( - data.map((item) => ( -
    • -
    • - )) - )} -
    -
    - {/*

    - {ctaDescription}{' '} - {ctaLink ? ( - - {ctaText} - - ) : ( - {ctaText} - )} -

    */} -
    - ); -} diff --git a/packages/ui/src/components/checkbox.tsx b/packages/ui/src/components/checkbox.tsx index 9021cef..c0189ff 100644 --- a/packages/ui/src/components/checkbox.tsx +++ b/packages/ui/src/components/checkbox.tsx @@ -1,9 +1,9 @@ // Tremor Checkbox [v1.0.0] -import React from 'react'; import * as CheckboxPrimitives from '@radix-ui/react-checkbox'; +import React from 'react'; -import { cx, focusRing } from '@/lib/utils'; +import { cx, focusRing } from '../lib/utils'; const Checkbox = React.forwardRef< React.ElementRef, @@ -35,10 +35,7 @@ const Checkbox = React.forwardRef< )} tremor-id='tremor-raw' > - + {checked === 'indeterminate' ? ( ); diff --git a/packages/ui/src/components/contextmenu.tsx b/packages/ui/src/components/contextmenu.tsx index b8eda23..278510a 100644 --- a/packages/ui/src/components/contextmenu.tsx +++ b/packages/ui/src/components/contextmenu.tsx @@ -1,10 +1,10 @@ 'use client'; -import * as React from 'react'; import * as ContextMenuPrimitive from '@radix-ui/react-context-menu'; import { RiArrowRightSLine, RiCheckLine, RiCircleFill } from '@remixicon/react'; +import * as React from 'react'; -import { cn } from '@/lib/utils'; +import { cn } from '../lib/utils'; const ContextMenu = ContextMenuPrimitive.Root; @@ -113,8 +113,7 @@ const ContextMenuCheckboxItem = React.forwardRef< {children} )); -ContextMenuCheckboxItem.displayName = - ContextMenuPrimitive.CheckboxItem.displayName; +ContextMenuCheckboxItem.displayName = ContextMenuPrimitive.CheckboxItem.displayName; const ContextMenuRadioItem = React.forwardRef< React.ElementRef, @@ -146,11 +145,7 @@ const ContextMenuLabel = React.forwardRef< >(({ className, inset, ...props }, ref) => ( )); @@ -168,16 +163,10 @@ const ContextMenuSeparator = React.forwardRef< )); ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName; -const ContextMenuShortcut = ({ - className, - ...props -}: React.HTMLAttributes) => { +const ContextMenuShortcut = ({ className, ...props }: React.HTMLAttributes) => { return ( ); diff --git a/packages/ui/src/components/datepicker.tsx b/packages/ui/src/components/datepicker.tsx index d29f240..dd561ac 100644 --- a/packages/ui/src/components/datepicker.tsx +++ b/packages/ui/src/components/datepicker.tsx @@ -21,7 +21,7 @@ // import { enUS } from 'date-fns/locale'; // import { tv, type VariantProps } from 'tailwind-variants'; -// import { cx, focusInput, focusRing, hasErrorInput } from '@/lib/utils'; +// import { cx, focusInput, focusRing, hasErrorInput } from '../lib/utils'; // import { Button } from './button'; // import { Calendar as CalendarPrimitive, type Matcher } from './calendar'; diff --git a/packages/ui/src/components/dialog.tsx b/packages/ui/src/components/dialog.tsx index 038f131..0377cb8 100644 --- a/packages/ui/src/components/dialog.tsx +++ b/packages/ui/src/components/dialog.tsx @@ -1,9 +1,9 @@ // Tremor Raw Dialog [v0.0.0] -import React from 'react'; import * as DialogPrimitives from '@radix-ui/react-dialog'; +import React from 'react'; -import { cx, focusRing } from '@/lib/utils'; +import { cx, focusRing } from '../lib/utils'; const Dialog = (props: React.ComponentPropsWithoutRef) => { return ; diff --git a/packages/ui/src/components/divider.tsx b/packages/ui/src/components/divider.tsx index 5d560ed..b729b4f 100644 --- a/packages/ui/src/components/divider.tsx +++ b/packages/ui/src/components/divider.tsx @@ -2,7 +2,7 @@ import React from 'react'; -import { cx } from '@/lib/utils'; +import { cx } from '../lib/utils'; interface DividerProps extends React.ComponentPropsWithoutRef<'div'> {} diff --git a/packages/ui/src/components/donutchart.tsx b/packages/ui/src/components/donutchart.tsx deleted file mode 100644 index 1203101..0000000 --- a/packages/ui/src/components/donutchart.tsx +++ /dev/null @@ -1,331 +0,0 @@ -// Tremor Raw DonutChart [v0.0.0] - -'use client'; - -import React from 'react'; -import { - Pie, - PieChart as ReChartsDonutChart, - ResponsiveContainer, - Sector, - Tooltip, -} from 'recharts'; - -import { - AvailableChartColors, - type AvailableChartColorsKeys, - constructCategoryColors, - getColorClassName, -} from '@/lib/chartUtils'; -import { cx } from '@/lib/utils'; - -const sumNumericArray = (arr: number[]): number => - arr.reduce((sum, num) => sum + num, 0); - -const parseData = ( - data: Record[], - categoryColors: Map, - category: string -) => - data.map((dataPoint) => ({ - ...dataPoint, - color: categoryColors.get(dataPoint[category]) || AvailableChartColors[0], - className: getColorClassName( - categoryColors.get(dataPoint[category]) || AvailableChartColors[0], - 'fill' - ), - })); - -const calculateDefaultLabel = (data: any[], valueKey: string): number => - sumNumericArray(data.map((dataPoint) => dataPoint[valueKey])); - -const parseLabelInput = ( - labelInput: string | undefined, - valueFormatter: (value: number) => string, - data: any[], - valueKey: string -): string => - labelInput || valueFormatter(calculateDefaultLabel(data, valueKey)); - -//#region Tooltip - -type TooltipProps = Pick; - -type PayloadItem = { - category: string; - value: number; - color: AvailableChartColorsKeys; -}; - -interface ChartTooltipProps { - active: boolean | undefined; - payload: PayloadItem[]; - valueFormatter: (value: number) => string; -} - -const ChartTooltip = ({ - active, - payload, - valueFormatter, -}: ChartTooltipProps) => { - if (active && payload && payload.length) { - return ( -
    -
    - {payload.map(({ value, category, color }, index) => ( -
    -
    -
    -

    - {valueFormatter(value)} -

    -
    - ))} -
    -
    - ); - } - return null; -}; - -const renderInactiveShape = (props: any) => { - const { cx, cy, innerRadius, outerRadius, startAngle, endAngle, className } = - props; - - return ( - - ); -}; - -type DonutChartVariant = 'donut' | 'pie'; - -type BaseEventProps = { - eventType: 'sector'; - categoryClicked: string; - [key: string]: number | string; -}; - -type DonutChartEventProps = BaseEventProps | null | undefined; - -interface DonutChartProps extends React.HTMLAttributes { - data: Record[]; - category: string; - value: string; - colors?: AvailableChartColorsKeys[]; - variant?: DonutChartVariant; - valueFormatter?: (value: number) => string; - label?: string; - showLabel?: boolean; - showTooltip?: boolean; - onValueChange?: (value: DonutChartEventProps) => void; - tooltipCallback?: (tooltipCallbackContent: TooltipProps) => void; - customTooltip?: React.ComponentType; -} - -const DonutChart = React.forwardRef( - ( - { - data = [], - value, - category, - colors = AvailableChartColors, - variant = 'donut', - valueFormatter = (value: number) => value.toString(), - label, - showLabel = false, - showTooltip = true, - onValueChange, - tooltipCallback, - customTooltip, - className, - ...other - }, - forwardedRef - ) => { - const CustomTooltip = customTooltip; - const [activeIndex, setActiveIndex] = React.useState( - undefined - ); - const isDonut = variant === 'donut'; - const parsedLabelInput = parseLabelInput( - label, - valueFormatter, - data, - value - ); - - const categories = Array.from(new Set(data.map((item) => item[category]))); - const categoryColors = constructCategoryColors(categories, colors); - - const prevActiveRef = React.useRef(undefined); - const prevCategoryRef = React.useRef(undefined); - - const handleShapeClick = ( - data: any, - index: number, - event: React.MouseEvent - ) => { - event.stopPropagation(); - if (!onValueChange) return; - - if (activeIndex === index) { - setActiveIndex(undefined); - onValueChange(null); - } else { - setActiveIndex(index); - onValueChange({ - eventType: 'sector', - categoryClicked: data.payload[category], - ...data.payload, - }); - } - }; - - return ( -
    - - { - setActiveIndex(undefined); - onValueChange(null); - } - : undefined - } - margin={{ top: 0, left: 0, right: 0, bottom: 0 }} - > - {showLabel && isDonut && ( - - {parsedLabelInput} - - )} - - {showTooltip && ( - { - const cleanPayload = payload - ? payload.map((item: any) => ({ - category: item.payload[category], - value: item.value, - color: categoryColors.get( - item.payload[category] - ) as AvailableChartColorsKeys, - })) - : []; - - const payloadCategory: string = cleanPayload[0]?.category; - - if ( - tooltipCallback && - (active !== prevActiveRef.current || - payloadCategory !== prevCategoryRef.current) - ) { - tooltipCallback({ - active, - payload: cleanPayload, - }); - prevActiveRef.current = active; - prevCategoryRef.current = payloadCategory; - } - - return showTooltip && active ? ( - CustomTooltip ? ( - - ) : ( - - ) - ) : null; - }} - /> - )} - - -
    - ); - } -); - -DonutChart.displayName = 'DonutChart'; - -export { DonutChart, type DonutChartEventProps, type TooltipProps }; diff --git a/packages/ui/src/components/drawer.tsx b/packages/ui/src/components/drawer.tsx index 25420d3..ed355ee 100644 --- a/packages/ui/src/components/drawer.tsx +++ b/packages/ui/src/components/drawer.tsx @@ -1,16 +1,14 @@ // Tremor Drawer [v0.0.1] -import * as React from 'react'; import * as DrawerPrimitives from '@radix-ui/react-dialog'; import { RiCloseLine } from '@remixicon/react'; +import * as React from 'react'; -import { cx, focusRing } from '@/lib/utils'; +import { cx, focusRing } from '../lib/utils'; import { Button } from './button'; -const Drawer = ( - props: React.ComponentPropsWithoutRef -) => { +const Drawer = (props: React.ComponentPropsWithoutRef) => { return ; }; Drawer.displayName = 'Drawer'; @@ -19,9 +17,7 @@ const DrawerTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => { - return ( - - ); + return ; }); DrawerTrigger.displayName = 'Drawer.Trigger'; @@ -29,9 +25,7 @@ const DrawerClose = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => { - return ( - - ); + return ; }); DrawerClose.displayName = 'Drawer.Close'; @@ -96,30 +90,24 @@ const DrawerContent = React.forwardRef< DrawerContent.displayName = 'DrawerContent'; -const DrawerHeader = React.forwardRef< - HTMLDivElement, - React.ComponentPropsWithoutRef<'div'> ->(({ children, className, ...props }, ref) => { - return ( -
    -
    - {children} +const DrawerHeader = React.forwardRef>( + ({ children, className, ...props }, ref) => { + return ( +
    +
    {children}
    + + +
    - - - -
    - ); -}); + ); + } +); DrawerHeader.displayName = 'Drawer.Header'; @@ -142,12 +130,11 @@ const DrawerTitle = React.forwardRef< DrawerTitle.displayName = 'DrawerTitle'; -const DrawerBody = React.forwardRef< - HTMLDivElement, - React.ComponentPropsWithoutRef<'div'> ->(({ className, ...props }, ref) => { - return
    ; -}); +const DrawerBody = React.forwardRef>( + ({ className, ...props }, ref) => { + return
    ; + } +); DrawerBody.displayName = 'Drawer.Body'; const DrawerDescription = React.forwardRef< @@ -165,10 +152,7 @@ const DrawerDescription = React.forwardRef< DrawerDescription.displayName = 'DrawerDescription'; -const DrawerFooter = ({ - className, - ...props -}: React.HTMLAttributes) => { +const DrawerFooter = ({ className, ...props }: React.HTMLAttributes) => { return (
    >( ( - { - className, - sideOffset = 8, - collisionPadding = 8, - align = 'center', - loop = true, - ...props - }, + { className, sideOffset = 8, collisionPadding = 8, align = 'center', loop = true, ...props }, forwardedRef ) => ( @@ -163,14 +156,8 @@ const DropdownMenuItem = React.forwardRef< {...props} > {children} - {hint && ( - {hint} - )} - {shortcut && ( - - {shortcut} - - )} + {hint && {hint}} + {shortcut && {shortcut}} )); DropdownMenuItem.displayName = 'DropdownMenuItem'; @@ -181,55 +168,39 @@ const DropdownMenuCheckboxItem = React.forwardRef< shortcut?: string; hint?: string; } ->( - ( - { className, hint, shortcut, children, checked, ...props }, - forwardedRef - ) => ( - - - - +>(({ className, hint, shortcut, children, checked, ...props }, forwardedRef) => ( + + + + + + {children} + {hint && {hint}} + {shortcut && ( + + {shortcut} - {children} - {hint && ( - - {hint} - - )} - {shortcut && ( - - {shortcut} - - )} - - ) -); + )} + +)); DropdownMenuCheckboxItem.displayName = 'DropdownMenuCheckboxItem'; const DropdownMenuRadioItem = React.forwardRef< @@ -267,17 +238,9 @@ const DropdownMenuRadioItem = React.forwardRef< /> {children} - {hint && ( - - {hint} - - )} + {hint && {hint}} {shortcut && ( - + {shortcut} )} diff --git a/packages/ui/src/components/gauge.tsx b/packages/ui/src/components/gauge.tsx index 32c7366..e059bac 100644 --- a/packages/ui/src/components/gauge.tsx +++ b/packages/ui/src/components/gauge.tsx @@ -4,7 +4,8 @@ * @credit-to https://gauge.onur.dev/ */ -import React, { useEffect, useState, type CSSProperties, type SVGProps } from 'react'; +// biome-ignore lint/correctness/noUnusedImports: needed for type +import React, { type CSSProperties, type SVGProps, useEffect, useState } from 'react'; import { calculatePrimaryOpacity, @@ -15,9 +16,9 @@ import { calculateSecondaryStroke, calculateSecondaryStrokeDasharray, calculateSecondaryTransform, - sizeConfig, type GaugeProps, -} from '@/lib/gaugeUtils'; + sizeConfig, +} from '../lib/gaugeUtils'; /** * Renders a circular gauge using SVG. Allows configuration of colors, stroke, and animations. @@ -152,7 +153,7 @@ export function Gauge({ style={{ userSelect: 'none' }} {...props} > - {/*secondary*/} + Gauge { className?: string; @@ -8,31 +8,19 @@ interface HeadingProps extends React.HTMLAttributes { const TinyHeader = React.forwardRef( ({ className, ...props }, forwardedRef) => ( -

    +

    ) ); const SmallHeader = React.forwardRef( ({ className, ...props }, forwardedRef) => ( -

    +

    ) ); const LargeHeader = React.forwardRef( ({ className, ...props }, forwardedRef) => ( -

    +

    ) ); diff --git a/packages/ui/src/components/input.tsx b/packages/ui/src/components/input.tsx index c9d06b8..211c8c9 100644 --- a/packages/ui/src/components/input.tsx +++ b/packages/ui/src/components/input.tsx @@ -1,10 +1,10 @@ // Tremor Raw Input [v1.0.0] -import React from 'react'; import { RiEyeFill, RiEyeOffFill, RiSearchLine } from '@remixicon/react'; +import React from 'react'; import { tv, type VariantProps } from 'tailwind-variants'; -import { cx, focusInput, focusRing, hasErrorInput } from '@/lib/utils'; +import { cx, focusInput, focusRing, hasErrorInput } from '../lib/utils'; const inputStyles = tv({ base: [ @@ -54,14 +54,7 @@ interface InputProps const Input = React.forwardRef( ( - { - className, - inputClassName, - hasError, - enableStepper, - type, - ...props - }: InputProps, + { className, inputClassName, hasError, enableStepper, type, ...props }: InputProps, forwardedRef ) => { const [typeState, setTypeState] = React.useState(type); @@ -93,17 +86,12 @@ const Input = React.forwardRef( 'text-stone-400' )} > -

    )} {isPassword && (
    - ); -}; - -interface LegendProps extends React.OlHTMLAttributes { - categories: string[]; - colors?: AvailableChartColorsKeys[]; - onClickLegendItem?: (category: string, color: string) => void; - activeLegend?: string; - enableLegendSlider?: boolean; -} - -type HasScrollProps = { - left: boolean; - right: boolean; -}; - -const Legend = React.forwardRef((props, ref) => { - const { - categories, - colors = AvailableChartColors, - className, - onClickLegendItem, - activeLegend, - enableLegendSlider = false, - ...other - } = props; - const scrollableRef = React.useRef(null); - const [hasScroll, setHasScroll] = React.useState(null); - const [isKeyDowned, setIsKeyDowned] = React.useState(null); - const intervalRef = React.useRef(null); - - const checkScroll = React.useCallback(() => { - const scrollable = scrollableRef?.current; - if (!scrollable) return; - - const hasLeftScroll = scrollable.scrollLeft > 0; - const hasRightScroll = - scrollable.scrollWidth - scrollable.clientWidth > scrollable.scrollLeft; - - setHasScroll({ left: hasLeftScroll, right: hasRightScroll }); - }, [setHasScroll]); - - const scrollToTest = React.useCallback( - (direction: 'left' | 'right') => { - const element = scrollableRef?.current; - const width = element?.clientWidth ?? 0; - - if (element && enableLegendSlider) { - element.scrollTo({ - left: - direction === 'left' - ? element.scrollLeft - width - : element.scrollLeft + width, - behavior: 'smooth', - }); - setTimeout(() => { - checkScroll(); - }, 400); - } - }, - [enableLegendSlider, checkScroll] - ); - - React.useEffect(() => { - const keyDownHandler = (key: string) => { - if (key === 'ArrowLeft') { - scrollToTest('left'); - } else if (key === 'ArrowRight') { - scrollToTest('right'); - } - }; - if (isKeyDowned) { - keyDownHandler(isKeyDowned); - intervalRef.current = setInterval(() => { - keyDownHandler(isKeyDowned); - }, 300); - } else { - clearInterval(intervalRef.current as NodeJS.Timeout); - } - return () => clearInterval(intervalRef.current as NodeJS.Timeout); - }, [isKeyDowned, scrollToTest]); - - const keyDown = (e: KeyboardEvent) => { - e.stopPropagation(); - if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { - e.preventDefault(); - setIsKeyDowned(e.key); - } - }; - const keyUp = (e: KeyboardEvent) => { - e.stopPropagation(); - setIsKeyDowned(null); - }; - - React.useEffect(() => { - const scrollable = scrollableRef?.current; - if (enableLegendSlider) { - checkScroll(); - scrollable?.addEventListener('keydown', keyDown); - scrollable?.addEventListener('keyup', keyUp); - } - - return () => { - scrollable?.removeEventListener('keydown', keyDown); - scrollable?.removeEventListener('keyup', keyUp); - }; - }, [checkScroll, enableLegendSlider]); - - return ( -
      -
      - {categories.map((category, index) => ( - - ))} -
      - {enableLegendSlider && (hasScroll?.right || hasScroll?.left) ? ( - <> -
      - { - setIsKeyDowned(null); - scrollToTest('left'); - }} - disabled={!hasScroll?.left} - /> - { - setIsKeyDowned(null); - scrollToTest('right'); - }} - disabled={!hasScroll?.right} - /> -
      - - ) : null} -
    - ); -}); - -Legend.displayName = 'Legend'; - -const ChartLegend = ( - { payload }: any, - categoryColors: Map, - setLegendHeight: React.Dispatch>, - activeLegend: string | undefined, - onClick?: (category: string, color: string) => void, - enableLegendSlider?: boolean, - legendPosition?: 'left' | 'center' | 'right', - yAxisWidth?: number -) => { - const legendRef = React.useRef(null); - - useOnWindowResize(() => { - const calculateHeight = (height: number | undefined) => - height ? Number(height) + 15 : 60; - setLegendHeight(calculateHeight(legendRef.current?.clientHeight)); - }); - - const filteredPayload = payload.filter((item: any) => item.type !== 'none'); - - const paddingLeft = - legendPosition === 'left' && yAxisWidth ? yAxisWidth - 8 : 0; - - return ( -
    - entry.value)} - colors={filteredPayload.map((entry: any) => - categoryColors.get(entry.value) - )} - onClickLegendItem={onClick} - activeLegend={activeLegend} - enableLegendSlider={enableLegendSlider} - /> -
    - ); -}; - -//#region Tooltip - -interface ChartTooltipRowProps { - value: string; - name: string; - color: string; -} - -const ChartTooltipRow = ({ value, name, color }: ChartTooltipRowProps) => ( -
    -
    -
    -

    - {value} -

    -
    -); - -interface ChartTooltipProps { - active: boolean | undefined; - payload: any; - label: string; - categoryColors: Map; - valueFormatter: (value: number) => string; -} - -const ChartTooltip = ({ - active, - payload, - label, - categoryColors, - valueFormatter, -}: ChartTooltipProps) => { - if (active && payload) { - const filteredPayload = payload.filter((item: any) => item.type !== 'none'); - - return ( -
    -
    -

    - {label} -

    -
    - -
    - {filteredPayload.map( - ( - { value, name }: { value: number; name: string }, - index: number - ) => ( - - ) - )} -
    -
    - ); - } - return null; -}; - -//#region LineChart - -interface ActiveDot { - index?: number; - dataKey?: string; -} - -type BaseEventProps = { - eventType: 'dot' | 'category'; - categoryClicked: string; - [key: string]: number | string; -}; - -type LineChartEventProps = BaseEventProps | null | undefined; - -interface LineChartProps extends React.HTMLAttributes { - data: Record[]; - index: string; - categories: string[]; - colors?: AvailableChartColorsKeys[]; - valueFormatter?: (value: number) => string; - startEndOnly?: boolean; - showXAxis?: boolean; - showYAxis?: boolean; - showGridLines?: boolean; - yAxisWidth?: number; - intervalType?: 'preserveStartEnd' | 'equidistantPreserveStart'; - showTooltip?: boolean; - hideTotalTooltip?: boolean; - showLegend?: boolean; - autoMinValue?: boolean; - minValue?: number; - maxValue?: number; - allowDecimals?: boolean; - onValueChange?: (value: LineChartEventProps) => void; - enableLegendSlider?: boolean; - tickGap?: number; - connectNulls?: boolean; - xAxisLabel?: string; - yAxisLabel?: string; - legendPosition?: 'left' | 'center' | 'right'; -} - -const LineChart = React.forwardRef( - (props, ref) => { - const { - data = [], - categories = [], - index, - colors = AvailableChartColors, - valueFormatter = (value: number) => value.toString(), - startEndOnly = false, - showXAxis = true, - showYAxis = true, - showGridLines = true, - yAxisWidth = 56, - intervalType = 'equidistantPreserveStart', - showTooltip = true, - hideTotalTooltip = false, - showLegend = true, - autoMinValue = false, - minValue, - maxValue, - allowDecimals = true, - connectNulls = false, - className, - onValueChange, - enableLegendSlider = false, - tickGap = 5, - xAxisLabel, - yAxisLabel, - legendPosition = 'right', - ...other - } = props; - const paddingValue = !showXAxis && !showYAxis ? 0 : 20; - const [legendHeight, setLegendHeight] = React.useState(60); - const [activeDot, setActiveDot] = React.useState( - undefined - ); - const [activeLegend, setActiveLegend] = React.useState( - undefined - ); - const categoryColors = constructCategoryColors(categories, colors); - - const yAxisDomain = getYAxisDomain(autoMinValue, minValue, maxValue); - const hasOnValueChange = !!onValueChange; - - function onDotClick(itemData: any, event: React.MouseEvent) { - event.stopPropagation(); - - if (!hasOnValueChange) return; - if ( - (itemData.index === activeDot?.index && - itemData.dataKey === activeDot?.dataKey) || - (hasOnlyOneValueForKey(data, itemData.dataKey) && - activeLegend && - activeLegend === itemData.dataKey) - ) { - setActiveLegend(undefined); - setActiveDot(undefined); - onValueChange?.(null); - } else { - setActiveLegend(itemData.dataKey); - setActiveDot({ - index: itemData.index, - dataKey: itemData.dataKey, - }); - onValueChange?.({ - eventType: 'dot', - categoryClicked: itemData.dataKey, - ...itemData.payload, - }); - } - } - - function onCategoryClick(dataKey: string) { - if (!hasOnValueChange) return; - if ( - (dataKey === activeLegend && !activeDot) || - (hasOnlyOneValueForKey(data, dataKey) && - activeDot && - activeDot.dataKey === dataKey) - ) { - setActiveLegend(undefined); - onValueChange?.(null); - } else { - setActiveLegend(dataKey); - onValueChange?.({ - eventType: 'category', - categoryClicked: dataKey, - }); - } - setActiveDot(undefined); - } - - return ( -
    - - { - setActiveDot(undefined); - setActiveLegend(undefined); - onValueChange?.(null); - } - : undefined - } - margin={{ - bottom: xAxisLabel ? 30 : undefined, - left: yAxisLabel ? 20 : undefined, - right: yAxisLabel ? 5 : undefined, - top: 5, - }} - > - {showGridLines ? ( - - ) : null} - - {xAxisLabel && ( - - )} - - - {yAxisLabel && ( - - )} - - - {hideTotalTooltip ? null : ( - ( - - ) - ) : ( - <> - ) - } - /> - )} - {showLegend ? ( - - ChartLegend( - { payload }, - categoryColors, - setLegendHeight, - activeLegend, - hasOnValueChange - ? (clickedLegendItem: string) => - onCategoryClick(clickedLegendItem) - : undefined, - enableLegendSlider, - legendPosition, - yAxisWidth - ) - } - /> - ) : null} - {categories.map((category) => ( - { - const { - cx: cxCoord, - cy: cyCoord, - stroke, - strokeLinecap, - strokeLinejoin, - strokeWidth, - dataKey, - } = props; - return ( - onDotClick(props, event)} - /> - ); - }} - dot={(props: any) => { - const { - stroke, - strokeLinecap, - strokeLinejoin, - strokeWidth, - cx: cxCoord, - cy: cyCoord, - dataKey, - index, - } = props; - - if ( - (hasOnlyOneValueForKey(data, category) && - !( - activeDot || - (activeLegend && activeLegend !== category) - )) || - (activeDot?.index === index && - activeDot?.dataKey === category) - ) { - return ( - - ); - } - return ; - }} - key={category} - name={category} - type='linear' - dataKey={category} - stroke='' - strokeWidth={2} - strokeLinejoin='round' - strokeLinecap='round' - isAnimationActive={false} - connectNulls={connectNulls} - /> - ))} - {/* hidden lines to increase clickable target area */} - {onValueChange - ? categories.map((category) => ( - { - event.stopPropagation(); - const { name } = props; - onCategoryClick(name); - }} - /> - )) - : null} - - -
    - ); - } -); - -LineChart.displayName = 'LineChart'; - -export { LineChart, type LineChartEventProps }; diff --git a/packages/ui/src/components/navigationmenu.tsx b/packages/ui/src/components/navigationmenu.tsx index ddd664e..704ed68 100644 --- a/packages/ui/src/components/navigationmenu.tsx +++ b/packages/ui/src/components/navigationmenu.tsx @@ -1,8 +1,7 @@ -import * as React from 'react'; import * as NavigationMenuPrimitive from '@radix-ui/react-navigation-menu'; - import { RiArrowDownSLine } from '@remixicon/react'; -import { cn } from '@/lib/utils'; +import * as React from 'react'; +import { cn } from '../lib/utils'; const NavigationMenu = React.forwardRef< React.ElementRef, @@ -10,10 +9,7 @@ const NavigationMenu = React.forwardRef< >(({ className, children, ...props }, ref) => ( {children} @@ -28,10 +24,7 @@ const NavigationMenuList = React.forwardRef< >(({ className, ...props }, ref) => ( )); @@ -93,8 +86,7 @@ const NavigationMenuViewport = React.forwardRef< />
    )); -NavigationMenuViewport.displayName = - NavigationMenuPrimitive.Viewport.displayName; +NavigationMenuViewport.displayName = NavigationMenuPrimitive.Viewport.displayName; const NavigationMenuIndicator = React.forwardRef< React.ElementRef, @@ -111,8 +103,7 @@ const NavigationMenuIndicator = React.forwardRef<
    )); -NavigationMenuIndicator.displayName = - NavigationMenuPrimitive.Indicator.displayName; +NavigationMenuIndicator.displayName = NavigationMenuPrimitive.Indicator.displayName; export { navigationMenuTriggerStyle, diff --git a/packages/ui/src/components/popover.tsx b/packages/ui/src/components/popover.tsx index f224d5e..5fd980b 100644 --- a/packages/ui/src/components/popover.tsx +++ b/packages/ui/src/components/popover.tsx @@ -1,9 +1,9 @@ 'use client'; -import * as React from 'react'; import * as PopoverPrimitive from '@radix-ui/react-popover'; +import * as React from 'react'; -import { cn } from '@/lib/utils'; +import { cn } from '../lib/utils'; const Popover = PopoverPrimitive.Root; diff --git a/packages/ui/src/components/progressbar.tsx b/packages/ui/src/components/progressbar.tsx index 6adc452..4a4bfe7 100644 --- a/packages/ui/src/components/progressbar.tsx +++ b/packages/ui/src/components/progressbar.tsx @@ -3,7 +3,7 @@ import React from 'react'; import { tv, type VariantProps } from 'tailwind-variants'; -import { cx } from '@/lib/utils'; +import { cx } from '../lib/utils'; const progressBarVariants = tv({ slots: { @@ -64,26 +64,13 @@ const ProgressBar = React.forwardRef( const safeValue = Math.min(max, Math.max(value, 0)); const { background, bar } = progressBarVariants({ variant }); return ( -
    -
    +
    +
    ( const { background, circle } = progressCircleVariants({ variant }); return ( - <> -
    - +
    + + Progress Circle + + {safeValue >= 0 ? ( - {safeValue >= 0 ? ( - - ) : null} - -
    - {children} -
    -
    - + ) : null} + +
    {children}
    +
    ); } ); diff --git a/packages/ui/src/components/radiogroup.tsx b/packages/ui/src/components/radiogroup.tsx index b104a4d..324c408 100644 --- a/packages/ui/src/components/radiogroup.tsx +++ b/packages/ui/src/components/radiogroup.tsx @@ -1,9 +1,9 @@ // Tremor RadioGroup [v0.0.2] -import React from 'react'; import * as RadioGroupPrimitives from '@radix-ui/react-radio-group'; +import React from 'react'; -import { cx, focusRing } from '@/lib/utils'; +import { cx, focusRing } from '../lib/utils'; const RadioGroup = React.forwardRef< React.ElementRef, diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsx index 105f6fc..2cee292 100644 --- a/packages/ui/src/components/select.tsx +++ b/packages/ui/src/components/select.tsx @@ -1,6 +1,5 @@ // Tremor Raw Select [v0.0.0] -import React from 'react'; import * as SelectPrimitives from '@radix-ui/react-select'; import { RiArrowDownSLine, @@ -8,8 +7,9 @@ import { RiCheckLine, RiExpandUpDownLine, } from '@remixicon/react'; +import React from 'react'; -import { cx, focusInput, hasErrorInput } from '@/lib/utils'; +import { cx, focusInput, hasErrorInput } from '../lib/utils'; const Select = SelectPrimitives.Root; Select.displayName = 'Select'; @@ -52,12 +52,7 @@ const SelectTrigger = React.forwardRef< return ( {children} @@ -85,10 +80,7 @@ const SelectScrollUpButton = React.forwardRef< >(({ className, ...props }, forwardedRef) => (