From 7db579b0ebb61566c590596849af7c25d980d550 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Sun, 10 Aug 2025 14:33:27 +0800 Subject: [PATCH 01/17] Adds display name system & nearest airport API Introduces full name, display mode, and cached display name to personalize and standardize user identity while removing client-supplied contribution display names to prevent spoofing and eliminate duplication. Centralizes display name computation in auth with selectable modes and automatic backfill from external profile data. Reworks contributions and leaderboards to derive names directly from the user record for consistency. Adds high-performance nearest-airport lookup with bounding box prefilter, cached bucketed queries, and precise distance refinement for scalable geospatial queries. Extends division management with rename and delete actions and surfaces member display names. Captures first/last name from external API and enriches account responses; updates user listings accordingly. Removes obsolete display name endpoints and legacy update logic for a cleaner, more authoritative model. --- openapi.json | 3995 ++++++------ schema.sql | 4 +- src/index.ts | 266 +- src/services/airport.ts | 52 + src/services/auth.ts | 68 +- src/services/contributions.ts | 61 +- src/services/divisions.ts | 32 +- src/services/users.ts | 18 +- src/services/vatsim.ts | 2 + src/types.ts | 5 + worker-configuration.d.ts | 10674 ++++++++++++++++++-------------- 11 files changed, 8754 insertions(+), 6423 deletions(-) diff --git a/openapi.json b/openapi.json index efbb193..4153e52 100644 --- a/openapi.json +++ b/openapi.json @@ -1,1833 +1,2164 @@ { - "openapi": "3.0.4", - "info": { - "title": "BARS Core API", - "version": "2.0.0", - "description": "API documentation for BARS Core", - "contact": { - "name": "BARS Support", - "email": "support@stopbars.com", - "url": "https://stopbars.com/support" - } - }, - "externalDocs": { - "description": "Find more info here", - "url": "https://docs.stopbars.com" - }, - "servers": [ - { - "url": "https://v2.stopbars.com", - "description": "Production" - }, - { - "url": "http://localhost:8787", - "description": "Local development (wrangler dev)" - } - ], - "tags": [ - { - "name": "RealTime", - "description": "WebSocket connection and real-time state interaction endpoints." - }, - { - "name": "State", - "description": "Endpoints for retrieving current system or airport lighting/network state." - }, - { - "name": "Auth", - "description": "Authentication, account management, and API key lifecycle." - }, - { - "name": "Airports", - "description": "Lookup and metadata endpoints for airports." - }, - { - "name": "Divisions", - "description": "Division management, membership, and associated airport access." - }, - { - "name": "Points", - "description": "Creation and management of lighting/navigation point data." - }, - { - "name": "Support", - "description": "Utilities for generating light support / BARS XML artifacts." - }, - { - "name": "NOTAM", - "description": "Global NOTAM retrieval and (staff) updates." - }, - { - "name": "Contributions", - "description": "Community lighting package submission, review, and leaderboard." - }, - { - "name": "Staff", - "description": "Restricted staff-only operational and moderation endpoints (hidden from public docs)." - }, - { - "name": "CDN", - "description": "File storage, upload, listing, and deletion via CDN-backed storage." - }, - { - "name": "EuroScope", - "description": "EuroScope sector file upload, listing, and permission checks by ICAO." - }, - { - "name": "Cache", - "description": "Administrative cache management operations." - }, - { - "name": "GitHub", - "description": "Repository contributor information." - }, - { - "name": "System", - "description": "System health and OpenAPI specification discovery." - } - ], - "paths": { - "/connect": { - "get": { - "summary": "Establish a WebSocket for an airport", - "tags": ["RealTime"], - "description": "Performs a WebSocket upgrade to stream real-time airport state. Requires:\n- GET with `Upgrade: websocket`\n- `airport` (ICAO, 4 chars) & `key` (API key) query params\nThe API key is forwarded as a Bearer token to the airport's Durable Object for auth.\n", - "parameters": [ - { - "in": "query", - "name": "airport", - "required": true, - "description": "Airport ICAO (4 alphanumeric characters)", - "schema": { - "type": "string", - "minLength": 4, - "maxLength": 4, - "pattern": "^[A-Z0-9]{4}$" - } - }, - { - "in": "query", - "name": "key", - "required": true, - "description": "User API key", - "schema": { - "type": "string" - } - } - ], - "responses": { - "101": { - "description": "WebSocket upgrade accepted" - }, - "400": { - "description": "Missing/invalid params or not a WebSocket upgrade" - }, - "401": { - "description": "API key rejected" - } - } - } - }, - "/state": { - "get": { - "summary": "Get current lighting/network state", - "tags": ["State"], - "description": "Retrieves real-time state for a specific airport or all active airports.", - "parameters": [ - { - "in": "query", - "name": "airport", - "required": true, - "description": "ICAO code of airport or 'all' for every active airport", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "State information returned" - }, - "400": { - "description": "Missing or invalid airport parameter" - } - } - } - }, - "/auth/vatsim/callback": { - "get": { - "summary": "VATSIM OAuth callback", - "tags": ["Auth"], - "description": "Exchanges authorization code for a VATSIM token and redirects to frontend with token.", - "parameters": [ - { - "in": "query", - "name": "code", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "302": { - "description": "Redirect to application with token or error" - }, - "400": { - "description": "Missing code parameter" - } - } - } - }, - "/auth/account": { - "get": { - "summary": "Get authenticated account information", - "tags": ["Auth"], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Account found" - }, - "401": { - "description": "Missing or invalid token" - }, - "404": { - "description": "User not found" - } - } - } - }, - "/auth/regenerate-api-key": { - "post": { - "summary": "Regenerate API key", - "tags": ["Auth"], - "description": "Generates a new API key for the authenticated user (24h cooldown).", - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Key regenerated" - }, - "401": { - "description": "Unauthorized" - }, - "404": { - "description": "User not found" - }, - "429": { - "description": "Rate limited (cooldown not elapsed)" - } - } - } - }, - "/auth/delete": { - "delete": { - "summary": "Delete current user account", - "tags": ["Auth"], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "204": { - "description": "Account deleted" - }, - "401": { - "description": "Unauthorized" - }, - "404": { - "description": "User not found" - } - } - } - }, - "/auth/is-staff": { - "get": { - "x-hidden": true, - "summary": "Check staff status", - "tags": ["Staff"], - "security": [ - { - "ApiKeyAuth": [] - } - ], - "responses": { - "200": { - "description": "Staff status returned" - }, - "401": { - "description": "Unauthorized" - } - } - } - }, - "/airports": { - "get": { - "summary": "Get airport data", - "tags": ["Airports"], - "description": "Fetch airport(s) by ICAO(s) or by continent.", - "parameters": [ - { - "in": "query", - "name": "icao", - "required": false, - "description": "Single ICAO or comma-separated list", - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "continent", - "required": false, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Airport data returned" - }, - "400": { - "description": "Invalid parameters" - }, - "404": { - "description": "Airport not found" - } - } - } - }, - "/divisions": { - "get": { - "summary": "List all divisions", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Divisions returned" - }, - "401": { - "description": "Unauthorized" - } - } - }, - "post": { - "x-hidden": true, - "summary": "Create a new division", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["name", "headVatsimId"], - "properties": { - "name": { - "type": "string" - }, - "headVatsimId": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Division created" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/divisions/user": { - "get": { - "summary": "Get divisions for current user", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "User divisions returned" - } - } - } - }, - "/divisions/{id}": { - "get": { - "summary": "Get division details", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "Division returned" - }, - "404": { - "description": "Division not found" - } - } - } - }, - "/divisions/{id}/members": { - "get": { - "summary": "List division members", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "Members listed" - }, - "404": { - "description": "Division not found" - } - } - }, - "post": { - "x-hidden": true, - "summary": "Add member to division", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["vatsimId", "role"], - "properties": { - "vatsimId": { - "type": "string" - }, - "role": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Member added" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/divisions/{id}/members/{vatsimId}": { - "delete": { - "x-hidden": true, - "summary": "Remove member from division", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - }, - { - "in": "path", - "name": "vatsimId", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "204": { - "description": "Member removed" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/divisions/{id}/airports": { - "get": { - "summary": "List division airports", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "Airports listed" - }, - "404": { - "description": "Division not found" - } - } - }, - "post": { - "x-hidden": true, - "summary": "Request airport addition to division", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["icao"], - "properties": { - "icao": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Airport request created" - }, - "404": { - "description": "Division not found" - } - } - } - }, - "/divisions/{id}/airports/{airportId}/approve": { - "post": { - "x-hidden": true, - "summary": "Approve or reject airport request", - "tags": ["Divisions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - }, - { - "in": "path", - "name": "airportId", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["approved"], - "properties": { - "approved": { - "type": "boolean" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Airport approval processed" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/airports/{icao}/points": { - "get": { - "summary": "List lighting/navigation points for airport", - "tags": ["Points"], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string", - "minLength": 4, - "maxLength": 4 - } - } - ], - "responses": { - "200": { - "description": "Points returned" - }, - "400": { - "description": "Invalid ICAO" - } - } - }, - "post": { - "x-hidden": true, - "summary": "Create a single point", - "tags": ["Points"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PointData" - } - } - } - }, - "responses": { - "201": { - "description": "Point created" - }, - "401": { - "description": "Unauthorized" - } - } - } - }, - "/airports/{icao}/points/batch": { - "post": { - "x-hidden": true, - "summary": "Apply a batch point changeset", - "tags": ["Points"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PointChangeset" - } - } - } - }, - "responses": { - "201": { - "description": "Changeset applied" - } - } - } - }, - "/airports/{icao}/points/{id}": { - "put": { - "x-hidden": true, - "summary": "Update a point", - "tags": ["Points"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object" - } - } - } - }, - "responses": { - "200": { - "description": "Point updated" - } - } - }, - "delete": { - "x-hidden": true, - "summary": "Delete a point", - "tags": ["Points"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "204": { - "description": "Deleted" - } - } - } - }, - "/points/{id}": { - "get": { - "summary": "Get a single point by ID", - "tags": ["Points"], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Point found" - }, - "404": { - "description": "Not found" - } - } - } - }, - "/points": { - "get": { - "summary": "Get multiple points by IDs", - "tags": ["Points"], - "parameters": [ - { - "in": "query", - "name": "ids", - "required": true, - "description": "Comma-separated list of point IDs (max 100)", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Points returned" - }, - "400": { - "description": "Validation error" - } - } - } - }, - "/supports/generate": { - "post": { - "summary": "Generate Light Supports and BARS XML", - "tags": ["Support"], - "description": "Upload raw XML and generate both light supports XML and processed BARS XML.", - "requestBody": { - "required": true, - "content": { - "multipart/form-data": { - "schema": { - "type": "object", - "required": ["xmlFile", "icao"], - "properties": { - "xmlFile": { - "type": "string", - "format": "binary" - }, - "icao": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Generated XML returned" - }, - "400": { - "description": "Validation error" - } - } - } - }, - "/notam": { - "get": { - "summary": "Get global NOTAM", - "tags": ["NOTAM"], - "responses": { - "200": { - "description": "Current NOTAM returned" - } - } - }, - "put": { - "x-hidden": true, - "summary": "Update global NOTAM", - "tags": ["NOTAM"], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["content"], - "properties": { - "content": { - "type": "string" - }, - "type": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "NOTAM updated" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/staff/users": { - "get": { - "x-hidden": true, - "summary": "List users (staff only)", - "tags": ["Staff"], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Users returned" - }, - "401": { - "description": "Unauthorized" - } - } - } - }, - "/staff/users/search": { - "get": { - "x-hidden": true, - "summary": "Search users (staff only)", - "tags": ["Staff"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "query", - "name": "q", - "required": true, - "schema": { - "type": "string", - "minLength": 3 - } - } - ], - "responses": { - "200": { - "description": "Search results returned" - }, - "400": { - "description": "Invalid query" - } - } - } - }, - "/staff/users/refresh-api-token": { - "post": { - "x-hidden": true, - "summary": "Refresh a user's API token (staff only)", - "tags": ["Staff"], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["vatsimId"], - "properties": { - "vatsimId": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Token refreshed" - } - } - } - }, - "/staff/users/{id}": { - "delete": { - "x-hidden": true, - "summary": "Delete a user (staff only)", - "tags": ["Staff"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "User deletion result" - } - } - } - }, - "/contributions": { - "get": { - "summary": "List contributions", - "tags": ["Contributions"], - "parameters": [ - { - "in": "query", - "name": "status", - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "airport", - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "user", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Contributions listed" - } - } - }, - "post": { - "summary": "Submit a new contribution", - "tags": ["Contributions"], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["airportIcao", "packageName", "submittedXml"], - "properties": { - "userDisplayName": { - "type": "string" - }, - "airportIcao": { - "type": "string" - }, - "packageName": { - "type": "string" - }, - "submittedXml": { - "type": "string" - }, - "notes": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "201": { - "description": "Contribution created" - } - } - } - }, - "/contributions/leaderboard": { - "get": { - "summary": "Get top contributors", - "tags": ["Contributions"], - "responses": { - "200": { - "description": "Leaderboard returned" - } - } - } - }, - "/contributions/top-packages": { - "get": { - "summary": "Get most used packages", - "tags": ["Contributions"], - "responses": { - "200": { - "description": "Package stats returned" - } - } - } - }, - "/contributions/user": { - "get": { - "summary": "Get current user's contributions", - "tags": ["Contributions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "query", - "name": "status", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Contributions returned" - } - } - } - }, - "/contributions/{id}": { - "get": { - "summary": "Get a specific contribution", - "tags": ["Contributions"], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Contribution returned" - }, - "404": { - "description": "Not found" - } - } - }, - "delete": { - "x-hidden": true, - "summary": "Delete a contribution", - "tags": ["Contributions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Deletion result" - } - } - } - }, - "/contributions/{id}/decision": { - "post": { - "x-hidden": true, - "summary": "Approve or reject a contribution", - "tags": ["Contributions"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["approved"], - "properties": { - "approved": { - "type": "boolean" - }, - "rejectionReason": { - "type": "string" - }, - "newPackageName": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Decision processed" - }, - "403": { - "description": "Not authorized" - } - } - } - }, - "/contributions/user/display-name": { - "get": { - "summary": "Get display name for authenticated user", - "tags": ["Contributions"], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Display name returned" - } - } - } - }, - "/cdn/files/{fileKey}": { - "get": { - "summary": "Download a file from CDN", - "tags": ["CDN"], - "parameters": [ - { - "in": "path", - "name": "fileKey", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "File stream" - }, - "404": { - "description": "Not found" - } - } - }, - "delete": { - "x-hidden": true, - "summary": "Delete a file (staff only)", - "tags": ["CDN"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "fileKey", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Deletion result" - } - } - } - }, - "/cdn/upload": { - "post": { - "x-hidden": true, - "summary": "Upload a file to CDN (staff only)", - "tags": ["CDN"], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "multipart/form-data": { - "schema": { - "type": "object", - "required": ["file"], - "properties": { - "file": { - "type": "string", - "format": "binary" - }, - "path": { - "type": "string" - }, - "key": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "201": { - "description": "File uploaded" - } - } - } - }, - "/cdn/files": { - "get": { - "x-hidden": true, - "summary": "List CDN files (staff only)", - "tags": ["CDN"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "query", - "name": "prefix", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Files listed" - } - } - } - }, - "/euroscope/files/{icao}": { - "get": { - "summary": "List public EuroScope files for an airport", - "tags": ["EuroScope"], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Files listed" - }, - "400": { - "description": "Invalid ICAO" - } - } - } - }, - "/euroscope/upload": { - "post": { - "x-hidden": true, - "summary": "Upload EuroScope file for an airport", - "tags": ["EuroScope"], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "multipart/form-data": { - "schema": { - "type": "object", - "required": ["file", "icao"], - "properties": { - "file": { - "type": "string", - "format": "binary" - }, - "icao": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "201": { - "description": "File uploaded" - } - } - } - }, - "/euroscope/files/{icao}/{filename}": { - "delete": { - "x-hidden": true, - "summary": "Delete EuroScope file", - "tags": ["EuroScope"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "path", - "name": "filename", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Deletion result" - } - } - } - }, - "/euroscope/{icao}/editable": { - "get": { - "x-hidden": true, - "summary": "Check if EuroScope files are editable by user", - "tags": ["EuroScope"], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Permission status returned" - } - } - } - }, - "/purge-cache": { - "post": { - "x-hidden": true, - "summary": "Purge a cache key (lead developer only)", - "tags": ["Staff", "Cache"], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": ["key"], - "properties": { - "key": { - "type": "string" - }, - "namespace": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Cache purged" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/contributors": { - "get": { - "summary": "List GitHub contributors", - "tags": ["GitHub"], - "responses": { - "200": { - "description": "Contributors returned" - } - } - } - }, - "/health": { - "get": { - "summary": "System/service health check", - "tags": ["System"], - "parameters": [ - { - "in": "query", - "name": "service", - "required": false, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "All services healthy" - }, - "503": { - "description": "One or more services degraded" - } - } - } - }, - "/openapi.json": { - "get": { - "summary": "Get OpenAPI specification", - "tags": ["System"], - "description": "Returns the current OpenAPI 3.0 document for the BARS Core API.", - "responses": { - "200": { - "description": "OpenAPI document", - "content": { - "application/json": { - "schema": { - "type": "object" - } - } - } - } - } - } - } - }, - "components": { - "securitySchemes": { - "VatsimToken": { - "type": "apiKey", - "in": "header", - "name": "X-Vatsim-Token", - "description": "VATSIM authentication token obtained via OAuth callback." - }, - "ApiKeyAuth": { - "type": "http", - "scheme": "bearer", - "bearerFormat": "API Key", - "description": "User API key passed as Bearer token in Authorization header." - } - }, - "schemas": { - "Coordinates": { - "type": "object", - "required": ["lat", "lng"], - "properties": { - "lat": { - "type": "number", - "description": "Latitude in decimal degrees." - }, - "lng": { - "type": "number", - "description": "Longitude in decimal degrees." - } - } - }, - "PointData": { - "type": "object", - "required": ["type", "name", "coordinates"], - "properties": { - "type": { - "type": "string", - "enum": ["stopbar", "lead_on", "taxiway", "stand"], - "description": "Point category." - }, - "name": { - "type": "string", - "description": "Human readable point name / identifier." - }, - "coordinates": { - "$ref": "#/components/schemas/Coordinates" - }, - "directionality": { - "type": "string", - "enum": ["bi-directional", "uni-directional"] - }, - "orientation": { - "type": "string", - "enum": ["left", "right"] - }, - "color": { - "type": "string", - "enum": ["yellow", "green", "green-yellow", "green-orange", "green-blue"] - }, - "elevated": { - "type": "boolean" - }, - "ihp": { - "type": "boolean", - "description": "In pavement (false) vs elevated (true) for some systems." - } - }, - "description": "Point creation object. Server assigns id, airportId, created/updated timestamps & createdBy." - }, - "Point": { - "allOf": [ - { - "$ref": "#/components/schemas/PointData" - }, - { - "type": "object", - "required": ["id", "airportId", "createdAt", "updatedAt", "createdBy"], - "properties": { - "id": { - "type": "string" - }, - "airportId": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "updatedAt": { - "type": "string", - "format": "date-time" - }, - "createdBy": { - "type": "string", - "description": "VATSIM ID of creator" - } - }, - "description": "Persisted point including server-managed fields." - } - ] - }, - "PointDataPartial": { - "type": "object", - "description": "Partial PointData used for updates. All properties optional.", - "properties": { - "type": { - "type": "string", - "enum": ["stopbar", "lead_on", "taxiway", "stand"] - }, - "name": { - "type": "string" - }, - "coordinates": { - "type": "object", - "properties": { - "lat": { - "type": "number" - }, - "lng": { - "type": "number" - } - } - }, - "directionality": { - "type": "string", - "enum": ["bi-directional", "uni-directional"] - }, - "orientation": { - "type": "string", - "enum": ["left", "right"] - }, - "color": { - "type": "string", - "enum": ["yellow", "green", "green-yellow", "green-orange", "green-blue"] - }, - "elevated": { - "type": "boolean" - }, - "ihp": { - "type": "boolean" - } - } - }, - "PointChangeset": { - "type": "object", - "description": "Transactional batch of point operations. Operations are applied atomically where possible.", - "properties": { - "create": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PointData" - }, - "description": "List of new points to create." - }, - "modify": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/PointDataPartial" - }, - "description": "Map of point ID -> partial point data to update." - }, - "delete": { - "type": "array", - "items": { - "type": "string" - }, - "description": "List of point IDs to delete." - } - } - }, - "ErrorResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "message": { - "type": "string" - }, - "code": { - "type": "string", - "description": "Optional machine-readable error code" - } - }, - "required": ["error"], - "description": "Standard error envelope." - } - } - } -} + "openapi": "3.0.4", + "info": { + "title": "BARS Core API", + "version": "2.0.0", + "description": "API documentation for BARS Core", + "contact": { + "name": "BARS Support", + "email": "support@stopbars.com", + "url": "https://stopbars.com/support" + } + }, + "externalDocs": { + "description": "Find more info here", + "url": "https://docs.stopbars.com" + }, + "servers": [ + { + "url": "https://v2.stopbars.com", + "description": "Production" + }, + { + "url": "http://localhost:8787", + "description": "Local development (wrangler dev)" + } + ], + "tags": [ + { + "name": "RealTime", + "description": "WebSocket connection and real-time state interaction endpoints." + }, + { + "name": "State", + "description": "Endpoints for retrieving current system or airport lighting/network state." + }, + { + "name": "Auth", + "description": "Authentication, account management, and API key lifecycle." + }, + { + "name": "Airports", + "description": "Lookup and metadata endpoints for airports." + }, + { + "name": "Divisions", + "description": "Division management, membership, and associated airport access." + }, + { + "name": "Points", + "description": "Creation and management of lighting/navigation point data." + }, + { + "name": "Support", + "description": "Utilities for generating light support / BARS XML artifacts." + }, + { + "name": "NOTAM", + "description": "Global NOTAM retrieval and (staff) updates." + }, + { + "name": "Contributions", + "description": "Community lighting package submission, review, and leaderboard." + }, + { + "name": "Staff", + "description": "Restricted staff-only operational and moderation endpoints (hidden from public docs)." + }, + { + "name": "CDN", + "description": "File storage, upload, listing, and deletion via CDN-backed storage." + }, + { + "name": "EuroScope", + "description": "EuroScope sector file upload, listing, and permission checks by ICAO." + }, + { + "name": "Cache", + "description": "Administrative cache management operations." + }, + { + "name": "GitHub", + "description": "Repository contributor information." + }, + { + "name": "System", + "description": "System health and OpenAPI specification discovery." + } + ], + "paths": { + "/connect": { + "get": { + "summary": "Establish a WebSocket for an airport", + "tags": [ + "RealTime" + ], + "description": "Performs a WebSocket upgrade to stream real-time airport state. Requires:\n- GET with `Upgrade: websocket`\n- `airport` (ICAO, 4 chars) & `key` (API key) query params\nThe API key is forwarded as a Bearer token to the airport's Durable Object for auth.\n", + "parameters": [ + { + "in": "query", + "name": "airport", + "required": true, + "description": "Airport ICAO (4 alphanumeric characters)", + "schema": { + "type": "string", + "minLength": 4, + "maxLength": 4, + "pattern": "^[A-Z0-9]{4}$" + } + }, + { + "in": "query", + "name": "key", + "required": true, + "description": "User API key", + "schema": { + "type": "string" + } + } + ], + "responses": { + "101": { + "description": "WebSocket upgrade accepted" + }, + "400": { + "description": "Missing/invalid params or not a WebSocket upgrade" + }, + "401": { + "description": "API key rejected" + } + } + } + }, + "/state": { + "get": { + "summary": "Get current lighting/network state", + "tags": [ + "State" + ], + "description": "Retrieves real-time state for a specific airport or all active airports.", + "parameters": [ + { + "in": "query", + "name": "airport", + "required": true, + "description": "ICAO code of airport or 'all' for every active airport", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "State information returned" + }, + "400": { + "description": "Missing or invalid airport parameter" + } + } + } + }, + "/auth/vatsim/callback": { + "get": { + "summary": "VATSIM OAuth callback", + "tags": [ + "Auth" + ], + "description": "Exchanges authorization code for a VATSIM token and redirects to frontend with token.", + "parameters": [ + { + "in": "query", + "name": "code", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "302": { + "description": "Redirect to application with token or error" + }, + "400": { + "description": "Missing code parameter" + } + } + } + }, + "/auth/account": { + "get": { + "summary": "Get authenticated account information", + "tags": [ + "Auth" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Account found" + }, + "401": { + "description": "Missing or invalid token" + }, + "404": { + "description": "User not found" + } + } + } + }, + "/auth/display-mode": { + "put": { + "summary": "Update preferred display name mode", + "tags": [ + "Auth" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "mode" + ], + "properties": { + "mode": { + "type": "integer", + "enum": [ + 0, + 1, + 2 + ], + "description": "0=First,1=First LastInitial,2=CID" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Updated" + } + } + } + }, + "/auth/regenerate-api-key": { + "post": { + "summary": "Regenerate API key", + "tags": [ + "Auth" + ], + "description": "Generates a new API key for the authenticated user (24h cooldown).", + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Key regenerated" + }, + "401": { + "description": "Unauthorized" + }, + "404": { + "description": "User not found" + }, + "429": { + "description": "Rate limited (cooldown not elapsed)" + } + } + } + }, + "/auth/delete": { + "delete": { + "summary": "Delete current user account", + "tags": [ + "Auth" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "204": { + "description": "Account deleted" + }, + "401": { + "description": "Unauthorized" + }, + "404": { + "description": "User not found" + } + } + } + }, + "/auth/is-staff": { + "get": { + "x-hidden": true, + "summary": "Check staff status", + "tags": [ + "Staff" + ], + "security": [ + { + "ApiKeyAuth": [] + } + ], + "responses": { + "200": { + "description": "Staff status returned" + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/airports": { + "get": { + "summary": "Get airport data", + "tags": [ + "Airports" + ], + "description": "Fetch airport(s) by ICAO(s) or by continent.", + "parameters": [ + { + "in": "query", + "name": "icao", + "required": false, + "description": "Single ICAO or comma-separated list", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "continent", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Airport data returned" + }, + "400": { + "description": "Invalid parameters" + }, + "404": { + "description": "Airport not found" + } + } + } + }, + "/airports/nearest": { + "get": { + "summary": "Find nearest airport", + "tags": [ + "Airports" + ], + "description": "Returns the nearest airport to a given latitude/longitude. Results are cached in 5NM buckets for high performance.", + "parameters": [ + { + "in": "query", + "name": "lat", + "required": true, + "description": "Latitude in decimal degrees (-90 to 90)", + "schema": { + "type": "number" + } + }, + { + "in": "query", + "name": "lon", + "required": true, + "description": "Longitude in decimal degrees (-180 to 180)", + "schema": { + "type": "number" + } + } + ], + "responses": { + "200": { + "description": "Nearest airport returned" + }, + "400": { + "description": "Invalid coordinates" + }, + "404": { + "description": "No airport found" + } + } + } + }, + "/divisions": { + "get": { + "summary": "List all divisions", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Divisions returned" + }, + "401": { + "description": "Unauthorized" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Create a new division", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "name", + "headVatsimId" + ], + "properties": { + "name": { + "type": "string" + }, + "headVatsimId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Division created" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/divisions/{id}": { + "put": { + "x-hidden": true, + "summary": "Update division name", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Division updated" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Division not found" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete a division", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "204": { + "description": "Division deleted" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Division not found" + } + } + }, + "get": { + "summary": "Get division details", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Division returned" + }, + "404": { + "description": "Division not found" + } + } + } + }, + "/divisions/user": { + "get": { + "summary": "Get divisions for current user", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "User divisions returned" + } + } + } + }, + "/divisions/{id}/members": { + "get": { + "summary": "List division members", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Members listed" + }, + "404": { + "description": "Division not found" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Add member to division", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "vatsimId", + "role" + ], + "properties": { + "vatsimId": { + "type": "string" + }, + "role": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Member added" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/divisions/{id}/members/{vatsimId}": { + "delete": { + "x-hidden": true, + "summary": "Remove member from division", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "in": "path", + "name": "vatsimId", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Member removed" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/divisions/{id}/airports": { + "get": { + "summary": "List division airports", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Airports listed" + }, + "404": { + "description": "Division not found" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Request airport addition to division", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "icao" + ], + "properties": { + "icao": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Airport request created" + }, + "404": { + "description": "Division not found" + } + } + } + }, + "/divisions/{id}/airports/{airportId}/approve": { + "post": { + "x-hidden": true, + "summary": "Approve or reject airport request", + "tags": [ + "Divisions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "in": "path", + "name": "airportId", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "approved" + ], + "properties": { + "approved": { + "type": "boolean" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Airport approval processed" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/airports/{icao}/points": { + "get": { + "summary": "List lighting/navigation points for airport", + "tags": [ + "Points" + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string", + "minLength": 4, + "maxLength": 4 + } + } + ], + "responses": { + "200": { + "description": "Points returned" + }, + "400": { + "description": "Invalid ICAO" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Create a single point", + "tags": [ + "Points" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PointData" + } + } + } + }, + "responses": { + "201": { + "description": "Point created" + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/airports/{icao}/points/batch": { + "post": { + "x-hidden": true, + "summary": "Apply a batch point changeset", + "tags": [ + "Points" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PointChangeset" + } + } + } + }, + "responses": { + "201": { + "description": "Changeset applied" + } + } + } + }, + "/airports/{icao}/points/{id}": { + "put": { + "x-hidden": true, + "summary": "Update a point", + "tags": [ + "Points" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "responses": { + "200": { + "description": "Point updated" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete a point", + "tags": [ + "Points" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Deleted" + } + } + } + }, + "/points/{id}": { + "get": { + "summary": "Get a single point by ID", + "tags": [ + "Points" + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Point found" + }, + "404": { + "description": "Not found" + } + } + } + }, + "/points": { + "get": { + "summary": "Get multiple points by IDs", + "tags": [ + "Points" + ], + "parameters": [ + { + "in": "query", + "name": "ids", + "required": true, + "description": "Comma-separated list of point IDs (max 100)", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Points returned" + }, + "400": { + "description": "Validation error" + } + } + } + }, + "/supports/generate": { + "post": { + "summary": "Generate Light Supports and BARS XML", + "tags": [ + "Support" + ], + "description": "Upload raw XML and generate both light supports XML and processed BARS XML.", + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "required": [ + "xmlFile", + "icao" + ], + "properties": { + "xmlFile": { + "type": "string", + "format": "binary" + }, + "icao": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Generated XML returned" + }, + "400": { + "description": "Validation error" + } + } + } + }, + "/notam": { + "get": { + "summary": "Get global NOTAM", + "tags": [ + "NOTAM" + ], + "responses": { + "200": { + "description": "Current NOTAM returned" + } + } + }, + "put": { + "x-hidden": true, + "summary": "Update global NOTAM", + "tags": [ + "NOTAM" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "content" + ], + "properties": { + "content": { + "type": "string" + }, + "type": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "NOTAM updated" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/staff/users": { + "get": { + "x-hidden": true, + "summary": "List users (staff only)", + "tags": [ + "Staff" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Users returned" + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/staff/users/search": { + "get": { + "x-hidden": true, + "summary": "Search users (staff only)", + "tags": [ + "Staff" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "query", + "name": "q", + "required": true, + "schema": { + "type": "string", + "minLength": 3 + } + } + ], + "responses": { + "200": { + "description": "Search results returned" + }, + "400": { + "description": "Invalid query" + } + } + } + }, + "/staff/users/refresh-api-token": { + "post": { + "x-hidden": true, + "summary": "Refresh a user's API token (staff only)", + "tags": [ + "Staff" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "vatsimId" + ], + "properties": { + "vatsimId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Token refreshed" + } + } + } + }, + "/staff/users/{id}": { + "delete": { + "x-hidden": true, + "summary": "Delete a user (staff only)", + "tags": [ + "Staff" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "User deletion result" + } + } + } + }, + "/contributions": { + "get": { + "summary": "List contributions", + "tags": [ + "Contributions" + ], + "parameters": [ + { + "in": "query", + "name": "status", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "airport", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "user", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Contributions listed" + } + } + }, + "post": { + "summary": "Submit a new contribution", + "tags": [ + "Contributions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "airportIcao", + "packageName", + "submittedXml" + ], + "properties": { + "airportIcao": { + "type": "string" + }, + "packageName": { + "type": "string" + }, + "submittedXml": { + "type": "string" + }, + "notes": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Contribution created" + } + } + } + }, + "/contributions/leaderboard": { + "get": { + "summary": "Get top contributors", + "tags": [ + "Contributions" + ], + "responses": { + "200": { + "description": "Leaderboard returned" + } + } + } + }, + "/contributions/top-packages": { + "get": { + "summary": "Get most used packages", + "tags": [ + "Contributions" + ], + "responses": { + "200": { + "description": "Package stats returned" + } + } + } + }, + "/contributions/user": { + "get": { + "summary": "Get current user's contributions", + "tags": [ + "Contributions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "query", + "name": "status", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Contributions returned" + } + } + } + }, + "/contributions/{id}": { + "get": { + "summary": "Get a specific contribution", + "tags": [ + "Contributions" + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Contribution returned" + }, + "404": { + "description": "Not found" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete a contribution", + "tags": [ + "Contributions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Deletion result" + } + } + } + }, + "/contributions/{id}/decision": { + "post": { + "x-hidden": true, + "summary": "Approve or reject a contribution", + "tags": [ + "Contributions" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "approved" + ], + "properties": { + "approved": { + "type": "boolean" + }, + "rejectionReason": { + "type": "string" + }, + "newPackageName": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Decision processed" + }, + "403": { + "description": "Not authorized" + } + } + } + }, + "/cdn/files/{fileKey}": { + "get": { + "summary": "Download a file from CDN", + "tags": [ + "CDN" + ], + "parameters": [ + { + "in": "path", + "name": "fileKey", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "File stream" + }, + "404": { + "description": "Not found" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete a file (staff only)", + "tags": [ + "CDN" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "fileKey", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Deletion result" + } + } + } + }, + "/cdn/upload": { + "post": { + "x-hidden": true, + "summary": "Upload a file to CDN (staff only)", + "tags": [ + "CDN" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "required": [ + "file" + ], + "properties": { + "file": { + "type": "string", + "format": "binary" + }, + "path": { + "type": "string" + }, + "key": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "File uploaded" + } + } + } + }, + "/cdn/files": { + "get": { + "x-hidden": true, + "summary": "List CDN files (staff only)", + "tags": [ + "CDN" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "query", + "name": "prefix", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Files listed" + } + } + } + }, + "/euroscope/files/{icao}": { + "get": { + "summary": "List public EuroScope files for an airport", + "tags": [ + "EuroScope" + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Files listed" + }, + "400": { + "description": "Invalid ICAO" + } + } + } + }, + "/euroscope/upload": { + "post": { + "x-hidden": true, + "summary": "Upload EuroScope file for an airport", + "tags": [ + "EuroScope" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "required": [ + "file", + "icao" + ], + "properties": { + "file": { + "type": "string", + "format": "binary" + }, + "icao": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "File uploaded" + } + } + } + }, + "/euroscope/files/{icao}/{filename}": { + "delete": { + "x-hidden": true, + "summary": "Delete EuroScope file", + "tags": [ + "EuroScope" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "filename", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Deletion result" + } + } + } + }, + "/euroscope/{icao}/editable": { + "get": { + "x-hidden": true, + "summary": "Check if EuroScope files are editable by user", + "tags": [ + "EuroScope" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Permission status returned" + } + } + } + }, + "/purge-cache": { + "post": { + "x-hidden": true, + "summary": "Purge a cache key (lead developer only)", + "tags": [ + "Staff", + "Cache" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "key" + ], + "properties": { + "key": { + "type": "string" + }, + "namespace": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Cache purged" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/contributors": { + "get": { + "summary": "List GitHub contributors", + "tags": [ + "GitHub" + ], + "responses": { + "200": { + "description": "Contributors returned" + } + } + } + }, + "/health": { + "get": { + "summary": "System/service health check", + "tags": [ + "System" + ], + "parameters": [ + { + "in": "query", + "name": "service", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "All services healthy" + }, + "503": { + "description": "One or more services degraded" + } + } + } + }, + "/openapi.json": { + "get": { + "summary": "Get OpenAPI specification", + "tags": [ + "System" + ], + "description": "Returns the current OpenAPI 3.0 document for the BARS Core API.", + "responses": { + "200": { + "description": "OpenAPI document", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + } + } + }, + "components": { + "securitySchemes": { + "VatsimToken": { + "type": "apiKey", + "in": "header", + "name": "X-Vatsim-Token", + "description": "VATSIM authentication token obtained via OAuth callback." + }, + "ApiKeyAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "API Key", + "description": "User API key passed as Bearer token in Authorization header." + } + }, + "schemas": { + "Coordinates": { + "type": "object", + "required": [ + "lat", + "lng" + ], + "properties": { + "lat": { + "type": "number", + "description": "Latitude in decimal degrees." + }, + "lng": { + "type": "number", + "description": "Longitude in decimal degrees." + } + } + }, + "PointData": { + "type": "object", + "required": [ + "type", + "name", + "coordinates" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "stopbar", + "lead_on", + "taxiway", + "stand" + ], + "description": "Point category." + }, + "name": { + "type": "string", + "description": "Human readable point name / identifier." + }, + "coordinates": { + "$ref": "#/components/schemas/Coordinates" + }, + "directionality": { + "type": "string", + "enum": [ + "bi-directional", + "uni-directional" + ] + }, + "orientation": { + "type": "string", + "enum": [ + "left", + "right" + ] + }, + "color": { + "type": "string", + "enum": [ + "yellow", + "green", + "green-yellow", + "green-orange", + "green-blue" + ] + }, + "elevated": { + "type": "boolean" + }, + "ihp": { + "type": "boolean", + "description": "In pavement (false) vs elevated (true) for some systems." + } + }, + "description": "Point creation object. Server assigns id, airportId, created/updated timestamps & createdBy." + }, + "Point": { + "allOf": [ + { + "$ref": "#/components/schemas/PointData" + }, + { + "type": "object", + "required": [ + "id", + "airportId", + "createdAt", + "updatedAt", + "createdBy" + ], + "properties": { + "id": { + "type": "string" + }, + "airportId": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "createdBy": { + "type": "string", + "description": "VATSIM ID of creator" + } + }, + "description": "Persisted point including server-managed fields." + } + ] + }, + "PointDataPartial": { + "type": "object", + "description": "Partial PointData used for updates. All properties optional.", + "properties": { + "type": { + "type": "string", + "enum": [ + "stopbar", + "lead_on", + "taxiway", + "stand" + ] + }, + "name": { + "type": "string" + }, + "coordinates": { + "type": "object", + "properties": { + "lat": { + "type": "number" + }, + "lng": { + "type": "number" + } + } + }, + "directionality": { + "type": "string", + "enum": [ + "bi-directional", + "uni-directional" + ] + }, + "orientation": { + "type": "string", + "enum": [ + "left", + "right" + ] + }, + "color": { + "type": "string", + "enum": [ + "yellow", + "green", + "green-yellow", + "green-orange", + "green-blue" + ] + }, + "elevated": { + "type": "boolean" + }, + "ihp": { + "type": "boolean" + } + } + }, + "PointChangeset": { + "type": "object", + "description": "Transactional batch of point operations. Operations are applied atomically where possible.", + "properties": { + "create": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PointData" + }, + "description": "List of new points to create." + }, + "modify": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/PointDataPartial" + }, + "description": "Map of point ID -> partial point data to update." + }, + "delete": { + "type": "array", + "items": { + "type": "string" + }, + "description": "List of point IDs to delete." + } + } + }, + "ErrorResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "message": { + "type": "string" + }, + "code": { + "type": "string", + "description": "Optional machine-readable error code" + } + }, + "required": [ + "error" + ], + "description": "Standard error envelope." + } + } + } +} \ No newline at end of file diff --git a/schema.sql b/schema.sql index 5c36abb..6acb16f 100644 --- a/schema.sql +++ b/schema.sql @@ -5,6 +5,9 @@ CREATE TABLE IF NOT EXISTS users ( api_key TEXT NOT NULL, last_api_key_regen DATETIME DEFAULT CURRENT_TIMESTAMP, email TEXT NOT NULL, + full_name TEXT, -- Stored full name from VATSIM (first + last) + display_mode INTEGER NOT NULL DEFAULT 0, + display_name TEXT, -- Cached computed display name created_at TEXT NOT NULL, last_login TEXT NOT NULL ); @@ -101,7 +104,6 @@ CREATE TABLE IF NOT EXISTS active_objects ( CREATE TABLE IF NOT EXISTS contributions ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, - user_display_name TEXT, airport_icao TEXT NOT NULL, package_name TEXT NOT NULL, submitted_xml TEXT NOT NULL, diff --git a/src/index.ts b/src/index.ts index cdf6e4a..2dbe822 100644 --- a/src/index.ts +++ b/src/index.ts @@ -34,7 +34,6 @@ interface ApproveAirportPayload { } interface ContributionSubmissionPayload { - userDisplayName?: string; airportIcao: string; packageName: string; submittedXml: string; @@ -360,20 +359,92 @@ app.get('/auth/account', async (c) => { const auth = ServicePool.getAuth(c.env); const vatsimUser = await vatsim.getUser(vatsimToken); - const user = await auth.getUserByVatsimId(vatsimUser.id); + let user = await auth.getUserByVatsimId(vatsimUser.id); if (!user) { return dbContext.textResponse('User not found', { status: 404 }); } + // Backfill full_name if missing locally but available from VATSIM + if ((!user.full_name || user.full_name.trim() === '') && (vatsimUser.first_name || vatsimUser.last_name)) { + const newFullName = [vatsimUser.first_name, vatsimUser.last_name].filter(Boolean).join(' ').trim(); + if (newFullName) { + try { await auth.updateFullName(user.id, newFullName); } catch { /* ignore */ } + const refreshed = await auth.getUserByVatsimId(vatsimUser.id); + if (refreshed) user = refreshed; + } + } return dbContext.jsonResponse({ - ...user, + id: user.id, + vatsim_id: user.vatsim_id, email: vatsimUser.email, + api_key: user.api_key, + full_name: user.full_name || null, + display_mode: user.display_mode ?? 0, + display_name: user.display_name || auth.computeDisplayName(user, vatsimUser), + created_at: user.created_at, + last_login: user.last_login, }); } finally { dbContext.close(); } }); +/** + * @openapi + * /auth/display-mode: + * put: + * summary: Update preferred display name mode + * tags: + * - Auth + * security: + * - VatsimToken: [] + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: [mode] + * properties: + * mode: + * type: integer + * enum: [0,1,2] + * description: 0=First,1=First LastInitial,2=CID + * responses: + * 200: + * description: Updated + */ +app.put('/auth/display-mode', async (c) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + + let body: any; + try { body = await c.req.json(); } catch { return c.json({ error: 'Invalid JSON body' }, 400); } + + const rawMode = body?.mode; + const mode = Number(rawMode); + if (!Number.isInteger(mode) || ![0, 1, 2].includes(mode)) { + return c.json({ error: 'Invalid mode', message: 'mode must be integer 0,1,2' }, 400); + } + + const dbContext = DatabaseContextFactory.createRequestContext(c.env.DB, c.req.raw); + try { + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return dbContext.textResponse('User not found', { status: 404 }); + await auth.updateDisplayMode(user.id, mode); + return dbContext.jsonResponse({ mode }); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Unknown error'; + const status = msg.includes('Invalid display mode') ? 400 : 500; + return dbContext.jsonResponse({ error: 'Failed to update display mode', message: msg }, { status }); + } finally { + dbContext.close(); + } +}); + // Regenerate API key /** * @openapi @@ -614,6 +685,69 @@ app.get('/airports', } ); +// Nearest airport (public, unauthenticated) +/** + * @openapi + * /airports/nearest: + * get: + * summary: Find nearest airport + * tags: + * - Airports + * description: Returns the nearest airport to a given latitude/longitude. Results are cached in 5NM buckets for high performance. + * parameters: + * - in: query + * name: lat + * required: true + * description: Latitude in decimal degrees (-90 to 90) + * schema: { type: number } + * - in: query + * name: lon + * required: true + * description: Longitude in decimal degrees (-180 to 180) + * schema: { type: number } + * responses: + * 200: + * description: Nearest airport returned + * 400: + * description: Invalid coordinates + * 404: + * description: No airport found + */ +app.get('/airports/nearest', + withCache((req) => { + // Bucket cache key by ~5NM (~9.26km). 1 degree lat ~111km => bucket size deg ≈ 9.26/111 ≈ 0.083 + const url = new URL(req.url); + const lat = parseFloat(url.searchParams.get('lat') || '0'); + const lon = parseFloat(url.searchParams.get('lon') || '0'); + const bucketDeg = 0.083; // ~5NM + const bucketLat = Math.round(lat / bucketDeg); + const bucketLon = Math.round(lon / bucketDeg); + return `/airports/nearest/${bucketLat}_${bucketLon}`; + }, 600, 'airports'), + async (c) => { + const latStr = c.req.query('lat'); + const lonStr = c.req.query('lon'); + + if (!latStr || !lonStr) { + return c.text('Missing lat/lon', 400); + } + const lat = parseFloat(latStr); + const lon = parseFloat(lonStr); + if (Number.isNaN(lat) || Number.isNaN(lon) || lat < -90 || lat > 90 || lon < -180 || lon > 180) { + return c.text('Invalid lat/lon', 400); + } + + try { + const airports = ServicePool.getAirport(c.env); + const nearest = await airports.getNearestAirport(lat, lon); + if (!nearest) return c.text('No airport found', 404); + return c.json(nearest); + } catch (err) { + return c.json({ error: 'Failed to find nearest airport' }, 500); + } + } +); + // Divisions routes const divisionsApp = new Hono<{ Bindings: Env; @@ -715,6 +849,99 @@ divisionsApp.post('/', async (c) => { return c.json(division); }); +// PUT /divisions/:id - Update division name (lead_developer only) +/** + * @openapi + * /divisions/{id}: + * put: + * x-hidden: true + * summary: Update division name + * tags: + * - Divisions + * security: + * - VatsimToken: [] + * parameters: + * - in: path + * name: id + * required: true + * schema: { type: integer } + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: [name] + * properties: + * name: + * type: string + * responses: + * 200: + * description: Division updated + * 403: + * description: Forbidden + * 404: + * description: Division not found + */ +divisionsApp.put('/:id', async (c) => { + const user = c.get('user'); + const roles = ServicePool.getRoles(c.env); + const divisions = ServicePool.getDivisions(c.env); + const id = parseInt(c.req.param('id')); + + const isLeadDev = await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER); + if (!isLeadDev) return c.text('Forbidden', 403); + + const existing = await divisions.getDivision(id); + if (!existing) return c.text('Division not found', 404); + + const body = await c.req.json() as { name: string }; + if (!body.name || !body.name.trim()) return c.text('Invalid name', 400); + + const updated = await divisions.updateDivisionName(id, body.name.trim()); + return c.json(updated); +}); + +// DELETE /divisions/:id - Delete division (lead_developer only) +/** + * @openapi + * /divisions/{id}: + * delete: + * x-hidden: true + * summary: Delete a division + * tags: + * - Divisions + * security: + * - VatsimToken: [] + * parameters: + * - in: path + * name: id + * required: true + * schema: { type: integer } + * responses: + * 204: + * description: Division deleted + * 403: + * description: Forbidden + * 404: + * description: Division not found + */ +divisionsApp.delete('/:id', async (c) => { + const user = c.get('user'); + const roles = ServicePool.getRoles(c.env); + const divisions = ServicePool.getDivisions(c.env); + const id = parseInt(c.req.param('id')); + + const isLeadDev = await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER); + if (!isLeadDev) return c.text('Forbidden', 403); + + const existing = await divisions.getDivision(id); + if (!existing) return c.text('Division not found', 404); + + await divisions.deleteDivision(id); + return c.body(null, 204); +}); + // GET /divisions/user - Get user's divisions /** * @openapi @@ -1920,7 +2147,6 @@ contributionsApp.get('/top-packages', * type: object * required: [airportIcao, packageName, submittedXml] * properties: - * userDisplayName: { type: string } * airportIcao: { type: string } * packageName: { type: string } * submittedXml: { type: string } @@ -1950,7 +2176,6 @@ contributionsApp.post('/', async (c) => { const payload = await c.req.json() as ContributionSubmissionPayload; const result = await contributions.createContribution({ userId: user.vatsim_id, - userDisplayName: payload.userDisplayName, airportIcao: payload.airportIcao, packageName: payload.packageName, submittedXml: payload.submittedXml, @@ -2111,37 +2336,6 @@ contributionsApp.post('/:id/decision', async (c) => { } }); -// GET /contributions/user/display-name - Get user's display name -/** - * @openapi - * /contributions/user/display-name: - * get: - * summary: Get display name for authenticated user - * tags: - * - Contributions - * security: - * - VatsimToken: [] - * responses: - * 200: - * description: Display name returned - */ -contributionsApp.get('/user/display-name', async (c) => { - const token = c.req.header('X-Vatsim-Token'); - if (!token) { - return c.text('Unauthorized', 401); - } - - const vatsim = ServicePool.getVatsim(c.env); - const vatsimUser = await vatsim.getUser(token); - const contributions = ServicePool.getContributions(c.env); - const displayName = await contributions.getUserDisplayName(vatsimUser.id); - - if (!displayName) { - return c.text('User not found', 404); - } - - return c.json({ displayName }); -}); // DELETE /contributions/:id - Delete a contribution (admin only) /** diff --git a/src/services/airport.ts b/src/services/airport.ts index f333cd6..44a6fb0 100644 --- a/src/services/airport.ts +++ b/src/services/airport.ts @@ -1,5 +1,6 @@ import { DatabaseSessionService } from './database-session'; import { PostHogService } from './posthog'; +import { calculateDistance } from './bars/geoUtils'; interface AirportData { latitude_deg?: number; @@ -139,4 +140,55 @@ export class AirportService { ); return { results: result.results }; } + + /** + * Find the nearest airport to a latitude/longitude using a very fast approximate search + * followed by an exact distance refinement. Designed for high QPS usage. + */ + async getNearestAirport(lat: number, lon: number) { + // Guard invalid input early + if (Number.isNaN(lat) || Number.isNaN(lon) || lat < -90 || lat > 90 || lon < -180 || lon > 180) { + return null; + } + + // Use a small bounding box to reduce rows scanned (±1° ~ up to 60nm lat / 60nm * cos(lat) lon) + const LAT_BOX = 1; // degrees + const LON_BOX = 1; // degrees + const minLat = lat - LAT_BOX; + const maxLat = lat + LAT_BOX; + const minLon = lon - LON_BOX; + const maxLon = lon + LON_BOX; + + // Pre-compute cos^2(lat) to weight longitudinal delta for planar approx distance ordering + const cosLat = Math.cos(lat * Math.PI / 180); + const cosLatSq = cosLat * cosLat; + const approx = await this.dbSession.executeRead( + `SELECT icao, latitude, longitude, name, continent, + ((latitude - ?) * (latitude - ?) + ((longitude - ?) * (longitude - ?) * ?)) AS distance_score + FROM airports + WHERE latitude BETWEEN ? AND ? AND longitude BETWEEN ? AND ? + ORDER BY distance_score + LIMIT 1`, + [lat, lat, lon, lon, cosLatSq, minLat, maxLat, minLon, maxLon] + ); + + const row = approx.results?.[0]; + if (!row) return null; + + // Refine with precise geodesic distance (meters) and convert to NM + const distance_m = calculateDistance({ lat, lon }, { lat: row.latitude, lon: row.longitude }); + const distance_nm = distance_m / 1852; + + try { this.posthog?.track('Nearest Airport Lookup', { icao: row.icao }); } catch { } + + return { + icao: row.icao, + latitude: row.latitude, + longitude: row.longitude, + name: row.name, + continent: row.continent, + distance_m: Math.round(distance_m), + distance_nm: Number(distance_nm.toFixed(2)), + }; + } } diff --git a/src/services/auth.ts b/src/services/auth.ts index 01ec911..95781f9 100644 --- a/src/services/auth.ts +++ b/src/services/auth.ts @@ -82,9 +82,15 @@ export class AuthService { apiKey = this.generateApiKey(); } + const fullName = [vatsimUser.first_name, vatsimUser.last_name].filter(Boolean).join(' ') || null; + const displayMode = 0; + const displayName = this.computeDisplayName({ + id: 0, vatsim_id: vatsimUser.id, api_key: apiKey, email: vatsimUser.email, + full_name: fullName, display_mode: displayMode, created_at: '', last_login: '', vatsimToken: '' + }, vatsimUser); const result = await this.dbSession.executeWrite( - 'INSERT INTO users (vatsim_id, api_key, email, created_at, last_login) VALUES (?, ?, ?, ?, ?) RETURNING *', - [vatsimUser.id, apiKey, vatsimUser.email, new Date().toISOString(), new Date().toISOString()] + 'INSERT INTO users (vatsim_id, api_key, email, full_name, display_mode, display_name, created_at, last_login) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING *', + [vatsimUser.id, apiKey, vatsimUser.email, fullName, displayMode, displayName, new Date().toISOString(), new Date().toISOString()] ); if (!result.results[0]) throw new Error('Failed to create user'); @@ -127,6 +133,64 @@ export class AuthService { return result.results[0] || null; } + computeDisplayName(user: UserRecord, vatsimUser?: VatsimUser): string { + const mode = (user.display_mode ?? 0); + const fullName = user.full_name || [vatsimUser?.first_name, vatsimUser?.last_name].filter(Boolean).join(' ').trim(); + if (mode === 2) return user.vatsim_id; + if (!fullName) return user.vatsim_id; + const parts = fullName.split(/\s+/); + if (mode === 0) return parts[0]; + if (mode === 1) { + const first = parts[0]; + const lastInitial = parts.length > 1 ? parts[parts.length - 1][0] : ''; + return lastInitial ? `${first} ${lastInitial}` : first; + } + return fullName; // fallback + } + + async updateDisplayMode(userId: number, mode: number) { + if (![0, 1, 2].includes(mode)) throw new Error('Invalid display mode'); + + // Use primary for consistency on write + this.dbSession.startSession({ mode: 'first-primary' }); + + const current = await this.dbSession.executeRead( + 'SELECT id, vatsim_id, email, full_name, display_mode, display_name FROM users WHERE id = ?', + [userId] + ); + const user = current.results[0]; + if (!user) return; + + if (user.display_mode === mode) return; // nothing to do + + const fullNameParts = (user.full_name || '').trim().split(/\s+/).filter(Boolean); + const vatsimUser: VatsimUser = { + id: user.vatsim_id, + email: user.email, + first_name: fullNameParts[0] || '', + last_name: fullNameParts.slice(1).join(' '), + }; + + const displayName = this.computeDisplayName({ ...user, display_mode: mode } as UserRecord, vatsimUser); + + await this.dbSession.executeWrite( + 'UPDATE users SET display_mode = ?, display_name = ? WHERE id = ?', + [mode, displayName, userId] + ); + } + + async updateFullName(userId: number, fullName: string) { + await this.dbSession.executeWrite('UPDATE users SET full_name = ? WHERE id = ?', [fullName, userId]); + // Recompute display_name after updating full_name using existing display_mode + const current = await this.dbSession.executeRead('SELECT * FROM users WHERE id = ?', [userId]); + const user = current.results[0]; + if (user) { + const vatsimUser: VatsimUser = { id: user.vatsim_id, email: user.email, first_name: fullName.split(' ')[0], last_name: fullName.split(' ').slice(1).join(' ') }; + const displayName = this.computeDisplayName(user, vatsimUser); + await this.dbSession.executeWrite('UPDATE users SET display_name = ? WHERE id = ?', [displayName, userId]); + } + } + private async updateUserLastLogin(userId: number) { await this.dbSession.executeWrite( 'UPDATE users SET last_login = ? WHERE id = ?', diff --git a/src/services/contributions.ts b/src/services/contributions.ts index 6ff2709..961eb49 100644 --- a/src/services/contributions.ts +++ b/src/services/contributions.ts @@ -22,7 +22,6 @@ export interface Contribution { export interface ContributionSubmission { userId: string; - userDisplayName?: string; airportIcao: string; packageName: string; submittedXml: string; @@ -87,7 +86,12 @@ export class ContributionService { const id = crypto.randomUUID(); const now = new Date().toISOString(); - await this.updateUserDisplayNameForAllContributions(submission.userId, submission.userDisplayName || null); + // Get authoritative display name from users table (ignore any client-provided value) + const userDisplayResult = await this.dbSession.executeRead<{ display_name: string | null }>( + 'SELECT display_name FROM users WHERE vatsim_id = ?', + [submission.userId] + ); + const authoritativeDisplayName = userDisplayResult.results[0]?.display_name || null; await this.dbSession.executeWrite( ` INSERT INTO contributions ( @@ -99,7 +103,7 @@ export class ContributionService { [ id, submission.userId, - submission.userDisplayName || null, + authoritativeDisplayName, submission.airportIcao, submission.packageName, trimmedXml, @@ -113,7 +117,7 @@ export class ContributionService { const contribution: Contribution = { id, userId: submission.userId, - userDisplayName: submission.userDisplayName || null, + userDisplayName: authoritativeDisplayName, airportIcao: submission.airportIcao, packageName: submission.packageName, submittedXml: trimmedXml, @@ -515,51 +519,20 @@ export class ContributionService { }> > { const query = ` - SELECT - user_id, - user_display_name, - COUNT(*) as contribution_count - FROM contributions - WHERE status = 'approved' - GROUP BY user_id + SELECT c.user_id, u.display_name, COUNT(*) as contribution_count + FROM contributions c + LEFT JOIN users u ON u.vatsim_id = c.user_id + WHERE c.status = 'approved' + GROUP BY c.user_id ORDER BY contribution_count DESC LIMIT 5 `; - const results = await this.dbSession.executeRead<{ user_id: string; - user_display_name: string | null; + display_name: string | null; contribution_count: number; - }>( - query - ); - return results.results.map((item) => ({ - name: item.user_display_name || item.user_id, - count: item.contribution_count, - })); - } - - private async updateUserDisplayNameForAllContributions(userId: string, displayName: string | null): Promise { - await this.dbSession.executeWrite( - ` - UPDATE contributions - SET user_display_name = ? - WHERE user_id = ? - `, - [displayName, userId] - ); - } - async getUserDisplayName(userId: string): Promise { - const result = await this.dbSession.executeRead<{ userDisplayName: string | null }>( - ` - SELECT user_display_name as userDisplayName - FROM contributions - WHERE user_id = ? - ORDER BY submission_date DESC - LIMIT 1 - `, - [userId] - ); - return result.results[0]?.userDisplayName || null; + }>(query); + return results.results.map(r => ({ name: r.display_name || r.user_id, count: r.contribution_count })); } + // Removed legacy user display name update + lookup helpers; display names now sourced directly from users table } diff --git a/src/services/divisions.ts b/src/services/divisions.ts index 213397f..4a19094 100644 --- a/src/services/divisions.ts +++ b/src/services/divisions.ts @@ -47,6 +47,29 @@ export class DivisionService { return division; } + async updateDivisionName(id: number, newName: string): Promise { + const result = await this.dbSession.executeWrite( + 'UPDATE divisions SET name = ? WHERE id = ? RETURNING *', + [newName, id] + ); + const division = result.results[0] as Division; + if (!division) throw new Error('Division not found'); + try { this.posthog?.track('Division Renamed', { divisionId: id, name: newName }); } catch { } + return division; + } + + async deleteDivision(id: number): Promise { + const result = await this.dbSession.executeWrite( + 'DELETE FROM divisions WHERE id = ? RETURNING id', + [id] + ); + const deleted = !!result.results[0]; + if (deleted) { + try { this.posthog?.track('Division Deleted', { divisionId: id }); } catch { } + } + return deleted; + } + async getDivision(id: number): Promise { const result = await this.dbSession.executeRead( 'SELECT * FROM divisions WHERE id = ?', @@ -123,8 +146,13 @@ export class DivisionService { } async getDivisionMembers(divisionId: number): Promise { - const result = await this.dbSession.executeRead( - 'SELECT * FROM division_members WHERE division_id = ?', + // Use cached display_name; fallback to vatsim_id if null + const result = await this.dbSession.executeRead( + `SELECT dm.id, dm.division_id, dm.vatsim_id, dm.role, dm.created_at, + COALESCE(u.display_name, dm.vatsim_id) AS display_name + FROM division_members dm + LEFT JOIN users u ON u.vatsim_id = dm.vatsim_id + WHERE dm.division_id = ?`, [divisionId] ); return result.results; diff --git a/src/services/users.ts b/src/services/users.ts index c03379c..87e6822 100644 --- a/src/services/users.ts +++ b/src/services/users.ts @@ -30,14 +30,14 @@ export class UserService { const [usersResult, countResult] = await Promise.all([ this.dbSession.executeRead( ` - SELECT u.id, u.vatsim_id, u.email, u.created_at, u.last_login, - CASE WHEN s.id IS NOT NULL THEN 1 ELSE 0 END as is_staff, - s.role - FROM users u - LEFT JOIN staff s ON u.id = s.user_id - ORDER BY u.created_at DESC - LIMIT ? OFFSET ? - `, + SELECT u.id, u.vatsim_id, u.email, u.full_name, u.display_mode, u.created_at, u.last_login, + CASE WHEN s.id IS NOT NULL THEN 1 ELSE 0 END as is_staff, + s.role + FROM users u + LEFT JOIN staff s ON u.id = s.user_id + ORDER BY u.created_at DESC + LIMIT ? OFFSET ? + `, [limit, offset] ), this.dbSession.executeRead<{ count: number }>( @@ -67,7 +67,7 @@ export class UserService { try { const result = await this.dbSession.executeRead( ` - SELECT u.id, u.vatsim_id, u.email, u.created_at, u.last_login, + SELECT u.id, u.vatsim_id, u.email, u.full_name, u.display_mode, u.created_at, u.last_login, CASE WHEN s.id IS NOT NULL THEN 1 ELSE 0 END as is_staff, s.role FROM users u diff --git a/src/services/vatsim.ts b/src/services/vatsim.ts index 3687f65..afa02dd 100644 --- a/src/services/vatsim.ts +++ b/src/services/vatsim.ts @@ -39,6 +39,8 @@ export class VatsimService { return { id: userData.data.cid, email: userData.data.personal.email, + first_name: (userData as any)?.data?.personal?.name_first || undefined, + last_name: (userData as any)?.data?.personal?.name_last || undefined, }; } async getUserStatus(userId: string): Promise<{ cid: string; callsign: string; type: string } | null> { diff --git a/src/types.ts b/src/types.ts index 2691aa6..aaeca31 100644 --- a/src/types.ts +++ b/src/types.ts @@ -7,6 +7,8 @@ export interface AuthResponse { export interface VatsimUser { id: string; email: string; + first_name?: string; + last_name?: string; } export interface UserRecord { @@ -14,6 +16,9 @@ export interface UserRecord { vatsim_id: string; api_key: string; email: string; + full_name?: string | null; + display_mode?: number; // 0=First,1=First LastInitial,2=CID + display_name?: string | null; // cached display name created_at: string; last_login: string; vatsimToken: string; diff --git a/worker-configuration.d.ts b/worker-configuration.d.ts index 1f1a696..9da729e 100644 --- a/worker-configuration.d.ts +++ b/worker-configuration.d.ts @@ -1,10 +1,9 @@ /* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: e029e6e638bdf3cdc564247460c43241) -// Runtime types generated with workerd@1.20250507.0 2024-12-18 nodejs_compat +// Generated by Wrangler by running `wrangler types` (hash: add5d8fef79ab367bb6d84eba9005bf2) +// Runtime types generated with workerd@1.20250803.0 2024-12-18 nodejs_compat declare namespace Cloudflare { interface Env { VATSIM_CLIENT_ID: "1562"; - POSTHOG_API_KEY: "phc_d9RAnVNErmg4zZ4oxpmjbeuLp8oR3nu7iYoAH5vc43I"; POSTHOG_HOST: "https://eu.i.posthog.com"; VATSIM_CLIENT_SECRET: string; AIRPORTDB_API_KEY: string; @@ -39,165 +38,165 @@ declare var onmessage: never; * [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); + 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; + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; }; declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof 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; + "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; + 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. @@ -206,83 +205,83 @@ declare namespace WebAssembly { * [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; + 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; @@ -346,41 +345,41 @@ declare const navigator: Navigator; interface TestController { } interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - props: any; + 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 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; + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; } interface StructuredSerializeOptions { - transfer?: any[]; + 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; + /* [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; + sendBeacon(url: string, body?: (ReadableStream | string | (ArrayBuffer | ArrayBufferView) | Blob | FormData | URLSearchParams | URLSearchParams)): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; } /** * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, @@ -389,136 +388,136 @@ declare abstract class Navigator { * [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; + /* [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; + readonly isRetry: boolean; + readonly retryCount: number; } interface Cloudflare { - readonly compatibilityFlags: Record; + 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; + 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; + readonly id: DurableObjectId; + readonly name?: string; }; interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; + 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; + 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"; +type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; + jurisdiction?: DurableObjectJurisdiction; } type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; + 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; + 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; + 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; + 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; + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; + allowConcurrency?: boolean; } interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; } interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; } declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; + constructor(request: string, response: string); + get request(): string; + get response(): string; } interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; + writeDataPoint(event?: AnalyticsEngineDataPoint): void; } interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; } /** * An event which takes place in the DOM. @@ -526,128 +525,128 @@ interface AnalyticsEngineDataPoint { * [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; + 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; + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; } type EventListener = (event: EventType) => void; interface EventListenerObject { - handleEvent(event: EventType): void; + handleEvent(event: EventType): void; } type EventListenerOrEventListenerObject = EventListener | EventListenerObject; /** @@ -656,49 +655,49 @@ type EventListenerOrEventListenerObject = Event * [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; + 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; + capture?: boolean; } interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; } interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; + handleEvent: (event: Event) => any | undefined; } /** * A controller object that allows you to abort one or more DOM requests as and when desired. @@ -706,19 +705,19 @@ interface EventTargetHandlerObject { * [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; + 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. @@ -726,32 +725,32 @@ declare class AbortController { * [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; + /* [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; + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; } interface SchedulerWaitOptions { - signal?: AbortSignal; + 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. @@ -759,24 +758,24 @@ interface SchedulerWaitOptions { * [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/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; + 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; + 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. @@ -784,24 +783,24 @@ interface CustomEventCustomEventInit { * [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; + 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; + type?: string; } /** * Provides information about files and allows JavaScript in a web page to access their content. @@ -809,15 +808,15 @@ interface BlobOptions { * [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; + 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; + type?: string; + lastModified?: number; } /** * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. @@ -825,9 +824,9 @@ interface FileOptions { * [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; + /* [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. @@ -835,15 +834,15 @@ declare abstract class CacheStorage { * [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; + /* [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; + ignoreMethod?: boolean; } /** * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. @@ -854,21 +853,21 @@ interface CacheQueryOptions { * [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; + /** + * 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). @@ -877,31 +876,31 @@ declare abstract class Crypto { * [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; + /* [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. @@ -910,117 +909,117 @@ declare abstract class SubtleCrypto { * [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[]; + /* [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; + 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; + 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; + r?: string; + d?: string; + t?: string; } interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: (ArrayBuffer | ArrayBufferView); - iterations?: number; - hash?: (string | SubtleCryptoHashAlgorithm); - $public?: CryptoKey; - info?: (ArrayBuffer | ArrayBufferView); + 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); + 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; + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + modulusLength?: number; + publicExponent?: (ArrayBuffer | ArrayBufferView); + length?: number; + namedCurve?: string; } interface SubtleCryptoHashAlgorithm { - name: string; + name: string; } interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - length?: number; - namedCurve?: string; - compressed?: boolean; + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + length?: number; + namedCurve?: string; + compressed?: boolean; } interface SubtleCryptoSignAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - dataLength?: number; - saltLength?: number; + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + dataLength?: number; + saltLength?: number; } interface CryptoKeyKeyAlgorithm { - name: string; + name: string; } interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; + name: string; + length: number; } interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; } interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; } interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; + name: string; + namedCurve: string; } interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; } declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; + 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. @@ -1028,26 +1027,26 @@ declare class DigestStream extends WritableStream * [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; + 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. @@ -1055,31 +1054,31 @@ declare class TextDecoder { * [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; + 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; + fatal: boolean; + ignoreBOM: boolean; } interface TextDecoderDecodeOptions { - stream: boolean; + stream: boolean; } interface TextEncoderEncodeIntoResult { - read: number; - written: number; + read: number; + written: number; } /** * Events providing information related to errors in scripts or in files. @@ -1087,24 +1086,65 @@ interface TextEncoderEncodeIntoResult { * [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; + 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; + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +/** + * 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: any; + /** + * Returns the origin of the message, for server-sent events and cross-document messaging. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null; + /** + * Returns the last event ID string, for server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string; + /** + * Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null; + /** + * Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[]; +} +interface MessageEventInit { + data: ArrayBuffer | string; } /** * 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". @@ -1112,107 +1152,107 @@ interface ErrorEventErrorEventInit { * [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 - ]>; + 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; + html?: boolean; } declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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. @@ -1220,11 +1260,11 @@ interface DocumentEnd { * [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; + /* [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; /** @@ -1233,53 +1273,53 @@ type HeadersInit = Headers | Iterable> | Record * [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 - ]>; + 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; + /* [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. @@ -1287,11 +1327,11 @@ declare abstract class Body { * [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; + 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. @@ -1299,32 +1339,32 @@ declare var Response: { * [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"; + /* [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"; + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: (WebSocket | null); + encodeBody?: "automatic" | "manual"; } type RequestInfo> = Request | string; /** @@ -1333,8 +1373,8 @@ type RequestInfo> = * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ declare var Request: { - prototype: Request; - new >(input: RequestInfo | URL, init?: RequestInit): Request; + prototype: Request; + new >(input: RequestInfo | URL, init?: RequestInit): Request; }; /** * This Fetch API interface represents a resource request. @@ -1342,401 +1382,402 @@ declare var 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"; + /* [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; + /* 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 Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; }; interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; + name: Key; + expiration?: number; + metadata?: Metadata; } type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; } | { - list_complete: true; - keys: KVNamespaceListKey[]; - 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; + 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); + limit?: number; + prefix?: (string | null); + cursor?: (string | null); } interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; + type: Type; + cacheTtl?: number; } interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); + expiration?: number; + expirationTtl?: number; + metadata?: (any | null); } interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; + 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; + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; } interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueSendBatchOptions { - delaySeconds?: number; + delaySeconds?: number; } interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueRetryOptions { - delaySeconds?: number; + delaySeconds?: number; } interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; + 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; + 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; + 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; + 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")[]; + 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; + 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; + 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; + 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; + 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; - text(): Promise; - json(): Promise; - blob(): Promise; + 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; } | { - offset?: number; - length: number; + offset?: number; + length: number; } | { - suffix: number; + suffix: number; }; interface R2Conditional { - etagMatches?: string; - etagDoesNotMatch?: string; - uploadedBefore?: Date; - uploadedAfter?: Date; - secondsGranularity?: boolean; + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; } interface R2GetOptions { - onlyIf?: (R2Conditional | Headers); - range?: (R2Range | Headers); - ssecKey?: (ArrayBuffer | string); + 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); + 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); + 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; + 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; + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; } interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; } type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; + objects: R2Object[]; + delimitedPrefixes: string[]; } & ({ - truncated: true; - cursor: string; + truncated: true; + cursor: string; } | { - truncated: false; + truncated: false; }); interface R2UploadPartOptions { - ssecKey?: (ArrayBuffer | string); + ssecKey?: (ArrayBuffer | string); } declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface QueuingStrategy { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; + 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; + 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; + 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); + 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; + 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; + /** + * 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: false; + value: R; } | { - done: true; - value?: undefined; + 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. @@ -1744,25 +1785,25 @@ type ReadableStreamReadResult = { * [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; + /* [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. @@ -1770,75 +1811,75 @@ interface ReadableStream { * [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; + 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; + 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>; + 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; + 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"; + /** + * 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/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/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; + /* [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. @@ -1846,30 +1887,30 @@ declare abstract class ReadableByteStreamController { * [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/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; + /* [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; + /** + * 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. @@ -1877,15 +1918,15 @@ interface ReadableWritablePair { * [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; + 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. @@ -1893,65 +1934,65 @@ declare class WritableStream { * [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; + 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; + 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); + constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); } declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); } interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); + highWaterMark?: (number | bigint); } interface ReadableStreamValuesOptions { - preventCancel?: boolean; + preventCancel?: boolean; } /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); + 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"); + 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; + 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; + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; + fatal?: boolean; + ignoreBOM?: boolean; } /** * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. @@ -1959,11 +2000,11 @@ interface TextDecoderStreamTextDecoderStreamInit { * [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; + 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. @@ -1971,123 +2012,123 @@ declare class ByteLengthQueuingStrategy implements QueuingStrategy number; + 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; + /** + * 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; + id?: string; + tag?: string; + message?: string; } declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; + 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; + 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; + readonly scheduledTime: Date; } interface TraceItemCustomEventInfo { } interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; + readonly scheduledTime: number; + readonly cron: string; } interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; + readonly queue: string; + readonly batchSize: number; } interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; } interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; } interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; + readonly scriptName: string | null; } interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoResponse { - readonly status: number; + readonly status: number; } interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; + readonly rpcMethod: string; } interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; + readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; } interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; } interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; + readonly timestamp: number; + readonly level: string; + readonly message: any; } interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; } interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; + readonly timestamp: number; + readonly channel: string; + readonly message: any; } interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; + readonly cpuTime: number; + readonly wallTime: number; } interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; + fromTrace(item: TraceItem): TraceMetrics; } /** * The URL interface represents an object providing static methods used for creating object URLs. @@ -2095,165 +2136,165 @@ interface UnsafeTraceMetrics { * [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; + 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 - ]>; + 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; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; + 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; + 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; + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; } interface URLPatternComponentResult { - input: string; - groups: Record; + 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; + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; } interface URLPatternOptions { - ignoreCase?: boolean; + 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. @@ -2261,53 +2302,36 @@ interface URLPatternOptions { * [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; + 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; + code?: number; + reason?: string; + wasClean?: boolean; } type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; + 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. @@ -2315,16 +2339,16 @@ type WebSocketEventMap = { * [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; + 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. @@ -2332,1381 +2356,2962 @@ declare var WebSocket: { * [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; + 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; - }; + new (): { + 0: WebSocket; + 1: WebSocket; + }; }; interface SqlStorage { - exec>(query: string, ...bindings: any[]): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; + 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; + 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; + 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); + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: (number | bigint); } interface SocketAddress { - hostname: string; - port: number; + hostname: string; + port: number; } interface TlsOptions { - expectedServerHostname?: string; + expectedServerHostname?: string; } interface SocketInfo { - remoteAddress?: string; - localAddress?: string; + 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; + 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; + 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; + 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; + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; +} +/** + * This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) + */ +interface MessagePort extends EventTarget { + /** + * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. + * + * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; + /** + * Disconnects the port, so that it is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void; + /** + * Begins dispatching messages received on the port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void; + get onmessage(): any | null; + set onmessage(value: any | null); +} +interface MessagePortPostMessageOptions { + transfer?: any[]; } type AiImageClassificationInput = { - image: number[]; + image: number[]; }; type AiImageClassificationOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; + 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[]; + 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; + description: string; }; declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; + 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[]; + 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; + description: string; }; declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } type AiObjectDetectionInput = { - image: number[]; + image: number[]; }; type AiObjectDetectionOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; } type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; + source: string; + sentences: string[]; }; type AiSentenceSimilarityOutput = number[]; declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; } type AiAutomaticSpeechRecognitionInput = { - audio: number[]; + audio: number[]; }; type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; }; declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; } type AiSummarizationInput = { - input_text: string; - max_length?: number; + input_text: string; + max_length?: number; }; type AiSummarizationOutput = { - summary: string; + summary: string; }; declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; } type AiTextClassificationInput = { - text: string; + text: string; }; type AiTextClassificationOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; } type AiTextEmbeddingsInput = { - text: string | string[]; + text: string | string[]; }; type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; + shape: number[]; + data: number[][]; }; declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; } type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; + 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[]; - }; + 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: "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; + name: string; + code: string; }; type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; + 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[]; + 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; - }[]; -} | ReadableStream; + response?: string; + tool_calls?: { + name: string; + arguments: unknown; + }[]; +}; declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; } type AiTextToSpeechInput = { - prompt: string; - lang?: string; + prompt: string; + lang?: string; }; type AiTextToSpeechOutput = Uint8Array | { - audio: string; + audio: string; }; declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; + 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; + 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; + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; } type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; + text: string; + target_lang: string; + source_lang?: string; }; type AiTranslationOutput = { - translated_text?: string; + translated_text?: string; }; declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; + 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[]; + /** + * 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; + /** + * 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; + 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; + /** + * 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; + 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; + 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[]; + /** + * 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; + /** + * 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; + 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?: string; - /** - * 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; + /** + * 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; + 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; + 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; + /** + * 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; -} -type Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding; + 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; - }[]; + 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"; + 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"; + 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; + 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; + /** + * 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; + /** + * 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; + 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; + /** + * 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 content of the message as a string. - */ - content: string; - }[]; - image?: number[] | 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; - }; - }; - }; - }; - })[]; - /** - * 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; + /** + * 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; - }[]; -} | ReadableStream; + /** + * 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; + 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; - }; + /** + * 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; - }; + 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; + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; } interface Ai_Cf_Baai_Bge_Reranker_Base_Input { - /** - * A query you wish to perform against the provided contexts. - */ - /** - * Number of returned results starting with the best score. - */ - top_k?: number; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; + /** + * 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; - }[]; + 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; + 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; - /** - * 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; + /** + * 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. 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; + /** + * 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 arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -} | string; + /** + * 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; + 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/baai/bge-base-en-v1.5": BaseAiTextEmbeddings; - "@cf/baai/bge-small-en-v1.5": BaseAiTextEmbeddings; - "@cf/baai/bge-large-en-v1.5": BaseAiTextEmbeddings; - "@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/meta/llama-3.3-70b-instruct-fp8-fast": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; - "@cf/meta/m2m100-1.2b": BaseAiTranslation; - "@cf/facebook/bart-large-cnn": BaseAiSummarization; - "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; - "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; - "@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-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; - "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; - "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@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 = { - gateway?: GatewayOptions; - returnRawResponse?: boolean; - prefix?: string; - extraHeaders?: object; + /** + * 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; + 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; + 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; - }[]; + 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 { } @@ -3714,116 +5319,118 @@ 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: AiModelList[Name]["inputs"], 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; + 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'; + 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; + 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; + 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; + 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; + '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; + 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 + 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 { } @@ -3831,121 +5438,133 @@ 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; + key: string; + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + value: string | number | boolean; }; type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; + 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; + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + rewrite_query?: boolean; }; type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean; + stream?: boolean; }; type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; + 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; + 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; + response: string; }; declare abstract class AutoRAG { - search(params: AutoRagSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; + 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; + /** + * 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'; + x?: number; + y?: number; + mode?: 'remainder' | 'box-center'; } /** * In addition to the properties you can set in the RequestInit dict @@ -3957,651 +5576,651 @@ interface BasicImageTransformationsGravityCoordinates { * 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; + 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; + /** + * 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"; + /** + * 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; + javascript?: boolean; + css?: boolean; + html?: boolean; } interface RequestInitCfPropertiesR2 { - /** - * Colo id of bucket that an object is stored in - */ - bucketColoId?: number; + /** + * 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; + /** + * [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[]; + /** + * 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; + /** + * 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; - }; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** 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: ""; + 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"; +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. */ @@ -4612,91 +6231,91 @@ declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" 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; - }; + 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; + success: true; + meta: D1Meta & Record; + error?: never; } type D1Result = D1Response & { - results: T[]; + 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"; + 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; + 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; + 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; + 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. @@ -4710,687 +6329,737 @@ 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; + /** + * 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; + /** + * 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; + send(message: EmailMessage): Promise; } declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; + 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 }; + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +/** + * Hello World binding to serve as an explanatory example. DO NOT USE + */ +interface HelloWorldBinding { + /** + * Retrieve the current stored value + */ + get(): Promise<{ + value: string; + ms?: number; + }>; + /** + * Set a new stored value + */ + set(value: string): Promise; } interface Hyperdrive { - /** - * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. - * - * Calling this method returns an 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; + /** + * 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: 'image/svg+xml'; } | { - format: string; - fileSize: number; - width: number; - height: number; + 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; - }; - }; + 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; + opacity?: number; + repeat?: boolean | string; + top?: number; + left?: number; + bottom?: number; + right?: number; +}; +type ImageInputOptions = { + encoding?: 'base64'; }; type ImageOutputOptions = { - format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; - quality?: number; - background?: string; + 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; + /** + * Get image metadata (type, width and height) + * @throws {@link ImagesError} with code 9412 if input is not an image + * @param stream The image bytes + */ + info(stream: ReadableStream, options?: ImageInputOptions): Promise; + /** + * Begin applying a series of transformations to an image + * @param stream The image bytes + * @returns A transform handle + */ + input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; } 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; -} + /** + * Apply transform next, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param transform + */ + transform(transform: ImageTransform): ImageTransformer; + /** + * Draw an image on this transformer, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param image The image (or transformer that will give the image) to draw + * @param options The options configuring how to draw the image + */ + draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; + /** + * Retrieve the image that results from applying the transforms to the + * provided input + * @param options Options that apply to the output e.g. output format + */ + output(options: ImageOutputOptions): Promise; +} +type ImageTransformationOutputOptions = { + encoding?: 'base64'; +}; interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(): ReadableStream; + /** + * The image as a response, ready to store in cache or return to users + */ + response(): Response; + /** + * The content type of the returned image + */ + contentType(): string; + /** + * The bytes of the response + */ + image(options?: ImageTransformationOutputOptions): ReadableStream; } interface ImagesError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; + 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; + 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; + 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; + 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; - } + 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; + // 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; + // Key Identifier of the JWK + readonly kid: string; } interface RateLimitOptions { - key: string; + key: string; } interface RateLimitOutcome { - success: boolean; + 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; + /** + * 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; - }; + // 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 { - } + interface Env { + } +} +declare module 'cloudflare:node' { + export interface DefaultHandler { + 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 function httpServerHandler(options: { + port: number; + }, handlers?: Omit): DefaultHandler; } 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 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; + 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 function waitUntil(promise: Promise): void; + 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; + /** + * 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 }; + 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 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 op?: string; - readonly info?: FetchEventInfo | JsRpcEventInfo | Attribute[]; - } - 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 | Attribute[]; - } - interface Link { - readonly type: "link"; - readonly label?: string; - readonly traceId: string; - readonly invocationId: string; - readonly spanId: string; - } - interface Attribute { - readonly type: "attribute"; - readonly name: string; - readonly value: string | string[] | boolean | boolean[] | number | number[]; - } - type Mark = DiagnosticChannelEvent | Exception | Log | Return | Link | 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 | Mark; - } - type TailEventHandler = (event: TailEvent) => void | Promise; - type TailEventHandlerName = "onset" | "outcome" | "hibernate" | "spanOpen" | "spanClose" | "diagnosticChannel" | "exception" | "log" | "return" | "link" | "attribute"; - type TailEventHandlerObject = Record; - type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; + interface Header { + readonly name: string; + readonly value: string; + } + interface FetchEventInfo { + readonly type: "fetch"; + readonly method: string; + readonly url: string; + readonly cfJson?: object; + readonly headers: Header[]; + } + interface JsRpcEventInfo { + readonly type: "jsrpc"; + 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: object; + } + 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[]; + } + type EventType = Onset | Outcome | Hibernate | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Link | Attributes; + interface TailEvent { + readonly invocationId: string; + readonly spanId: string; + readonly timestamp: Date; + readonly sequence: number; + readonly event: Event; + } + type TailEventHandler = (event: TailEvent) => void | Promise; + type TailEventHandlerObject = { + outcome?: TailEventHandler; + hibernate?: TailEventHandler; + spanOpen?: TailEventHandler; + spanClose?: TailEventHandler; + diagnosticChannel?: TailEventHandler; + exception?: TailEventHandler; + log?: TailEventHandler; + return?: TailEventHandler; + link?: TailEventHandler; + attributes?: TailEventHandler; + }; + type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: @@ -5405,8 +7074,8 @@ type VectorizeVectorMetadataValue = string | number | boolean | string[]; type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; type VectorFloatArray = Float32Array | Float64Array; interface VectorizeError { - code?: number; - error: string; + code?: number; + error: string; } /** * Comparison logic/operation to use for metadata filtering. @@ -5418,9 +7087,9 @@ 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; - }; + [field: string]: Exclude | null | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; + }; }; /** * Supported distance metrics for an index. @@ -5438,20 +7107,20 @@ type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; */ type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none"; interface VectorizeQueryOptions { - topK?: number; - namespace?: string; - returnValues?: boolean; - returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; - filter?: VectorizeVectorMetadataFilter; + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; + filter?: VectorizeVectorMetadataFilter; } /** * Information about the configuration of an index. */ type VectorizeIndexConfig = { - dimensions: number; - metric: VectorizeDistanceMetric; + 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 + 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. @@ -5460,56 +7129,56 @@ type VectorizeIndexConfig = { * 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; + /** 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; + /** 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; + /** 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; + /** 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; + matches: VectorizeMatch[]; + count: number; } /** * Results of an operation that performed a mutation on a set of vectors. @@ -5519,18 +7188,18 @@ interface VectorizeMatches { * 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; + /* 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; + /** The unique identifier for the async mutation operation containing the changeset. */ + mutationId: string; } /** * A Vectorize Vector Search Index for querying vectors/embeddings. @@ -5539,42 +7208,42 @@ interface VectorizeAsyncMutation { * 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; + /** + * 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. @@ -5582,176 +7251,187 @@ declare abstract class VectorizeIndex { * 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; + /** + * 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; + /** 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; + /** + * 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; - }; + /** + * 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; + /** + * @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); - } + /** + * 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; -} + /** + * 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; + /** + * 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; + 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; + 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; + 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; } From 8a356052f0d30393ccc162d7e84f25a6122827ab Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Sun, 10 Aug 2025 14:35:32 +0800 Subject: [PATCH 02/17] Rename 'Support' to 'Generation' in OpenAPI documentation and related endpoints --- scripts/generate-openapi.mjs | 2 +- src/index.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/generate-openapi.mjs b/scripts/generate-openapi.mjs index 76e2cfd..a5bee14 100644 --- a/scripts/generate-openapi.mjs +++ b/scripts/generate-openapi.mjs @@ -36,7 +36,7 @@ const options = { { name: 'Airports', description: 'Lookup and metadata endpoints for airports.' }, { name: 'Divisions', description: 'Division management, membership, and associated airport access.' }, { name: 'Points', description: 'Creation and management of lighting/navigation point data.' }, - { name: 'Support', description: 'Utilities for generating light support / BARS XML artifacts.' }, + { name: 'Generation', description: 'Utilities for generating light support / BARS XML artifacts.' }, { name: 'NOTAM', description: 'Global NOTAM retrieval and (staff) updates.' }, { name: 'Contributions', description: 'Community lighting package submission, review, and leaderboard.' }, { name: 'Staff', description: 'Restricted staff-only operational and moderation endpoints (hidden from public docs).' }, diff --git a/src/index.ts b/src/index.ts index 2dbe822..80330ab 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1675,14 +1675,14 @@ app.get('/points', }); }); -// Light Support endpoints +// MSFS Light Supports and BARS XML generation endpoint /** * @openapi * /supports/generate: * post: * summary: Generate Light Supports and BARS XML * tags: - * - Support + * - Generation * description: Upload raw XML and generate both light supports XML and processed BARS XML. * requestBody: * required: true From 9381ddda92a6ed30e358a622a57e979ecbee7c07 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Sun, 10 Aug 2025 21:03:04 +0800 Subject: [PATCH 03/17] Refactor code structure for improved readability and maintainability --- .github/ISSUE_TEMPLATE/bug_report.md | 12 +- .github/ISSUE_TEMPLATE/config.yml | 2 +- .github/ISSUE_TEMPLATE/feature_request.md | 2 +- .github/ISSUE_TEMPLATE/task_request.md | 9 +- .github/PULL_REQUEST_TEMPLATE.md | 17 +- .github/dependabot.yml | 18 +- CODE_OF_CONDUCT.md | 22 +- CONTRIBUTING.md | 5 +- README.md | 3 +- SECURITY.md | 8 +- openapi.json | 30 +- scripts/generate-openapi.mjs | 78 +- src/index.ts | 919 +- src/network/connection.ts | 34 +- src/services/airport.ts | 56 +- src/services/auth.ts | 104 +- src/services/bars/handlers.ts | 113 +- src/services/cache.ts | 270 +- src/services/contributions.ts | 107 +- src/services/database-context.ts | 287 +- src/services/database-session.ts | 587 +- src/services/divisions.ts | 89 +- src/services/github.ts | 384 +- src/services/id.ts | 5 +- src/services/notam.ts | 4 +- src/services/points.ts | 151 +- src/services/polygons.ts | 97 +- src/services/posthog.ts | 237 +- src/services/roles.ts | 12 +- src/services/service-pool.ts | 220 +- src/services/support.ts | 2 +- src/services/users.ts | 28 +- src/services/vatsim.ts | 2 +- src/types.ts | 24 +- worker-configuration.d.ts | 13027 ++++++++++---------- 35 files changed, 8912 insertions(+), 8053 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 771a644..0609f75 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,7 +1,7 @@ --- name: 🐛 Bug report about: Report a problem or unexpected behavior -title: "[BUG] " +title: '[BUG] ' labels: ['bug'] assignees: [] --- @@ -11,6 +11,7 @@ A clear and concise description of what the bug is. **How to reproduce** Steps to reproduce the behavior (e.g.,): + 1. Go to '...' 2. Click on '...' 3. Observe that '...' occurs @@ -21,10 +22,11 @@ A clear and concise description of what you expected to happen. **Screenshots or logs (if applicable)** If applicable, add screenshots or copy/paste logs to help explain your problem. -**Environment (if relevant)** -- OS / Platform: [e.g. Windows 10, Ubuntu 20.04, macOS 11] -- Version (if applicable): [e.g. 1.2.3] +**Environment (if relevant)** + +- OS / Platform: [e.g. Windows 10, Ubuntu 20.04, macOS 11] +- Version (if applicable): [e.g. 1.2.3] - Additional info: [e.g. browser, plugin version, external dependency versions] **Additional context** -Add any other context about the problem here. \ No newline at end of file +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index ec4bb38..3ba13e0 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1 +1 @@ -blank_issues_enabled: false \ No newline at end of file +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 3a7a797..c254c5e 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,7 +1,7 @@ --- name: ✨ Feature request about: Suggest a new feature or enhancement -title: "[FEATURE] " +title: '[FEATURE] ' labels: ['enhancement'] assignees: [] --- diff --git a/.github/ISSUE_TEMPLATE/task_request.md b/.github/ISSUE_TEMPLATE/task_request.md index da046b2..3ec0b7a 100644 --- a/.github/ISSUE_TEMPLATE/task_request.md +++ b/.github/ISSUE_TEMPLATE/task_request.md @@ -1,7 +1,7 @@ --- name: ✅ Task / chore about: A general task or chore (e.g., “update docs,” “refactor code”) -title: "[TASK] " +title: '[TASK] ' labels: ['task'] assignees: [] --- @@ -12,9 +12,10 @@ What needs to be done? Briefly describe the scope of the work. **Why is this task needed?** Explain why it’s important (e.g., “fixes a bug,” “improves performance,” “updates documentation”). -**Acceptance criteria** -- [ ] Criterion 1 -- [ ] Criterion 2 +**Acceptance criteria** + +- [ ] Criterion 1 +- [ ] Criterion 2 - [ ] Criterion 3 (if any) **Additional notes** diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 5f17f27..faa04a1 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,18 +1,21 @@ ## Summary - + ## Changes Made + -- -- -- + +- +- +- ## Additional Information - + ## Author Information + **Discord Username:** **VATSIM CID:** @@ -20,5 +23,5 @@ ### Checklist: -* [ ] Have you followed the guidelines in our Contributing document? -* [ ] Have you checked to ensure there aren't other open Pull Requests for the same update/change? +- [ ] Have you followed the guidelines in our Contributing document? +- [ ] Have you checked to ensure there aren't other open Pull Requests for the same update/change? diff --git a/.github/dependabot.yml b/.github/dependabot.yml index bc61c55..5ce8324 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,17 +1,17 @@ version: 2 updates: - - package-ecosystem: "npm" - directory: "/" + - package-ecosystem: 'npm' + directory: '/' schedule: - interval: "weekly" + interval: 'weekly' open-pull-requests-limit: 5 - - package-ecosystem: "cargo" - directory: "/" + - package-ecosystem: 'cargo' + directory: '/' schedule: - interval: "weekly" + interval: 'weekly' open-pull-requests-limit: 5 - - package-ecosystem: "nuget" - directory: "/" + - package-ecosystem: 'nuget' + directory: '/' schedule: - interval: "weekly" + interval: 'weekly' open-pull-requests-limit: 5 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 6079532..b21f9fd 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -17,23 +17,23 @@ diverse, inclusive, and healthy community. Examples of behavior that contributes to a positive environment for our community include: -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall +- Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: -* The use of sexualized language or imagery, and sexual attention or advances of +- The use of sexualized language or imagery, and sexual attention or advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email address, +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a +- Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities @@ -129,4 +129,4 @@ For answers to common questions about this code of conduct, see the FAQ at [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq -[translations]: https://www.contributor-covenant.org/translations \ No newline at end of file +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4f1db25..f53f724 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,6 +20,7 @@ Thank you for your interest in contributing to BARS Core! This guide will help y cd Core ``` +
2. **Install Dependencies** @@ -37,11 +38,9 @@ Thank you for your interest in contributing to BARS Core! This guide will help y **Set up Cloudflare configuration:** The `wrangler.toml` file is already configured and safe to use as-is. For local testing, you'll need to: - 1. Create your own D1 SQL database in the [Cloudflare Dashboard](https://dash.cloudflare.com) (Storage & Databases > D1 SQL)
- 2. Edit `wrangler.toml` and update the database configuration (see comments in the file): - `account_id`: Your Cloudflare account ID (found in dash.cloudflare.com/your-id/home) - `VATSIM_CLIENT_ID`: Your VATSIM Connect application client ID @@ -49,7 +48,6 @@ Thank you for your interest in contributing to BARS Core! This guide will help y - `database_id`: Your D1 database ID (found in your database page)
- 3. Update `package.json` scripts to use your database name: - Replace `bars-db` with your database name in the `update-db-local` and `update-db` scripts - Example: `"update-db": "wrangler d1 execute bars-dev-example --remote --file schema.sql",` @@ -72,7 +70,6 @@ Thank you for your interest in contributing to BARS Core! This guide will help y
Edit `.dev.vars` and add your API credentials: - - `VATSIM_CLIENT_SECRET`: Your VATSIM Connect application secret - `AIRPORTDB_API_KEY`: Your [AirportDB](https://airportdb.io/) API key (optional for basic testing) diff --git a/README.md b/README.md index 5d9e161..cf627bc 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,6 @@ ![GitHub License](https://img.shields.io/github/license/stopbars/Core) [![Discord](https://img.shields.io/discord/1323993176318414889.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://stopbars.com/discord) - Core is the foundational backend infrastructure that powers BARS. This service provides comprehensive APIs, backend systems, and real-time capabilities for all BARS services & applications across the product suite.
@@ -31,4 +30,4 @@ If you find a bug or have a feature suggestion, please submit an issue [on our G ## Disclaimer -BARS is an **independent third-party** software project. **We are not affiliated** with, endorsed by, or connected to VATSIM, vatSys, Microsoft Flight Simulator, or any other simulation, controller client supported by our software. \ No newline at end of file +BARS is an **independent third-party** software project. **We are not affiliated** with, endorsed by, or connected to VATSIM, vatSys, Microsoft Flight Simulator, or any other simulation, controller client supported by our software. diff --git a/SECURITY.md b/SECURITY.md index db6c0ed..3d89592 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,10 +4,10 @@ We actively maintain and apply security patches to the latest stable version of this project. -| Version | Supported | -|---------|--------------------| -| Latest | ✅ Yes | -| Older | ❌ No | +| Version | Supported | +| ------- | --------- | +| Latest | ✅ Yes | +| Older | ❌ No | ## Reporting a Vulnerability diff --git a/openapi.json b/openapi.json index 4153e52..3f4e42d 100644 --- a/openapi.json +++ b/openapi.json @@ -50,7 +50,7 @@ "description": "Creation and management of lighting/navigation point data." }, { - "name": "Support", + "name": "Generation", "description": "Utilities for generating light support / BARS XML artifacts." }, { @@ -1106,7 +1106,7 @@ "post": { "summary": "Generate Light Supports and BARS XML", "tags": [ - "Support" + "Generation" ], "description": "Upload raw XML and generate both light supports XML and processed BARS XML.", "requestBody": { @@ -1560,6 +1560,32 @@ } } }, + "/maps/{icao}/latest": { + "get": { + "summary": "Get latest approved BARS map XML (raw content) for an airport", + "tags": [ + "Generation" + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "BARS XML document returned inline (application/xml)" + }, + "404": { + "description": "Not found" + } + } + } + }, "/cdn/files/{fileKey}": { "get": { "summary": "Download a file from CDN", diff --git a/scripts/generate-openapi.mjs b/scripts/generate-openapi.mjs index a5bee14..0a8515d 100644 --- a/scripts/generate-openapi.mjs +++ b/scripts/generate-openapi.mjs @@ -9,45 +9,45 @@ const __dirname = path.dirname(__filename); const root = path.resolve(__dirname, '..'); const options = { - definition: { - openapi: '3.0.4', - info: { - title: 'BARS Core API', - version: '2.0.0', - description: 'API documentation for BARS Core', - contact: { - name: 'BARS Support', - email: 'support@stopbars.com', - url: 'https://stopbars.com/support' - } - }, - externalDocs: { - description: 'Find more info here', - url: 'https://docs.stopbars.com' - }, - servers: [ - { url: 'https://v2.stopbars.com', description: 'Production' }, - { url: 'http://localhost:8787', description: 'Local development (wrangler dev)' } - ], - tags: [ - { name: 'RealTime', description: 'WebSocket connection and real-time state interaction endpoints.' }, - { name: 'State', description: 'Endpoints for retrieving current system or airport lighting/network state.' }, - { name: 'Auth', description: 'Authentication, account management, and API key lifecycle.' }, - { name: 'Airports', description: 'Lookup and metadata endpoints for airports.' }, - { name: 'Divisions', description: 'Division management, membership, and associated airport access.' }, - { name: 'Points', description: 'Creation and management of lighting/navigation point data.' }, - { name: 'Generation', description: 'Utilities for generating light support / BARS XML artifacts.' }, - { name: 'NOTAM', description: 'Global NOTAM retrieval and (staff) updates.' }, - { name: 'Contributions', description: 'Community lighting package submission, review, and leaderboard.' }, - { name: 'Staff', description: 'Restricted staff-only operational and moderation endpoints (hidden from public docs).' }, - { name: 'CDN', description: 'File storage, upload, listing, and deletion via CDN-backed storage.' }, - { name: 'EuroScope', description: 'EuroScope sector file upload, listing, and permission checks by ICAO.' }, - { name: 'Cache', description: 'Administrative cache management operations.' }, - { name: 'GitHub', description: 'Repository contributor information.' }, - { name: 'System', description: 'System health and OpenAPI specification discovery.' } - ] - }, - apis: [path.join(root, 'src', '**', '*.ts')] + definition: { + openapi: '3.0.4', + info: { + title: 'BARS Core API', + version: '2.0.0', + description: 'API documentation for BARS Core', + contact: { + name: 'BARS Support', + email: 'support@stopbars.com', + url: 'https://stopbars.com/support', + }, + }, + externalDocs: { + description: 'Find more info here', + url: 'https://docs.stopbars.com', + }, + servers: [ + { url: 'https://v2.stopbars.com', description: 'Production' }, + { url: 'http://localhost:8787', description: 'Local development (wrangler dev)' }, + ], + tags: [ + { name: 'RealTime', description: 'WebSocket connection and real-time state interaction endpoints.' }, + { name: 'State', description: 'Endpoints for retrieving current system or airport lighting/network state.' }, + { name: 'Auth', description: 'Authentication, account management, and API key lifecycle.' }, + { name: 'Airports', description: 'Lookup and metadata endpoints for airports.' }, + { name: 'Divisions', description: 'Division management, membership, and associated airport access.' }, + { name: 'Points', description: 'Creation and management of lighting/navigation point data.' }, + { name: 'Generation', description: 'Utilities for generating light support / BARS XML artifacts.' }, + { name: 'NOTAM', description: 'Global NOTAM retrieval and (staff) updates.' }, + { name: 'Contributions', description: 'Community lighting package submission, review, and leaderboard.' }, + { name: 'Staff', description: 'Restricted staff-only operational and moderation endpoints (hidden from public docs).' }, + { name: 'CDN', description: 'File storage, upload, listing, and deletion via CDN-backed storage.' }, + { name: 'EuroScope', description: 'EuroScope sector file upload, listing, and permission checks by ICAO.' }, + { name: 'Cache', description: 'Administrative cache management operations.' }, + { name: 'GitHub', description: 'Repository contributor information.' }, + { name: 'System', description: 'System health and OpenAPI specification discovery.' }, + ], + }, + apis: [path.join(root, 'src', '**', '*.ts')], }; const openapiSpec = swaggerJsdoc(options); diff --git a/src/index.ts b/src/index.ts index 80330ab..63b1720 100644 --- a/src/index.ts +++ b/src/index.ts @@ -88,7 +88,10 @@ app.use('*', async (c, next) => { // Env-driven ignore list: comma separated exact paths or prefix* globs const ignoreRaw = (c.env as any).ANALYTICS_IGNORE as string | undefined; if (ignoreRaw) { - const ignores = ignoreRaw.split(',').map(s => s.trim()).filter(Boolean); + const ignores = ignoreRaw + .split(',') + .map((s) => s.trim()) + .filter(Boolean); for (const pattern of ignores) { if (pattern.endsWith('*')) { const prefix = pattern.slice(0, -1); @@ -99,12 +102,16 @@ app.use('*', async (c, next) => { } } const posthog = ServicePool.getPostHog(c.env); - posthog.track('API Request', { - path, - method: c.req.method, - status: c.res?.status ?? 0, - duration_ms: Date.now() - start, - }, 'anonymous'); + posthog.track( + 'API Request', + { + path, + method: c.req.method, + status: c.res?.status ?? 0, + duration_ms: Date.now() - start, + }, + 'anonymous', + ); } catch (err) { // eslint-disable-next-line no-console console.warn('[Analytics] failed', err instanceof Error ? err.message : err); @@ -112,11 +119,14 @@ app.use('*', async (c, next) => { }); // Add CORS middleware -app.use('*', cors({ - origin: '*', - allowHeaders: ['Content-Type', 'Authorization', 'X-Vatsim-Token', 'Upgrade', 'X-Client-Type'], - allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], -})); +app.use( + '*', + cors({ + origin: '*', + allowHeaders: ['Content-Type', 'Authorization', 'X-Vatsim-Token', 'Upgrade', 'X-Client-Type'], + allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + }), +); // Connect endpoint /** @@ -158,9 +168,12 @@ app.use('*', cors({ app.get('/connect', async (c) => { const upgradeHeader = c.req.header('Upgrade'); if (upgradeHeader !== 'websocket') { - return c.json({ - message: 'This endpoint is for WebSocket connections only. Use a WebSocket client to test.', - }, 400); + return c.json( + { + message: 'This endpoint is for WebSocket connections only. Use a WebSocket client to test.', + }, + 400, + ); } const airportId = c.req.query('airport'); @@ -213,9 +226,12 @@ app.get('/connect', async (c) => { app.get('/state', async (c) => { const airport = c.req.query('airport'); if (!airport) { - return c.json({ - error: 'Airport parameter required', - }, 400); + return c.json( + { + error: 'Airport parameter required', + }, + 400, + ); } // Create database context for this request with bookmark handling @@ -227,7 +243,7 @@ app.get('/state', async (c) => { await dbContext.db.executeWrite("DELETE FROM active_objects WHERE last_updated <= datetime('now', '-2 day')"); const activeObjectsResult = await dbContext.db.executeRead( - "SELECT id, name FROM active_objects WHERE last_updated > datetime('now', '-2 day')" + "SELECT id, name FROM active_objects WHERE last_updated > datetime('now', '-2 day')", ); const allStates = await Promise.all( @@ -274,9 +290,12 @@ app.get('/state', async (c) => { const obj = c.env.BARS.get(id); if (airport.length !== 4) { - return dbContext.jsonResponse({ - error: 'Invalid airport ICAO', - }, { status: 400 }); + return dbContext.jsonResponse( + { + error: 'Invalid airport ICAO', + }, + { status: 400 }, + ); } const stateRequest = new Request(`https://internal/state?airport=${airport}`, { @@ -367,7 +386,11 @@ app.get('/auth/account', async (c) => { if ((!user.full_name || user.full_name.trim() === '') && (vatsimUser.first_name || vatsimUser.last_name)) { const newFullName = [vatsimUser.first_name, vatsimUser.last_name].filter(Boolean).join(' ').trim(); if (newFullName) { - try { await auth.updateFullName(user.id, newFullName); } catch { /* ignore */ } + try { + await auth.updateFullName(user.id, newFullName); + } catch { + /* ignore */ + } const refreshed = await auth.getUserByVatsimId(vatsimUser.id); if (refreshed) user = refreshed; } @@ -419,7 +442,11 @@ app.put('/auth/display-mode', async (c) => { if (!vatsimToken) return c.text('Unauthorized', 401); let body: any; - try { body = await c.req.json(); } catch { return c.json({ error: 'Invalid JSON body' }, 400); } + try { + body = await c.req.json(); + } catch { + return c.json({ error: 'Invalid JSON body' }, 400); + } const rawMode = body?.mode; const mode = Number(rawMode); @@ -489,7 +516,7 @@ app.post('/auth/regenerate-api-key', async (c) => { // Check when the user last regenerated their API key using session-aware query const lastRegenerationResult = await dbContext.db.executeRead<{ last_api_key_regen: string }>( 'SELECT last_api_key_regen FROM users WHERE id = ?', - [user.id] + [user.id], ); const lastRegeneration = lastRegenerationResult.results[0]; @@ -506,11 +533,14 @@ app.post('/auth/regenerate-api-key', async (c) => { const remainingHours = Math.floor(remainingMs / (60 * 60 * 1000)); const remainingMinutes = Math.floor((remainingMs % (60 * 60 * 1000)) / (60 * 1000)); - return dbContext.jsonResponse({ - error: 'Rate limited', - message: `You can only regenerate your API key once every 24 hours. Please try again in ${remainingHours} hour${remainingHours !== 1 ? 's' : ''}${remainingMinutes > 0 ? ` and ${remainingMinutes} minute${remainingMinutes !== 1 ? 's' : ''}` : ''}.`, - retryAfter: Math.ceil(remainingMs / 1000), - }, { status: 429 }); + return dbContext.jsonResponse( + { + error: 'Rate limited', + message: `You can only regenerate your API key once every 24 hours. Please try again in ${remainingHours} hour${remainingHours !== 1 ? 's' : ''}${remainingMinutes > 0 ? ` and ${remainingMinutes} minute${remainingMinutes !== 1 ? 's' : ''}` : ''}.`, + retryAfter: Math.ceil(remainingMs / 1000), + }, + { status: 429 }, + ); } } @@ -518,20 +548,20 @@ app.post('/auth/regenerate-api-key', async (c) => { const newApiKey = await auth.regenerateApiKey(user.id); // Update the last regeneration timestamp using session-aware write - await dbContext.db.executeWrite( - "UPDATE users SET last_api_key_regen = datetime('now') WHERE id = ?", - [user.id] - ); + await dbContext.db.executeWrite("UPDATE users SET last_api_key_regen = datetime('now') WHERE id = ?", [user.id]); return dbContext.jsonResponse({ success: true, apiKey: newApiKey, }); } catch (error) { - return dbContext.jsonResponse({ - error: 'Failed to regenerate API key', - message: error instanceof Error ? error.message : 'Unknown error', - }, { status: 500 }); + return dbContext.jsonResponse( + { + error: 'Failed to regenerate API key', + message: error instanceof Error ? error.message : 'Unknown error', + }, + { status: 500 }, + ); } finally { dbContext.close(); } @@ -593,31 +623,29 @@ app.delete('/auth/delete', async (c) => { * 401: * description: Unauthorized */ -app.get('/auth/is-staff', - withCache(CacheKeys.withUser('is-staff'), 3600, 'auth'), - async (c) => { - const authHeader = c.req.header('Authorization'); - if (!authHeader) { - return c.text('Unauthorized', 401); - } +app.get('/auth/is-staff', withCache(CacheKeys.withUser('is-staff'), 3600, 'auth'), async (c) => { + const authHeader = c.req.header('Authorization'); + if (!authHeader) { + return c.text('Unauthorized', 401); + } - const token = authHeader.replace('Bearer ', ''); + const token = authHeader.replace('Bearer ', ''); - const vatsim = ServicePool.getVatsim(c.env); - const auth = ServicePool.getAuth(c.env); - const roles = ServicePool.getRoles(c.env); + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); - const vatsimUser = await vatsim.getUser(token); - const user = await auth.getUserByVatsimId(vatsimUser.id); + const vatsimUser = await vatsim.getUser(token); + const user = await auth.getUserByVatsimId(vatsimUser.id); - if (!user) { - return c.text('Unauthorized', 401); - } + if (!user) { + return c.text('Unauthorized', 401); + } - const isStaff = await roles.isStaff(user.id); - const role = await roles.getUserRole(user.id); - return c.json({ isStaff, role }); - }); + const isStaff = await roles.isStaff(user.id); + const role = await roles.getUserRole(user.id); + return c.json({ isStaff, role }); +}); // Airports endpoint /** @@ -648,7 +676,8 @@ app.get('/auth/is-staff', * 404: * description: Airport not found */ -app.get('/airports', +app.get( + '/airports', withCache(CacheKeys.fromUrl, 31536000, 'airports'), // Cache for 1 year because airports data doesn't change ever :P async (c) => { const airports = ServicePool.getAirport(c.env); @@ -682,7 +711,7 @@ app.get('/airports', } catch (error) { return c.json({ error: 'Failed to fetch airport data' }, 500); } - } + }, ); // Nearest airport (public, unauthenticated) @@ -713,17 +742,22 @@ app.get('/airports', * 404: * description: No airport found */ -app.get('/airports/nearest', - withCache((req) => { - // Bucket cache key by ~5NM (~9.26km). 1 degree lat ~111km => bucket size deg ≈ 9.26/111 ≈ 0.083 - const url = new URL(req.url); - const lat = parseFloat(url.searchParams.get('lat') || '0'); - const lon = parseFloat(url.searchParams.get('lon') || '0'); - const bucketDeg = 0.083; // ~5NM - const bucketLat = Math.round(lat / bucketDeg); - const bucketLon = Math.round(lon / bucketDeg); - return `/airports/nearest/${bucketLat}_${bucketLon}`; - }, 600, 'airports'), +app.get( + '/airports/nearest', + withCache( + (req) => { + // Bucket cache key by ~5NM (~9.26km). 1 degree lat ~111km => bucket size deg ≈ 9.26/111 ≈ 0.083 + const url = new URL(req.url); + const lat = parseFloat(url.searchParams.get('lat') || '0'); + const lon = parseFloat(url.searchParams.get('lon') || '0'); + const bucketDeg = 0.083; // ~5NM + const bucketLat = Math.round(lat / bucketDeg); + const bucketLon = Math.round(lon / bucketDeg); + return `/airports/nearest/${bucketLat}_${bucketLon}`; + }, + 600, + 'airports', + ), async (c) => { const latStr = c.req.query('lat'); const lonStr = c.req.query('lon'); @@ -745,7 +779,7 @@ app.get('/airports/nearest', } catch (err) { return c.json({ error: 'Failed to find nearest airport' }, 500); } - } + }, ); // Divisions routes @@ -844,7 +878,7 @@ divisionsApp.post('/', async (c) => { return c.text('Forbidden', 403); } - const { name, headVatsimId } = await c.req.json() as CreateDivisionPayload; + const { name, headVatsimId } = (await c.req.json()) as CreateDivisionPayload; const division = await divisions.createDivision(name, headVatsimId); return c.json(division); }); @@ -895,7 +929,7 @@ divisionsApp.put('/:id', async (c) => { const existing = await divisions.getDivision(id); if (!existing) return c.text('Division not found', 404); - const body = await c.req.json() as { name: string }; + const body = (await c.req.json()) as { name: string }; if (!body.name || !body.name.trim()) return c.text('Invalid name', 400); const updated = await divisions.updateDivisionName(id, body.name.trim()); @@ -956,15 +990,13 @@ divisionsApp.delete('/:id', async (c) => { * 200: * description: User divisions returned */ -divisionsApp.get('/user', - withCache(CacheKeys.withUser('divisions'), 3600, 'divisions'), - async (c) => { - const vatsimUser = c.get('vatsimUser'); - const divisions = ServicePool.getDivisions(c.env); +divisionsApp.get('/user', withCache(CacheKeys.withUser('divisions'), 3600, 'divisions'), async (c) => { + const vatsimUser = c.get('vatsimUser'); + const divisions = ServicePool.getDivisions(c.env); - const userDivisions = await divisions.getUserDivisions(vatsimUser.id); - return c.json(userDivisions); - }); + const userDivisions = await divisions.getUserDivisions(vatsimUser.id); + return c.json(userDivisions); +}); // GET /divisions/:id - Get division details /** @@ -987,19 +1019,17 @@ divisionsApp.get('/user', * 404: * description: Division not found */ -divisionsApp.get('/:id', - withCache(CacheKeys.fromParams('id'), 2592000, 'divisions'), - async (c) => { - const divisionId = parseInt(c.req.param('id')); - const divisions = ServicePool.getDivisions(c.env); +divisionsApp.get('/:id', withCache(CacheKeys.fromParams('id'), 2592000, 'divisions'), async (c) => { + const divisionId = parseInt(c.req.param('id')); + const divisions = ServicePool.getDivisions(c.env); - const division = await divisions.getDivision(divisionId); - if (!division) { - return c.text('Division not found', 404); - } + const division = await divisions.getDivision(divisionId); + if (!division) { + return c.text('Division not found', 404); + } - return c.json(division); - }); + return c.json(division); +}); // GET /divisions/:id/members - List division members /** @@ -1086,7 +1116,7 @@ divisionsApp.post('/:id/members', async (c) => { return c.text('Forbidden', 403); } - const { vatsimId, role } = await c.req.json() as AddMemberPayload; + const { vatsimId, role } = (await c.req.json()) as AddMemberPayload; const member = await divisions.addMember(divisionId, vatsimId, role); return c.json(member); }); @@ -1164,21 +1194,19 @@ divisionsApp.delete('/:id/members/:vatsimId', async (c) => { * 404: * description: Division not found */ -divisionsApp.get('/:id/airports', - withCache(CacheKeys.fromParams('id'), 600, 'divisions'), - async (c) => { - const divisionId = parseInt(c.req.param('id')); - const divisions = ServicePool.getDivisions(c.env); +divisionsApp.get('/:id/airports', withCache(CacheKeys.fromParams('id'), 600, 'divisions'), async (c) => { + const divisionId = parseInt(c.req.param('id')); + const divisions = ServicePool.getDivisions(c.env); - // Verify division exists - const division = await divisions.getDivision(divisionId); - if (!division) { - return c.text('Division not found', 404); - } + // Verify division exists + const division = await divisions.getDivision(divisionId); + if (!division) { + return c.text('Division not found', 404); + } - const airports = await divisions.getDivisionAirports(divisionId); - return c.json(airports); - }); + const airports = await divisions.getDivisionAirports(divisionId); + return c.json(airports); +}); // POST /divisions/:id/airports - Request airport addition (requires division membership) /** @@ -1223,7 +1251,7 @@ divisionsApp.post('/:id/airports', async (c) => { return c.text('Division not found', 404); } - const { icao } = await c.req.json() as RequestAirportPayload; + const { icao } = (await c.req.json()) as RequestAirportPayload; const airport = await divisions.requestAirport(divisionId, icao, vatsimUser.id); return c.json(airport); }); @@ -1283,7 +1311,7 @@ divisionsApp.post('/:id/airports/:airportId/approve', async (c) => { return c.text('Forbidden', 403); } - const { approved } = await c.req.json() as ApproveAirportPayload; + const { approved } = (await c.req.json()) as ApproveAirportPayload; const airport = await divisions.approveAirport(airportId, vatsimUser.id, approved); return c.json(airport); }); @@ -1309,7 +1337,8 @@ app.route('/divisions', divisionsApp); * 400: * description: Invalid ICAO */ -app.get('/airports/:icao/points', +app.get( + '/airports/:icao/points', withCache(CacheKeys.fromUrl, 600, 'airports'), // 1296000 - For after beta async (c) => { const airportId = c.req.param('icao'); @@ -1323,7 +1352,8 @@ app.get('/airports/:icao/points', const airportPoints = await points.getAirportPoints(airportId); return c.json(airportPoints); - }); + }, +); /** * @openapi @@ -1375,7 +1405,7 @@ app.post('/airports/:icao/points', async (c) => { const points = ServicePool.getPoints(c.env); - const pointData = await c.req.json() as PointData; + const pointData = (await c.req.json()) as PointData; const newPoint = await points.createPoint(airportId, user.vatsim_id, pointData); return c.json(newPoint, 201); }); @@ -1429,7 +1459,7 @@ app.post('/airports/:icao/points/batch', async (c) => { const points = ServicePool.getPoints(c.env); - const changeset = await c.req.json() as PointChangeset; + const changeset = (await c.req.json()) as PointChangeset; const newPoints = await points.applyChangeset(airportId, user.vatsim_id, changeset); return c.json(newPoints, 201); }); @@ -1492,7 +1522,7 @@ app.put('/airports/:icao/points/:id', async (c) => { const points = ServicePool.getPoints(c.env); - const updates = await c.req.json() as Partial; + const updates = (await c.req.json()) as Partial; const updatedPoint = await points.updatePoint(pointId, vatsimUser.id, updates); return c.json(updatedPoint); }); @@ -1577,25 +1607,23 @@ app.delete('/airports/:icao/points/:id', async (c) => { * 404: * description: Not found */ -app.get('/points/:id', - withCache(CacheKeys.fromUrl, 3600, 'points'), - async (c) => { - const pointId = c.req.param('id'); +app.get('/points/:id', withCache(CacheKeys.fromUrl, 3600, 'points'), async (c) => { + const pointId = c.req.param('id'); - // Validate point ID format (alphanumeric, dash, underscore) - if (!pointId.match(POINT_ID_REGEX)) { - return c.text('Invalid point ID format', 400); - } + // Validate point ID format (alphanumeric, dash, underscore) + if (!pointId.match(POINT_ID_REGEX)) { + return c.text('Invalid point ID format', 400); + } - const points = ServicePool.getPoints(c.env); - const point = await points.getPoint(pointId); + const points = ServicePool.getPoints(c.env); + const point = await points.getPoint(pointId); - if (!point) { - return c.text('Point not found', 404); - } + if (!point) { + return c.text('Point not found', 404); + } - return c.json(point); - }); + return c.json(point); +}); // Get multiple points by IDs (batch endpoint) /** @@ -1617,63 +1645,73 @@ app.get('/points/:id', * 400: * description: Validation error */ -app.get('/points', - withCache(CacheKeys.fromUrl, 3600, 'points'), - async (c) => { - const ids = c.req.query('ids'); +app.get('/points', withCache(CacheKeys.fromUrl, 3600, 'points'), async (c) => { + const ids = c.req.query('ids'); - if (!ids) { - return c.json({ + if (!ids) { + return c.json( + { error: 'Missing ids query parameter', - message: 'Provide comma-separated point IDs: /points?ids=id1,id2,id3' - }, 400); - } + message: 'Provide comma-separated point IDs: /points?ids=id1,id2,id3', + }, + 400, + ); + } - // Parse and validate point IDs - const pointIds = ids.split(',') - .map(id => id.trim()) - .filter(id => id.length > 0); + // Parse and validate point IDs + const pointIds = ids + .split(',') + .map((id) => id.trim()) + .filter((id) => id.length > 0); - if (pointIds.length === 0) { - return c.json({ - error: 'No valid point IDs provided' - }, 400); - } + if (pointIds.length === 0) { + return c.json( + { + error: 'No valid point IDs provided', + }, + 400, + ); + } - if (pointIds.length > 100) { - return c.json({ + if (pointIds.length > 100) { + return c.json( + { error: 'Too many point IDs requested', - message: 'Maximum 100 points can be requested at once' - }, 400); - } - + message: 'Maximum 100 points can be requested at once', + }, + 400, + ); + } - const invalidIds = pointIds.filter(id => !id.match(POINT_ID_REGEX)); - if (invalidIds.length > 0) { - return c.json({ + const invalidIds = pointIds.filter((id) => !id.match(POINT_ID_REGEX)); + if (invalidIds.length > 0) { + return c.json( + { error: 'Invalid point ID format', - invalidIds - }, 400); - } + invalidIds, + }, + 400, + ); + } - const points = ServicePool.getPoints(c.env); + const points = ServicePool.getPoints(c.env); - // Fetch all points in parallel - const pointPromises = pointIds.map(id => points.getPoint(id)); - const pointResults = await Promise.all(pointPromises); + // Fetch all points in parallel + const pointPromises = pointIds.map((id) => points.getPoint(id)); + const pointResults = await Promise.all(pointPromises); - // Filter out null results and create response - const foundPoints = pointResults.filter(point => point !== null); - const foundIds = foundPoints.map(point => point!.id); - const notFoundIds = pointIds.filter(id => !foundIds.includes(id)); + // Filter out null results and create response + const foundPoints = pointResults.filter((point) => point !== null); + const foundIds = foundPoints.map((point) => point!.id); + const notFoundIds = pointIds.filter((id) => !foundIds.includes(id)); - return c.json({ - points: foundPoints, - requested: pointIds.length, - found: foundPoints.length, - notFound: notFoundIds.length > 0 ? notFoundIds : undefined - }); + return c.json({ + points: foundPoints, + requested: pointIds.length, + found: foundPoints.length, + notFound: notFoundIds.length > 0 ? notFoundIds : undefined, }); +}); // MSFS Light Supports and BARS XML generation endpoint /** @@ -1710,15 +1748,21 @@ app.post('/supports/generate', async (c) => { const icao = formData.get('icao')?.toString(); if (!xmlFile || !(xmlFile instanceof File)) { - return c.json({ - error: 'XML file is required', - }, 400); + return c.json( + { + error: 'XML file is required', + }, + 400, + ); } if (!icao) { - return c.json({ - error: 'ICAO code is required', - }, 400); + return c.json( + { + error: 'ICAO code is required', + }, + 400, + ); } const xmlContent = await xmlFile.text(); @@ -1738,9 +1782,12 @@ app.post('/supports/generate', async (c) => { }); } catch (error) { console.error('Error generating XMLs:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Unknown error generating XMLs', - }, 500); + return c.json( + { + error: error instanceof Error ? error.message : 'Unknown error generating XMLs', + }, + 500, + ); } }); @@ -1756,7 +1803,8 @@ app.post('/supports/generate', async (c) => { * 200: * description: Current NOTAM returned */ -app.get('/notam', +app.get( + '/notam', withCache(() => 'global-notam', 900, 'notam'), async (c) => { const notamService = ServicePool.getNotam(c.env); @@ -1765,7 +1813,7 @@ app.get('/notam', notam: notamData?.content || null, type: notamData?.type || 'warning', }); - } + }, ); /** @@ -1820,7 +1868,7 @@ app.put('/notam', async (c) => { } // Update the NOTAM - const { content, type } = await c.req.json() as { content: string; type?: string }; + const { content, type } = (await c.req.json()) as { content: string; type?: string }; const notamService = ServicePool.getNotam(c.env); const updated = await notamService.updateGlobalNotam(content, type, user.vatsim_id); @@ -1831,7 +1879,6 @@ app.put('/notam', async (c) => { return c.json({ success: true }); }); - // User management endpoints const staffUsersApp = new Hono<{ Bindings: Env; @@ -1924,9 +1971,12 @@ staffUsersApp.get('/search', async (c) => { try { const query = c.req.query('q') || ''; if (query.length < 3) { - return c.json({ - error: 'Search query must be at least 3 characters', - }, 400); + return c.json( + { + error: 'Search query must be at least 3 characters', + }, + 400, + ); } const user = c.get('user'); @@ -1968,12 +2018,15 @@ staffUsersApp.get('/search', async (c) => { */ staffUsersApp.post('/refresh-api-token', async (c) => { try { - const { vatsimId } = await c.req.json() as { vatsimId: string }; + const { vatsimId } = (await c.req.json()) as { vatsimId: string }; if (!vatsimId) { - return c.json({ - error: 'VATSIM ID is required', - }, 400); + return c.json( + { + error: 'VATSIM ID is required', + }, + 400, + ); } const user = c.get('user'); @@ -2063,30 +2116,28 @@ const contributionsApp = new Hono<{ Bindings: Env }>(); * 200: * description: Contributions listed */ -contributionsApp.get('/', - withCache(CacheKeys.fromUrl, 7200, 'contributions'), - async (c) => { - const contributions = ServicePool.getContributions(c.env); - - // Parse query parameters for filtering - const status = (c.req.query('status') as 'pending' | 'approved' | 'rejected' | 'outdated' | 'all') || 'all'; - const airportIcao = c.req.query('airport') || undefined; - const userId = c.req.query('user') || undefined; - const page = 1; // Default to page 1 for user contributions - const limit = Number.MAX_SAFE_INTEGER; +contributionsApp.get('/', async (c) => { + const contributions = ServicePool.getContributions(c.env); - // Get contributions with filters - const result = await contributions.listContributions({ - status, - airportIcao, - userId, - page, - limit, - }); + // Parse query parameters for filtering + const status = (c.req.query('status') as 'pending' | 'approved' | 'rejected' | 'outdated' | 'all') || 'all'; + const airportIcao = c.req.query('airport') || undefined; + const userId = c.req.query('user') || undefined; + const page = 1; // Default to page 1 for user contributions + const limit = Number.MAX_SAFE_INTEGER; - return c.json(result); + // Get contributions with filters + const result = await contributions.listContributions({ + status, + airportIcao, + userId, + page, + limit, }); + return c.json(result); +}); + // (Removed) contribution statistics endpoint // GET /contributions/leaderboard - Get top contributors @@ -2101,13 +2152,15 @@ contributionsApp.get('/', * 200: * description: Leaderboard returned */ -contributionsApp.get('/leaderboard', +contributionsApp.get( + '/leaderboard', withCache(() => 'contribution-leaderboard', 1800, 'contributions'), async (c) => { const contributions = ServicePool.getContributions(c.env); const leaderboard = await contributions.getContributionLeaderboard(); return c.json(leaderboard); - }); + }, +); // GET /contributions/top-packages - Get a list of most used packages /** @@ -2121,13 +2174,15 @@ contributionsApp.get('/leaderboard', * 200: * description: Package stats returned */ -contributionsApp.get('/top-packages', +contributionsApp.get( + '/top-packages', withCache(() => 'contribution-top-packages', 1800, 'contributions'), async (c) => { const contributions = ServicePool.getContributions(c.env); const topPackages = await contributions.getTopPackages(); return c.json(topPackages); - }); + }, +); // POST /contributions - Create a new contribution /** @@ -2173,7 +2228,7 @@ contributionsApp.post('/', async (c) => { try { const contributions = ServicePool.getContributions(c.env); - const payload = await c.req.json() as ContributionSubmissionPayload; + const payload = (await c.req.json()) as ContributionSubmissionPayload; const result = await contributions.createContribution({ userId: user.vatsim_id, airportIcao: payload.airportIcao, @@ -2321,7 +2376,7 @@ contributionsApp.post('/:id/decision', async (c) => { try { const contributionId = c.req.param('id'); const contributions = ServicePool.getContributions(c.env); - const payload = await c.req.json() as ContributionDecisionPayload; + const payload = (await c.req.json()) as ContributionDecisionPayload; const result = await contributions.processDecision(contributionId, user.vatsim_id, { approved: payload.approved, rejectionReason: payload.rejectionReason, @@ -2336,7 +2391,6 @@ contributionsApp.post('/:id/decision', async (c) => { } }); - // DELETE /contributions/:id - Delete a contribution (admin only) /** * @openapi @@ -2388,10 +2442,52 @@ contributionsApp.delete('/:id', async (c) => { app.route('/contributions', contributionsApp); - // CDN Endpoints const cdnApp = new Hono<{ Bindings: Env }>(); +// Latest approved BARS map for an airport +/** + * @openapi + * /maps/{icao}/latest: + * get: + * summary: Get latest approved BARS map XML (raw content) for an airport + * tags: + * - Generation + * parameters: + * - in: path + * name: icao + * required: true + * schema: { type: string } + * responses: + * 200: + * description: BARS XML document returned inline (application/xml) + * 404: + * description: Not found + */ +app.get('/maps/:icao/latest', withCache(CacheKeys.fromUrl, 900, 'airports'), async (c) => { + const icao = c.req.param('icao').toUpperCase(); + const contributions = ServicePool.getContributions(c.env); + const storage = ServicePool.getStorage(c.env); + + const latest = await contributions.getLatestApprovedContributionForAirport(icao); + if (!latest) { + return c.text('No approved map found', 404); + } + + const safePackageName = latest.packageName.replace(/[^a-zA-Z0-9.-]/g, '-'); + const fileKey = `Maps/${icao}_${safePackageName}_bars.xml`; + + // Fetch stored XML; if missing, return 404 + const stored = await storage.getFile(fileKey); + if (!stored) { + return c.text('Map file not found', 404); + } + if (!stored.headers.get('content-type')) { + stored.headers.set('content-type', 'application/xml; charset=utf-8'); + } + return stored; +}); + // Special case for direct file downloads /** * @openapi @@ -2428,7 +2524,6 @@ cdnApp.get('/files/*', async (c) => { return c.text('File not found', 404); } - // Return the file directly with proper headers for caching return fileResponse; }); @@ -2494,9 +2589,12 @@ cdnApp.post('/upload', async (c) => { const customKey = formData.get('key')?.toString(); if (!file || !(file instanceof File)) { - return c.json({ - error: 'File is required', - }, 400); + return c.json( + { + error: 'File is required', + }, + 400, + ); } // Create file path - use custom key if provided, otherwise generate one @@ -2518,19 +2616,25 @@ cdnApp.post('/upload', async (c) => { // Stats tracking removed // Return success with download URL - return c.json({ - success: true, - file: { - key: result.key, - etag: result.etag, - url: new URL(`/cdn/files/${result.key}`, c.req.url).toString(), + return c.json( + { + success: true, + file: { + key: result.key, + etag: result.etag, + url: new URL(`/cdn/files/${result.key}`, c.req.url).toString(), + }, }, - }, 201); + 201, + ); } catch (error) { console.error('File upload error:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to upload file', - }, 500); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to upload file', + }, + 500, + ); } }); @@ -2598,9 +2702,12 @@ cdnApp.get('/files', async (c) => { return c.json({ files }); } catch (error) { console.error('File listing error:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to list files', - }, 500); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to list files', + }, + 500, + ); } }); @@ -2652,9 +2759,12 @@ cdnApp.delete('/files/*', async (c) => { const fileKey = c.req.param('*'); if (!fileKey) { - return c.json({ - error: 'File not found', - }, 404); + return c.json( + { + error: 'File not found', + }, + 404, + ); } // Delete the file @@ -2662,9 +2772,12 @@ cdnApp.delete('/files/*', async (c) => { const deleted = await storage.deleteFile(fileKey); if (!deleted) { - return c.json({ - error: 'File not found', - }, 404); + return c.json( + { + error: 'File not found', + }, + 404, + ); } // Stats tracking removed @@ -2672,9 +2785,12 @@ cdnApp.delete('/files/*', async (c) => { return c.json({ success: true }); } catch (error) { console.error('File deletion error:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to delete file', - }, 500); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to delete file', + }, + 500, + ); } }); @@ -2704,9 +2820,12 @@ app.get('/euroscope/files/:icao', async (c) => { // Validate ICAO format if (!icao.match(/^[A-Z0-9]{4}$/)) { - return c.json({ - error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', - }, 400); + return c.json( + { + error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', + }, + 400, + ); } try { @@ -2729,9 +2848,12 @@ app.get('/euroscope/files/:icao', async (c) => { }); } catch (error) { console.error('EuroScope public file listing error:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to list files', - }, 500); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to list files', + }, + 500, + ); } }); @@ -2804,30 +2926,42 @@ euroscopeApp.post('/upload', async (c) => { const icao = formData.get('icao')?.toString()?.toUpperCase(); if (!file || !(file instanceof File)) { - return c.json({ - error: 'File is required', - }, 400); + return c.json( + { + error: 'File is required', + }, + 400, + ); } if (!icao) { - return c.json({ - error: 'ICAO code is required', - }, 400); + return c.json( + { + error: 'ICAO code is required', + }, + 400, + ); } // Validate ICAO format (exactly 4 uppercase letters/numbers) if (!icao.match(/^[A-Z0-9]{4}$/)) { - return c.json({ - error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', - }, 400); + return c.json( + { + error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', + }, + 400, + ); } // Check file size limit (10MB) const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB in bytes if (file.size > MAX_FILE_SIZE) { - return c.json({ - error: 'File size exceeds 10MB limit', - }, 400); + return c.json( + { + error: 'File size exceeds 10MB limit', + }, + 400, + ); } // Check if user has access to upload files for this ICAO @@ -2835,9 +2969,12 @@ euroscopeApp.post('/upload', async (c) => { const hasAccess = await divisions.userHasAirportAccess(vatsimUser.id.toString(), icao); if (!hasAccess) { - return c.json({ - error: 'You do not have permission to upload files for this airport. Please ensure your division has approved access to this ICAO.', - }, 403); + return c.json( + { + error: 'You do not have permission to upload files for this airport. Please ensure your division has approved access to this ICAO.', + }, + 403, + ); } // Create file path: EuroScope/ICAO/filename @@ -2849,11 +2986,14 @@ euroscopeApp.post('/upload', async (c) => { const existingFiles = await storage.listFiles(`EuroScope/${icao}/`, 10); // Count files that are not the one being replaced - const otherFiles = existingFiles.objects.filter(obj => obj.key !== fileKey); + const otherFiles = existingFiles.objects.filter((obj) => obj.key !== fileKey); if (otherFiles.length >= 2) { - return c.json({ - error: 'Maximum of 2 files per ICAO code allowed. Please delete an existing file before uploading a new one.', - }, 400); + return c.json( + { + error: 'Maximum of 2 files per ICAO code allowed. Please delete an existing file before uploading a new one.', + }, + 400, + ); } // Extract file data @@ -2867,23 +3007,28 @@ euroscopeApp.post('/upload', async (c) => { size: file.size.toString(), }); - // Return success with download URL - return c.json({ - success: true, - file: { - key: result.key, - icao: icao, - fileName: fileName, - size: file.size, - url: new URL(`https://dev-cdn.stopbars.com/${result.key}`, c.req.url).toString(), + return c.json( + { + success: true, + file: { + key: result.key, + icao: icao, + fileName: fileName, + size: file.size, + url: new URL(`https://dev-cdn.stopbars.com/${result.key}`, c.req.url).toString(), + }, }, - }, 201); + 201, + ); } catch (error) { console.error('EuroScope file upload error:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to upload file', - }, 500); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to upload file', + }, + 500, + ); } }); @@ -2919,9 +3064,12 @@ euroscopeApp.delete('/files/:icao/:filename', async (c) => { // Validate ICAO format if (!icao.match(/^[A-Z0-9]{4}$/)) { - return c.json({ - error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', - }, 400); + return c.json( + { + error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', + }, + 400, + ); } try { @@ -2930,9 +3078,12 @@ euroscopeApp.delete('/files/:icao/:filename', async (c) => { const hasAccess = await divisions.userHasAirportAccess(vatsimUser.id.toString(), icao); if (!hasAccess) { - return c.json({ - error: 'You do not have permission to delete files for this airport. Please ensure your division has approved access to this ICAO.', - }, 403); + return c.json( + { + error: 'You do not have permission to delete files for this airport. Please ensure your division has approved access to this ICAO.', + }, + 403, + ); } // Construct the file key @@ -2943,9 +3094,12 @@ euroscopeApp.delete('/files/:icao/:filename', async (c) => { const deleted = await storage.deleteFile(fileKey); if (!deleted) { - return c.json({ - error: 'File not found', - }, 404); + return c.json( + { + error: 'File not found', + }, + 404, + ); } return c.json({ @@ -2954,9 +3108,12 @@ euroscopeApp.delete('/files/:icao/:filename', async (c) => { }); } catch (error) { console.error('EuroScope file deletion error:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to delete file', - }, 500); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to delete file', + }, + 500, + ); } }); @@ -2986,9 +3143,12 @@ euroscopeApp.get('/:icao/editable', async (c) => { // Validate ICAO format if (!icao.match(/^[A-Z0-9]{4}$/)) { - return c.json({ - error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', - }, 400); + return c.json( + { + error: 'Invalid ICAO format. Must be exactly 4 uppercase letters/numbers.', + }, + 400, + ); } try { @@ -3004,9 +3164,12 @@ euroscopeApp.get('/:icao/editable', async (c) => { }); } catch (error) { console.error('EuroScope access check error:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to check airport access', - }, 500); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to check airport access', + }, + 500, + ); } }); app.route('/euroscope', euroscopeApp); @@ -3062,7 +3225,7 @@ app.post('/purge-cache', async (c) => { } try { - const { key, namespace } = await c.req.json() as { key: string; namespace?: string }; + const { key, namespace } = (await c.req.json()) as { key: string; namespace?: string }; if (!key) { return c.json({ error: 'Cache key is required' }, 400); @@ -3077,12 +3240,14 @@ app.post('/purge-cache', async (c) => { success: true, message: `Cache key "${key}" purged successfully`, }); - } catch (error) { console.error('Cache purge error:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to purge cache', - }, 500); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to purge cache', + }, + 500, + ); } }); @@ -3098,7 +3263,8 @@ app.post('/purge-cache', async (c) => { * 200: * description: Contributors returned */ -app.get('/contributors', +app.get( + '/contributors', withCache(() => 'github-contributors', 3600, 'github'), // Cache for 1 hour async (c) => { try { @@ -3107,12 +3273,15 @@ app.get('/contributors', return c.json(contributorsData); } catch (error) { console.error('Contributors endpoint error:', error); - return c.json({ - error: 'Failed to fetch contributors data', - message: error instanceof Error ? error.message : 'Unknown error' - }, 500); + return c.json( + { + error: 'Failed to fetch contributors data', + message: error instanceof Error ? error.message : 'Unknown error', + }, + 500, + ); } - } + }, ); // Health endpoint @@ -3134,84 +3303,84 @@ app.get('/contributors', * 503: * description: One or more services degraded */ -app.get('/health', - withCache(CacheKeys.fromUrl, 60, 'health'), - async (c) => { - const requestedService = c.req.query('service'); - const validServices = ['database', 'storage', 'vatsim', 'auth']; +app.get('/health', withCache(CacheKeys.fromUrl, 60, 'health'), async (c) => { + const requestedService = c.req.query('service'); + const validServices = ['database', 'storage', 'vatsim', 'auth']; - if (requestedService && !validServices.includes(requestedService)) { - return c.json({ + if (requestedService && !validServices.includes(requestedService)) { + return c.json( + { error: 'Invalid service', validServices: validServices, - }, 400); - } + }, + 400, + ); + } - const healthChecks: Record = {}; - const servicesToCheck = requestedService ? [requestedService] : validServices; + const healthChecks: Record = {}; + const servicesToCheck = requestedService ? [requestedService] : validServices; - for (const service of servicesToCheck) { - healthChecks[service] = 'ok'; - } + for (const service of servicesToCheck) { + healthChecks[service] = 'ok'; + } - try { - if (servicesToCheck.includes('database')) { - try { - await c.env.DB.prepare('SELECT 1').first(); - } catch (error) { - healthChecks.database = 'outage'; - } + try { + if (servicesToCheck.includes('database')) { + try { + await c.env.DB.prepare('SELECT 1').first(); + } catch (error) { + healthChecks.database = 'outage'; } + } - if (servicesToCheck.includes('storage')) { - try { - const storage = ServicePool.getStorage(c.env); - await storage.listFiles(undefined, 1); - } catch (error) { - healthChecks.storage = 'outage'; - } + if (servicesToCheck.includes('storage')) { + try { + const storage = ServicePool.getStorage(c.env); + await storage.listFiles(undefined, 1); + } catch (error) { + healthChecks.storage = 'outage'; } + } - if (servicesToCheck.includes('vatsim')) { - try { - const response = await fetch('https://auth.vatsim.net/api/user', { - method: 'GET', - headers: { - 'Accept': 'application/json', - 'User-Agent': 'BARS-Health-Check/1.0' - }, - signal: AbortSignal.timeout(5000) - }); - - if (!response.ok && response.status !== 401) { - throw new Error(`VATSIM API returned ${response.status}`); - } - } catch (error) { - console.error('VATSIM health check failed:', error); - healthChecks.vatsim = 'outage'; + if (servicesToCheck.includes('vatsim')) { + try { + const response = await fetch('https://auth.vatsim.net/api/user', { + method: 'GET', + headers: { + Accept: 'application/json', + 'User-Agent': 'BARS-Health-Check/1.0', + }, + signal: AbortSignal.timeout(5000), + }); + + if (!response.ok && response.status !== 401) { + throw new Error(`VATSIM API returned ${response.status}`); } + } catch (error) { + console.error('VATSIM health check failed:', error); + healthChecks.vatsim = 'outage'; } + } - if (servicesToCheck.includes('auth')) { - try { - const auth = ServicePool.getAuth(c.env); - await auth.getUserByVatsimId('1658308'); - } catch (error) { - healthChecks.auth = 'outage'; - } + if (servicesToCheck.includes('auth')) { + try { + const auth = ServicePool.getAuth(c.env); + await auth.getUserByVatsimId('1658308'); + } catch (error) { + healthChecks.auth = 'outage'; } - - // Stats service removed - - } catch (error) { - console.error('Health check error:', error); } - const hasOutages = Object.values(healthChecks).some(status => status === 'outage'); - const statusCode = hasOutages ? 503 : 200; + // Stats service removed + } catch (error) { + console.error('Health check error:', error); + } + + const hasOutages = Object.values(healthChecks).some((status) => status === 'outage'); + const statusCode = hasOutages ? 503 : 200; - return c.json(healthChecks, statusCode); - }); + return c.json(healthChecks, statusCode); +}); // Serve OpenAPI spec /** diff --git a/src/network/connection.ts b/src/network/connection.ts index 9ef46cd..342fc93 100644 --- a/src/network/connection.ts +++ b/src/network/connection.ts @@ -273,9 +273,7 @@ export class Connection { } // Ensure existing state is an object for merging - const baseState = (typeof existingObject.state === 'object' && existingObject.state !== null) - ? existingObject.state - : {}; + const baseState = typeof existingObject.state === 'object' && existingObject.state !== null ? existingObject.state : {}; // Apply patch using recursive merge with size limit newState = recursivelyMergeObjects(baseState, packet.data.patch); @@ -392,9 +390,11 @@ export class Connection { const isPilot = this.vatsim.isPilot(status); const isObserver = this.vatsim.isObserver(status); - if ((socketInfo.type === 'controller' && !isController) || + if ( + (socketInfo.type === 'controller' && !isController) || (socketInfo.type === 'pilot' && !isPilot) || - (socketInfo.type === 'observer' && !isObserver)) { + (socketInfo.type === 'observer' && !isObserver) + ) { console.log(`User ${socketInfo.controllerId} role changed on VATSIM, closing connection`); socket.send( JSON.stringify({ @@ -514,11 +514,7 @@ export class Connection { return new Response('User not connected to VATSIM', { status: 403 }); } // Auto-determine client type based on VATSIM status - const clientType = this.vatsim.isController(status) - ? 'controller' - : this.vatsim.isObserver(status) - ? 'observer' - : 'pilot'; + const clientType = this.vatsim.isController(status) ? 'controller' : this.vatsim.isObserver(status) ? 'observer' : 'pilot'; const pair = new WebSocketPair(); const [client, server] = Object.values(pair); @@ -665,7 +661,9 @@ export class Connection { await this.broadcast(broadcastPacket, server); await this.trackMessage(clientType); } catch (updateError) { - throw new Error(`State update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`); + throw new Error( + `State update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`, + ); } break; @@ -688,7 +686,9 @@ export class Connection { try { this.handleSharedStateUpdate(packet, user.vatsim_id, socketInfo.airport); } catch (updateError) { - throw new Error(`Shared state update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`); + throw new Error( + `Shared state update failed: ${updateError instanceof Error ? updateError.message : String(updateError)}`, + ); } break; @@ -834,7 +834,7 @@ export class Connection { controllers: [] as string[], pilots: [] as string[], controllerSet: new Set(), - pilotSet: new Set() + pilotSet: new Set(), }, ); const state = this.airportStates.get(airport); @@ -959,7 +959,7 @@ export class Connection { airport: airport, data: { sharedStatePatch: patch, - controllerId: controllerId + controllerId: controllerId, }, timestamp: Date.now(), }; @@ -974,7 +974,9 @@ export class Connection { try { socket.send(JSON.stringify(packet)); } catch (error) { - console.error(`Failed to send packet over WebSocket: ${error instanceof Error ? error.message : String(error)}`); + console.error( + `Failed to send packet over WebSocket: ${error instanceof Error ? error.message : String(error)}`, + ); } finally { resolve(); } @@ -1011,7 +1013,7 @@ export class Connection { 'INITIAL_STATE', 'CONTROLLER_CONNECT', 'CONTROLLER_DISCONNECT', - 'ERROR' + 'ERROR', ]; if (!validTypes.includes(packet.type)) { diff --git a/src/services/airport.ts b/src/services/airport.ts index 44a6fb0..2edaf9d 100644 --- a/src/services/airport.ts +++ b/src/services/airport.ts @@ -34,18 +34,12 @@ export class AirportService { const uppercaseIcao = icao.toUpperCase(); // First try to get from database using read-optimized query - const airportResult = await this.dbSession.executeRead( - 'SELECT * FROM airports WHERE icao = ?', - [uppercaseIcao] - ); + const airportResult = await this.dbSession.executeRead('SELECT * FROM airports WHERE icao = ?', [uppercaseIcao]); const airportFromDb = airportResult.results[0]; if (airportFromDb) { // Get runways for this airport - const runwaysResult = await this.dbSession.executeRead( - 'SELECT * FROM runways WHERE airport_icao = ?', - [uppercaseIcao] - ); + const runwaysResult = await this.dbSession.executeRead('SELECT * FROM runways WHERE airport_icao = ?', [uppercaseIcao]); return { ...airportFromDb, runways: runwaysResult.results }; } @@ -66,10 +60,13 @@ export class AirportService { }; // Save airport to database using write-optimized operation - await this.dbSession.executeWrite( - 'INSERT INTO airports (icao, latitude, longitude, name, continent) VALUES (?, ?, ?, ?, ?)', - [airport.icao, airport.latitude, airport.longitude, airport.name, airport.continent] - ); + await this.dbSession.executeWrite('INSERT INTO airports (icao, latitude, longitude, name, continent) VALUES (?, ?, ?, ?, ?)', [ + airport.icao, + airport.latitude, + airport.longitude, + airport.name, + airport.continent, + ]); // Save runway data if available if (airportData.runways && airportData.runways.length > 0) { @@ -91,24 +88,30 @@ export class AirportService { runway.he_ident, runway.he_latitude_deg, runway.he_longitude_deg, - ] + ], })); await this.dbSession.executeBatch(runwayStatements); // Fetch the saved runways to return with the airport - const runwaysResult = await this.dbSession.executeRead( - 'SELECT * FROM runways WHERE airport_icao = ?', - [uppercaseIcao] - ); + const runwaysResult = await this.dbSession.executeRead('SELECT * FROM runways WHERE airport_icao = ?', [ + uppercaseIcao, + ]); return { ...airport, runways: runwaysResult.results }; } - try { this.posthog?.track('Airport Fetched From External API', { icao: uppercaseIcao, hasRunways: !!airportData.runways?.length }); } catch { } + try { + this.posthog?.track('Airport Fetched From External API', { + icao: uppercaseIcao, + hasRunways: !!airportData.runways?.length, + }); + } catch {} return airport; } catch (error) { - try { this.posthog?.track('Airport External Fetch Failed', { icao: uppercaseIcao }); } catch { } + try { + this.posthog?.track('Airport External Fetch Failed', { icao: uppercaseIcao }); + } catch {} return null; } } @@ -134,10 +137,9 @@ export class AirportService { } async getAirportsByContinent(continent: string) { - const result = await this.dbSession.executeRead( - 'SELECT * FROM airports WHERE continent = ? ORDER BY icao', - [continent.toUpperCase()] - ); + const result = await this.dbSession.executeRead('SELECT * FROM airports WHERE continent = ? ORDER BY icao', [ + continent.toUpperCase(), + ]); return { results: result.results }; } @@ -160,7 +162,7 @@ export class AirportService { const maxLon = lon + LON_BOX; // Pre-compute cos^2(lat) to weight longitudinal delta for planar approx distance ordering - const cosLat = Math.cos(lat * Math.PI / 180); + const cosLat = Math.cos((lat * Math.PI) / 180); const cosLatSq = cosLat * cosLat; const approx = await this.dbSession.executeRead( `SELECT icao, latitude, longitude, name, continent, @@ -169,7 +171,7 @@ export class AirportService { WHERE latitude BETWEEN ? AND ? AND longitude BETWEEN ? AND ? ORDER BY distance_score LIMIT 1`, - [lat, lat, lon, lon, cosLatSq, minLat, maxLat, minLon, maxLon] + [lat, lat, lon, lon, cosLatSq, minLat, maxLat, minLon, maxLon], ); const row = approx.results?.[0]; @@ -179,7 +181,9 @@ export class AirportService { const distance_m = calculateDistance({ lat, lon }, { lat: row.latitude, lon: row.longitude }); const distance_nm = distance_m / 1852; - try { this.posthog?.track('Nearest Airport Lookup', { icao: row.icao }); } catch { } + try { + this.posthog?.track('Nearest Airport Lookup', { icao: row.icao }); + } catch {} return { icao: row.icao, diff --git a/src/services/auth.ts b/src/services/auth.ts index 95781f9..fd61f1b 100644 --- a/src/services/auth.ts +++ b/src/services/auth.ts @@ -27,7 +27,9 @@ export class AuthService { isNewUser: created, userId: user.id, }); - } catch { /* ignore analytics errors */ } + } catch { + /* ignore analytics errors */ + } return { user, vatsimToken: auth.access_token }; } @@ -35,10 +37,7 @@ export class AuthService { // Use primary mode for authentication checks to ensure latest data this.dbSession.startSession({ mode: 'first-primary' }); - const existingUserResult = await this.dbSession.executeRead( - 'SELECT * FROM users WHERE vatsim_id = ?', - [vatsimUser.id] - ); + const existingUserResult = await this.dbSession.executeRead('SELECT * FROM users WHERE vatsim_id = ?', [vatsimUser.id]); const existingUser = existingUserResult.results[0]; if (existingUser) { @@ -61,10 +60,9 @@ export class AuthService { private async createNewUser(vatsimUser: VatsimUser) { // Check for existing VATSIM user using session - const existingVatsimUserResult = await this.dbSession.executeRead( - 'SELECT id FROM users WHERE vatsim_id = ?', - [vatsimUser.id] - ); + const existingVatsimUserResult = await this.dbSession.executeRead('SELECT id FROM users WHERE vatsim_id = ?', [ + vatsimUser.id, + ]); if (existingVatsimUserResult.results[0]) { throw new Error('User with this VATSIM ID already exists'); @@ -73,10 +71,7 @@ export class AuthService { let apiKey = this.generateApiKey(); while (true) { - const existingKeyResult = await this.dbSession.executeRead( - 'SELECT id FROM users WHERE api_key = ?', - [apiKey] - ); + const existingKeyResult = await this.dbSession.executeRead('SELECT id FROM users WHERE api_key = ?', [apiKey]); if (!existingKeyResult.results[0]) break; apiKey = this.generateApiKey(); @@ -84,13 +79,32 @@ export class AuthService { const fullName = [vatsimUser.first_name, vatsimUser.last_name].filter(Boolean).join(' ') || null; const displayMode = 0; - const displayName = this.computeDisplayName({ - id: 0, vatsim_id: vatsimUser.id, api_key: apiKey, email: vatsimUser.email, - full_name: fullName, display_mode: displayMode, created_at: '', last_login: '', vatsimToken: '' - }, vatsimUser); + const displayName = this.computeDisplayName( + { + id: 0, + vatsim_id: vatsimUser.id, + api_key: apiKey, + email: vatsimUser.email, + full_name: fullName, + display_mode: displayMode, + created_at: '', + last_login: '', + vatsimToken: '', + }, + vatsimUser, + ); const result = await this.dbSession.executeWrite( 'INSERT INTO users (vatsim_id, api_key, email, full_name, display_mode, display_name, created_at, last_login) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING *', - [vatsimUser.id, apiKey, vatsimUser.email, fullName, displayMode, displayName, new Date().toISOString(), new Date().toISOString()] + [ + vatsimUser.id, + apiKey, + vatsimUser.email, + fullName, + displayMode, + displayName, + new Date().toISOString(), + new Date().toISOString(), + ], ); if (!result.results[0]) throw new Error('Failed to create user'); @@ -104,37 +118,33 @@ export class AuthService { await this.dbSession.executeBatch([ { query: 'DELETE FROM division_members WHERE vatsim_id = ?', params: [vatsimId] }, { query: 'DELETE FROM staff WHERE user_id IN (SELECT id FROM users WHERE vatsim_id = ?)', params: [vatsimId] }, - { query: 'DELETE FROM users WHERE vatsim_id = ?', params: [vatsimId] } + { query: 'DELETE FROM users WHERE vatsim_id = ?', params: [vatsimId] }, ]); const userExists = await this.getUserByVatsimId(vatsimId); const deleted = !userExists; if (deleted) { - try { this.posthog?.track('User Deleted', { vatsimId }); } catch { } + try { + this.posthog?.track('User Deleted', { vatsimId }); + } catch {} } return deleted; } async getUserByApiKey(apiKey: string): Promise { // Use unconstrained read for API key lookups (performance optimization) - const result = await this.dbSession.executeRead( - 'SELECT * FROM users WHERE api_key = ?', - [apiKey] - ); + const result = await this.dbSession.executeRead('SELECT * FROM users WHERE api_key = ?', [apiKey]); return result.results[0] || null; } async getUserByVatsimId(vatsimId: string): Promise { // Use unconstrained read for VATSIM ID lookups - const result = await this.dbSession.executeRead( - 'SELECT * FROM users WHERE vatsim_id = ?', - [vatsimId] - ); + const result = await this.dbSession.executeRead('SELECT * FROM users WHERE vatsim_id = ?', [vatsimId]); return result.results[0] || null; } computeDisplayName(user: UserRecord, vatsimUser?: VatsimUser): string { - const mode = (user.display_mode ?? 0); + const mode = user.display_mode ?? 0; const fullName = user.full_name || [vatsimUser?.first_name, vatsimUser?.last_name].filter(Boolean).join(' ').trim(); if (mode === 2) return user.vatsim_id; if (!fullName) return user.vatsim_id; @@ -156,7 +166,7 @@ export class AuthService { const current = await this.dbSession.executeRead( 'SELECT id, vatsim_id, email, full_name, display_mode, display_name FROM users WHERE id = ?', - [userId] + [userId], ); const user = current.results[0]; if (!user) return; @@ -173,10 +183,7 @@ export class AuthService { const displayName = this.computeDisplayName({ ...user, display_mode: mode } as UserRecord, vatsimUser); - await this.dbSession.executeWrite( - 'UPDATE users SET display_mode = ?, display_name = ? WHERE id = ?', - [mode, displayName, userId] - ); + await this.dbSession.executeWrite('UPDATE users SET display_mode = ?, display_name = ? WHERE id = ?', [mode, displayName, userId]); } async updateFullName(userId: number, fullName: string) { @@ -185,17 +192,19 @@ export class AuthService { const current = await this.dbSession.executeRead('SELECT * FROM users WHERE id = ?', [userId]); const user = current.results[0]; if (user) { - const vatsimUser: VatsimUser = { id: user.vatsim_id, email: user.email, first_name: fullName.split(' ')[0], last_name: fullName.split(' ').slice(1).join(' ') }; + const vatsimUser: VatsimUser = { + id: user.vatsim_id, + email: user.email, + first_name: fullName.split(' ')[0], + last_name: fullName.split(' ').slice(1).join(' '), + }; const displayName = this.computeDisplayName(user, vatsimUser); await this.dbSession.executeWrite('UPDATE users SET display_name = ? WHERE id = ?', [displayName, userId]); } } private async updateUserLastLogin(userId: number) { - await this.dbSession.executeWrite( - 'UPDATE users SET last_login = ? WHERE id = ?', - [new Date().toISOString(), userId] - ); + await this.dbSession.executeWrite('UPDATE users SET last_login = ? WHERE id = ?', [new Date().toISOString(), userId]); } async regenerateApiKey(userId: number): Promise { @@ -206,27 +215,26 @@ export class AuthService { // Make sure the new API key is unique while (true) { - const existingKeyResult = await this.dbSession.executeRead( - 'SELECT id FROM users WHERE api_key = ?', - [newApiKey] - ); + const existingKeyResult = await this.dbSession.executeRead('SELECT id FROM users WHERE api_key = ?', [newApiKey]); if (!existingKeyResult.results[0]) break; newApiKey = this.generateApiKey(); } // Update the user's API key in the database - const result = await this.dbSession.executeWrite( - 'UPDATE users SET api_key = ? WHERE id = ? RETURNING api_key', - [newApiKey, userId] - ); + const result = await this.dbSession.executeWrite('UPDATE users SET api_key = ? WHERE id = ? RETURNING api_key', [ + newApiKey, + userId, + ]); if (!result.results[0]) { throw new Error('Failed to update API key'); } const apiKey = (result.results[0] as { api_key: string }).api_key; - try { this.posthog?.track('User API Key Regenerated', { userId }); } catch { } + try { + this.posthog?.track('User API Key Regenerated', { userId }); + } catch {} return apiKey; } } diff --git a/src/services/bars/handlers.ts b/src/services/bars/handlers.ts index 48907a3..1c299a4 100644 --- a/src/services/bars/handlers.ts +++ b/src/services/bars/handlers.ts @@ -76,75 +76,60 @@ export class StopbarHandler extends BarsTypeHandler { if (points.length < 2) return []; const lightPoints = generateEquidistantPoints(points, STOPBAR_SPACING); - const headingAdjustment = this.getHeadingAdjustment(dbRecord.orientation) + 90; - - if (lightPoints.length >= 2) { - const initialHeading = calculateHeading(lightPoints[0], lightPoints[1]); - const needsReversal = initialHeading > 180 && initialHeading < 360; - - if (needsReversal) { - const extraAdjustment = 180; - const lightsWithHeading = this.addHeadingToPoints(lightPoints, headingAdjustment + extraAdjustment); - - const lightsWithProperties = lightsWithHeading.map( - (light): BarsLightPoint => ({ - ...light, - properties: { - type: 'stopbar', - color: dbRecord.color || 'red', - orientation: dbRecord.orientation, - elevated: false, - ihp: dbRecord.ihp, - }, - }), - ); - - // Generate IHP lights if needed - let allLights = [...lightsWithProperties]; - - if (dbRecord.ihp) { - const ihpLights = this.generateIHPLights(lightPoints, lightsWithHeading, headingAdjustment + extraAdjustment, dbRecord); - allLights = [...allLights, ...ihpLights]; - } - - // Handle elevated lights if needed - if (dbRecord.elevated) { - const elevatedLights = this.generateElevatedLights(lightPoints, lightsWithHeading, headingAdjustment + extraAdjustment); - allLights = [...allLights, ...elevatedLights]; - } - - return allLights; + // First derive along-line headings without any adjustment + const alongHeadings = this.addHeadingToPoints(lightPoints, 0); + + // Orientation mapping requirement (perpendicular to line): + // We compute perpendicular headings (seg - 90) and (seg + 90). + // Flipped per latest feedback: + // left -> choose perpendicular in north/east half (<180) + // right -> choose perpendicular in south/west half (>=180) + // both -> deterministic choice (south/west half) so stable output. + const orientation = dbRecord.orientation || 'both'; + + const lightsWithHeading: BarsLightPoint[] = alongHeadings.map((p) => { + const seg = ((p.heading % 360) + 360) % 360; // along-line heading + const perpA = (seg + 90) % 360; // right side relative to direction of drawing + const perpB = (seg + 270) % 360; // left side (seg - 90) + // Determine which candidate is north/east (<180) vs south/west (>=180) + const candidateNorthEast = perpA < 180 ? perpA : perpB < 180 ? perpB : perpA; // one <180 if possible + const candidateSouthWest = perpA >= 180 ? perpA : perpB >= 180 ? perpB : perpA; // one >=180 if possible + let chosen: number; + if (orientation === 'right') { + chosen = candidateSouthWest; // flipped + } else if (orientation === 'left') { + chosen = candidateNorthEast; // flipped + } else { + // both -> deterministic pick south/west + chosen = candidateSouthWest; } - } - - // If no reversal needed, proceed with normal processing - const lightsWithHeading = this.addHeadingToPoints(lightPoints, headingAdjustment); + return { ...p, heading: chosen }; + }); - // Add properties to all lights - const lightsWithProperties = lightsWithHeading.map( - (light): BarsLightPoint => ({ - ...light, - properties: { - type: 'stopbar', - color: dbRecord.color || 'red', - orientation: dbRecord.orientation, - elevated: false, - ihp: dbRecord.ihp, - }, - }), - ); + // Add properties to base stopbar lights + const lightsWithProperties: BarsLightPoint[] = lightsWithHeading.map((light): BarsLightPoint => ({ + ...light, + properties: { + type: 'stopbar', + color: dbRecord.color || 'red', + orientation: dbRecord.orientation, + elevated: false, + ihp: dbRecord.ihp, + }, + })); - // Generate IHP lights if needed - let allLights = [...lightsWithProperties]; + let allLights: BarsLightPoint[] = [...lightsWithProperties]; + // IHP lights (inherit chosen heading at center) if (dbRecord.ihp) { - const ihpLights = this.generateIHPLights(lightPoints, lightsWithHeading, headingAdjustment, dbRecord); + const ihpLights = this.generateIHPLights(lightPoints, lightsWithHeading, 0, dbRecord); allLights = [...allLights, ...ihpLights]; } - // Handle elevated lights if needed - if (dbRecord.elevated) { - const elevatedLights = this.generateElevatedLights(lightPoints, lightsWithHeading, headingAdjustment); + // Elevated lights (need baseline line direction). Compute baseline from first segment. + if (dbRecord.elevated && lightPoints.length >= 2) { + const baseLineHeading = calculateHeading(lightPoints[0], lightPoints[1]); + const elevatedLights = this.generateElevatedLights(lightPoints, lightsWithHeading, baseLineHeading); allLights = [...allLights, ...elevatedLights]; } @@ -225,7 +210,7 @@ export class StopbarHandler extends BarsTypeHandler { /** * Generate elevated lights at the ends of a stopbar */ - private generateElevatedLights(points: GeoPoint[], lightsWithHeading: BarsLightPoint[], headingAdjustment: number): BarsLightPoint[] { + private generateElevatedLights(points: GeoPoint[], lightsWithHeading: BarsLightPoint[], baseLineHeading: number): BarsLightPoint[] { if (points.length < 2 || lightsWithHeading.length < 2) return []; const elevatedLights: BarsLightPoint[] = []; @@ -234,9 +219,7 @@ export class StopbarHandler extends BarsTypeHandler { const firstLight = lightsWithHeading[0]; const lastLight = lightsWithHeading[lightsWithHeading.length - 1]; - // Get the direction of the stopbar line - // We need to adjust by -90 because the heading is perpendicular to the stopbar - const baseLineHeading = (firstLight.heading - 90) % 360; + // baseLineHeading provided (direction along the stopbar line) // Step 1: Calculate the extension points - placing them exactly 1 meter beyond each end of the stopbar // First point - elevated light placed exactly 1 meter BEFORE the first light (extending the line) diff --git a/src/services/cache.ts b/src/services/cache.ts index 8caf72e..2f239d8 100644 --- a/src/services/cache.ts +++ b/src/services/cache.ts @@ -1,6 +1,6 @@ interface CacheOptions { - ttl?: number; // Time to live in seconds - namespace?: string; + ttl?: number; // Time to live in seconds + namespace?: string; } /** @@ -8,67 +8,67 @@ interface CacheOptions { * More efficient than KV for short-lived cached data */ export class CacheService { - constructor(private env: Env) { } - - /** - * Get data from cache - * @param key - Cache key - * @returns Cached data or null if not found - */ - async get(key: string, namespace = 'default'): Promise { - // Create a cache key with namespace - const cacheKey = new Request(`https://cache.stopbars/${namespace}/${key}`); - - // Try to get from cache - const cache = caches.default; - const cachedResponse = await cache.match(cacheKey); - - if (!cachedResponse) { - return null; - } - - try { - return await cachedResponse.json(); - } catch (e) { - return null; - } - } - - /** - * Set data in cache - * @param key - Cache key - * @param data - Data to cache - * @param options - Cache options - */ - async set(key: string, data: T, options: CacheOptions = {}): Promise { - const { ttl = 60, namespace = 'default' } = options; - - // Create a cache key with namespace - const cacheKey = new Request(`https://cache.stopbars/${namespace}/${key}`); - - // Create response with the data - const response = new Response(JSON.stringify(data), { - headers: { - 'Content-Type': 'application/json', - 'Cache-Control': `max-age=${ttl}`, - }, - }); - - // Store in cache - const cache = caches.default; - await cache.put(cacheKey, response); - } - - /** - * Delete data from cache - * @param key - Cache key - * @param namespace - Cache namespace - */ - async delete(key: string, namespace = 'default'): Promise { - const cacheKey = new Request(`https://cache.stopbars/${namespace}/${key}`); - const cache = caches.default; - await cache.delete(cacheKey); - } + constructor(private env: Env) {} + + /** + * Get data from cache + * @param key - Cache key + * @returns Cached data or null if not found + */ + async get(key: string, namespace = 'default'): Promise { + // Create a cache key with namespace + const cacheKey = new Request(`https://cache.stopbars/${namespace}/${key}`); + + // Try to get from cache + const cache = caches.default; + const cachedResponse = await cache.match(cacheKey); + + if (!cachedResponse) { + return null; + } + + try { + return await cachedResponse.json(); + } catch (e) { + return null; + } + } + + /** + * Set data in cache + * @param key - Cache key + * @param data - Data to cache + * @param options - Cache options + */ + async set(key: string, data: T, options: CacheOptions = {}): Promise { + const { ttl = 60, namespace = 'default' } = options; + + // Create a cache key with namespace + const cacheKey = new Request(`https://cache.stopbars/${namespace}/${key}`); + + // Create response with the data + const response = new Response(JSON.stringify(data), { + headers: { + 'Content-Type': 'application/json', + 'Cache-Control': `max-age=${ttl}`, + }, + }); + + // Store in cache + const cache = caches.default; + await cache.put(cacheKey, response); + } + + /** + * Delete data from cache + * @param key - Cache key + * @param namespace - Cache namespace + */ + async delete(key: string, namespace = 'default'): Promise { + const cacheKey = new Request(`https://cache.stopbars/${namespace}/${key}`); + const cache = caches.default; + await cache.delete(cacheKey); + } } /** @@ -77,82 +77,82 @@ export class CacheService { * @param ttl - Time to live in seconds * @param namespace - Cache namespace */ -export function withCache( - cacheKeyFn: (req: Request) => string, - ttl: number = 60, - namespace: string = 'default' -) { - return async (c: any, next: () => Promise) => { - // Skip caching for non-GET requests - if (c.req.method !== 'GET') { - return next(); - } - - const cacheService = new CacheService(c.env); - const cacheKey = cacheKeyFn(c.req.raw); - - // Try to get from cache - const cachedData = await cacheService.get(cacheKey, namespace); - if (cachedData) { - // Set header to indicate cache hit - c.header('X-Cache', 'HIT'); - return c.json(cachedData); - } - - // Cache miss, proceed to handler - c.header('X-Cache', 'MISS'); - await next(); - - // After handler executes, cache the response if it was successful - // Don't cache error responses (4xx, 5xx) including 404 Not Found - if (c.res && c.res.status >= 200 && c.res.status < 300) { - try { - // Clone the response to read it without consuming the original - const clonedRes = c.res.clone(); - const contentType = clonedRes.headers.get('content-type'); - - // Only cache JSON responses - if (contentType && contentType.includes('application/json')) { - const data = await clonedRes.json(); - // Cache the data - await cacheService.set(cacheKey, data, { ttl, namespace }); - } - } catch (e) { - // Silently fail if we can't cache - console.error('Failed to cache response:', e); - } - } - }; +export function withCache(cacheKeyFn: (req: Request) => string, ttl: number = 60, namespace: string = 'default') { + return async (c: any, next: () => Promise) => { + // Skip caching for non-GET requests + if (c.req.method !== 'GET') { + return next(); + } + + const cacheService = new CacheService(c.env); + const cacheKey = cacheKeyFn(c.req.raw); + + // Try to get from cache + const cachedData = await cacheService.get(cacheKey, namespace); + if (cachedData) { + // Set header to indicate cache hit + c.header('X-Cache', 'HIT'); + return c.json(cachedData); + } + + // Cache miss, proceed to handler + c.header('X-Cache', 'MISS'); + await next(); + + // After handler executes, cache the response if it was successful + // Don't cache error responses (4xx, 5xx) including 404 Not Found + if (c.res && c.res.status >= 200 && c.res.status < 300) { + try { + // Clone the response to read it without consuming the original + const clonedRes = c.res.clone(); + const contentType = clonedRes.headers.get('content-type'); + + // Only cache JSON responses + if (contentType && contentType.includes('application/json')) { + const data = await clonedRes.json(); + // Cache the data + await cacheService.set(cacheKey, data, { ttl, namespace }); + } + } catch (e) { + // Silently fail if we can't cache + console.error('Failed to cache response:', e); + } + } + }; } /** * Simple cache key generators for common patterns */ export const CacheKeys = { - /** - * Generate cache key from URL path and query params - */ - fromUrl: (req: Request): string => { - const url = new URL(req.url); - return `${url.pathname}${url.search}`; - }, - - /** - * Generate cache key from specific query parameters - */ - fromParams: (...params: string[]) => (req: Request): string => { - const url = new URL(req.url); - const values = params.map(p => url.searchParams.get(p) || '').join('-'); - return `${url.pathname}-${values}`; - }, - - /** - * Generate cache key with user context (for authenticated endpoints) - */ - withUser: (baseKey: string) => (req: Request): string => { - const token = req.headers.get('X-Vatsim-Token') || 'anonymous'; - // Use a hash of the token to avoid storing sensitive data in cache keys - const userHash = token.substring(0, 8); // Simple approach, could use proper hashing - return `${baseKey}-user-${userHash}`; - }, + /** + * Generate cache key from URL path and query params + */ + fromUrl: (req: Request): string => { + const url = new URL(req.url); + return `${url.pathname}${url.search}`; + }, + + /** + * Generate cache key from specific query parameters + */ + fromParams: + (...params: string[]) => + (req: Request): string => { + const url = new URL(req.url); + const values = params.map((p) => url.searchParams.get(p) || '').join('-'); + return `${url.pathname}-${values}`; + }, + + /** + * Generate cache key with user context (for authenticated endpoints) + */ + withUser: + (baseKey: string) => + (req: Request): string => { + const token = req.headers.get('X-Vatsim-Token') || 'anonymous'; + // Use a hash of the token to avoid storing sensitive data in cache keys + const userHash = token.substring(0, 8); // Simple approach, could use proper hashing + return `${baseKey}-user-${userHash}`; + }, }; diff --git a/src/services/contributions.ts b/src/services/contributions.ts index 961eb49..a5a4100 100644 --- a/src/services/contributions.ts +++ b/src/services/contributions.ts @@ -89,7 +89,7 @@ export class ContributionService { // Get authoritative display name from users table (ignore any client-provided value) const userDisplayResult = await this.dbSession.executeRead<{ display_name: string | null }>( 'SELECT display_name FROM users WHERE vatsim_id = ?', - [submission.userId] + [submission.userId], ); const authoritativeDisplayName = userDisplayResult.results[0]?.display_name || null; await this.dbSession.executeWrite( @@ -110,10 +110,9 @@ export class ContributionService { submission.notes || null, now, 'pending', - ] + ], ); - const contribution: Contribution = { id, userId: submission.userId, @@ -127,7 +126,13 @@ export class ContributionService { rejectionReason: null, decisionDate: null, }; - try { this.posthog?.track('Contribution Submitted', { airport: submission.airportIcao, packageName: submission.packageName, userId: submission.userId }); } catch { } + try { + this.posthog?.track('Contribution Submitted', { + airport: submission.airportIcao, + packageName: submission.packageName, + userId: submission.userId, + }); + } catch {} return contribution; } async getContribution(id: string): Promise { @@ -142,7 +147,30 @@ export class ContributionService { FROM contributions WHERE id = ? `, - [id] + [id], + ); + return result.results[0] || null; + } + + /** + * Get the most recently approved contribution for an airport (by decision_date) + * @param airportIcao ICAO code + */ + async getLatestApprovedContributionForAirport(airportIcao: string): Promise { + const result = await this.dbSession.executeRead( + ` + SELECT + id, user_id as userId, user_display_name as userDisplayName, + airport_icao as airportIcao, package_name as packageName, + submitted_xml as submittedXml, notes, + submission_date as submissionDate, status, + rejection_reason as rejectionReason, decision_date as decisionDate + FROM contributions + WHERE airport_icao = ? AND status = 'approved' + ORDER BY datetime(decision_date) DESC + LIMIT 1 + `, + [airportIcao], ); return result.results[0] || null; } @@ -174,10 +202,7 @@ export class ContributionService { const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : ''; const countQuery = `SELECT COUNT(*) as total FROM contributions ${whereClause}`; - const countResult = await this.dbSession.executeRead<{ total: number }>( - countQuery, - params - ); + const countResult = await this.dbSession.executeRead<{ total: number }>(countQuery, params); const total = countResult.results[0]?.total || 0; const offset = (page - 1) * limit; @@ -196,10 +221,7 @@ export class ContributionService { LIMIT ? OFFSET ? `; - const contributionsResult = await this.dbSession.executeRead( - query, - [...params, limit, offset] - ); + const contributionsResult = await this.dbSession.executeRead(query, [...params, limit, offset]); return { contributions: contributionsResult.results, total, @@ -210,10 +232,7 @@ export class ContributionService { } async processDecision(id: string, userId: string, decision: ContributionDecision): Promise { - const userInfoResult = await this.dbSession.executeRead<{ id: number }>( - 'SELECT id FROM users WHERE vatsim_id = ?', - [userId] - ); + const userInfoResult = await this.dbSession.executeRead<{ id: number }>('SELECT id FROM users WHERE vatsim_id = ?', [userId]); const userInfo = userInfoResult.results[0]; if (!userInfo) { @@ -253,12 +272,7 @@ export class ContributionService { AND status = 'approved' AND id != ? `, - [ - now, - contribution.airportIcao, - packageName, - id, - ] + [now, contribution.airportIcao, packageName, id], ); // Generate and upload the XML files to CDN @@ -308,10 +322,9 @@ export class ContributionService { SET status = ?, rejection_reason = ?, decision_date = ?, package_name = ? WHERE id = ? `, - [status, decision.approved ? null : decision.rejectionReason || 'No reason provided', now, packageName, id] + [status, decision.approved ? null : decision.rejectionReason || 'No reason provided', now, packageName, id], ); - const updated: Contribution = { ...contribution, packageName, @@ -327,7 +340,7 @@ export class ContributionService { decidedBy: userId, rejectionReason: decision.approved ? undefined : decision.rejectionReason || 'No reason provided', }); - } catch { } + } catch {} return updated; } async getContributionStats(): Promise<{ @@ -342,25 +355,22 @@ export class ContributionService { const oneWeekAgoStr = oneWeekAgo.toISOString(); // Get counts for different statuses - const totalResult = await this.dbSession.executeRead<{ count: number }>( - 'SELECT COUNT(*) as count FROM contributions', - [] - ); + const totalResult = await this.dbSession.executeRead<{ count: number }>('SELECT COUNT(*) as count FROM contributions', []); const pendingResult = await this.dbSession.executeRead<{ count: number }>( 'SELECT COUNT(*) as count FROM contributions WHERE status = ?', - ['pending'] + ['pending'], ); const approvedResult = await this.dbSession.executeRead<{ count: number }>( 'SELECT COUNT(*) as count FROM contributions WHERE status = ?', - ['approved'] + ['approved'], ); const rejectedResult = await this.dbSession.executeRead<{ count: number }>( 'SELECT COUNT(*) as count FROM contributions WHERE status = ?', - ['rejected'] + ['rejected'], ); const lastWeekResult = await this.dbSession.executeRead<{ count: number }>( 'SELECT COUNT(*) as count FROM contributions WHERE submission_date > ?', - [oneWeekAgoStr] + [oneWeekAgoStr], ); return { total: totalResult.results[0]?.count || 0, @@ -371,10 +381,7 @@ export class ContributionService { }; } async deleteContribution(id: string, userId: string): Promise { - const userInfoResult = await this.dbSession.executeRead<{ id: number }>( - 'SELECT id FROM users WHERE vatsim_id = ?', - [userId] - ); + const userInfoResult = await this.dbSession.executeRead<{ id: number }>('SELECT id FROM users WHERE vatsim_id = ?', [userId]); const userInfo = userInfoResult.results[0]; if (!userInfo) { throw new Error('User not found'); @@ -383,11 +390,12 @@ export class ContributionService { if (!hasPermission) { throw new Error('Not authorized to delete contributions'); } - const result = await this.dbSession.executeWrite( - 'DELETE FROM contributions WHERE id = ?', - [id] - ); - if (result.success) { try { this.posthog?.track('Contribution Deleted', { id, userId }); } catch { } } + const result = await this.dbSession.executeWrite('DELETE FROM contributions WHERE id = ?', [id]); + if (result.success) { + try { + this.posthog?.track('Contribution Deleted', { id, userId }); + } catch {} + } return result.success; } /** @@ -435,7 +443,7 @@ export class ContributionService { FROM contributions WHERE user_id = ? `, - [userId] + [userId], ); const summaryRow = summaryResult.results[0] || { total: 0, approved: 0, pending: 0, rejected: 0 }; const summary = { @@ -474,10 +482,7 @@ export class ContributionService { LIMIT ? OFFSET ? `; - const contributionsResult = await this.dbSession.executeRead( - query, - [...params, limit, offset] - ); + const contributionsResult = await this.dbSession.executeRead(query, [...params, limit, offset]); return { contributions: contributionsResult.results, summary, @@ -507,9 +512,7 @@ export class ContributionService { const results = await this.dbSession.executeRead<{ packageName: string; count: number; - }>( - query - ); + }>(query); return results.results; } async getContributionLeaderboard(): Promise< @@ -532,7 +535,7 @@ export class ContributionService { display_name: string | null; contribution_count: number; }>(query); - return results.results.map(r => ({ name: r.display_name || r.user_id, count: r.contribution_count })); + return results.results.map((r) => ({ name: r.display_name || r.user_id, count: r.contribution_count })); } // Removed legacy user display name update + lookup helpers; display names now sourced directly from users table } diff --git a/src/services/database-context.ts b/src/services/database-context.ts index e1b76a0..f716d21 100644 --- a/src/services/database-context.ts +++ b/src/services/database-context.ts @@ -5,45 +5,38 @@ import { DatabaseSessionService, SessionOptions } from './database-session'; * Handles extracting bookmarks from request headers and setting response headers */ export class BookmarkManager { - private static readonly BOOKMARK_HEADER = 'x-d1-bookmark'; - - /** - * Extract bookmark from request headers - */ - public static getBookmarkFromRequest(request: Request): string | undefined { - return request.headers.get(BookmarkManager.BOOKMARK_HEADER) || undefined; - } - - /** - * Set bookmark in response headers - */ - public static setBookmarkInResponse(response: Response, bookmark: string | null): void { - if (bookmark) { - response.headers.set(BookmarkManager.BOOKMARK_HEADER, bookmark); - } - } - - /** - * Create a new Response with bookmark header set - */ - public static responseWithBookmark( - body: any, - bookmark: string | null, - init: ResponseInit = {} - ): Response { - const headers = new Headers(init.headers); - if (bookmark) { - headers.set(BookmarkManager.BOOKMARK_HEADER, bookmark); - } - - return new Response( - typeof body === 'string' ? body : JSON.stringify(body), - { - ...init, - headers - } - ); - } + private static readonly BOOKMARK_HEADER = 'x-d1-bookmark'; + + /** + * Extract bookmark from request headers + */ + public static getBookmarkFromRequest(request: Request): string | undefined { + return request.headers.get(BookmarkManager.BOOKMARK_HEADER) || undefined; + } + + /** + * Set bookmark in response headers + */ + public static setBookmarkInResponse(response: Response, bookmark: string | null): void { + if (bookmark) { + response.headers.set(BookmarkManager.BOOKMARK_HEADER, bookmark); + } + } + + /** + * Create a new Response with bookmark header set + */ + public static responseWithBookmark(body: any, bookmark: string | null, init: ResponseInit = {}): Response { + const headers = new Headers(init.headers); + if (bookmark) { + headers.set(BookmarkManager.BOOKMARK_HEADER, bookmark); + } + + return new Response(typeof body === 'string' ? body : JSON.stringify(body), { + ...init, + headers, + }); + } } /** @@ -51,124 +44,112 @@ export class BookmarkManager { * Automatically manages sessions and bookmarks for the request lifecycle */ export class RequestDatabaseContext { - private sessionService: DatabaseSessionService; - private request: Request; - private isStarted: boolean = false; - - constructor(db: D1Database, request: Request) { - this.sessionService = new DatabaseSessionService(db); - this.request = request; - } - - /** - * Start a session using bookmark from request headers or specified options - */ - public startSession(options: Omit = {}): void { - if (this.isStarted) { - return; // Already started - } - - const bookmark = BookmarkManager.getBookmarkFromRequest(this.request); - const sessionOptions: SessionOptions = { - ...options, - bookmark: bookmark || options.mode || 'first-unconstrained' - }; - - this.sessionService.startSession(sessionOptions); - this.isStarted = true; - } - - /** - * Get the database session service - */ - public get db(): DatabaseSessionService { - if (!this.isStarted) { - this.startSession(); - } - return this.sessionService; - } - - /** - * Create a JSON response with bookmark header - */ - public jsonResponse(data: any, init: ResponseInit = {}): Response { - const bookmark = this.sessionService.getBookmark(); - - const headers = new Headers(init.headers); - headers.set('Content-Type', 'application/json'); - - return BookmarkManager.responseWithBookmark( - JSON.stringify(data), - bookmark, - { ...init, headers } - ); - } - - /** - * Create a text response with bookmark header - */ - public textResponse(text: string, init: ResponseInit = {}): Response { - const bookmark = this.sessionService.getBookmark(); - return BookmarkManager.responseWithBookmark(text, bookmark, init); - } - - /** - * Close the session and clean up - */ - public close(): void { - this.sessionService.closeSession(); - this.isStarted = false; - } - - /** - * Get current session info for debugging - */ - public getSessionInfo() { - return { - ...this.sessionService.getSessionInfo(), - isStarted: this.isStarted, - requestBookmark: BookmarkManager.getBookmarkFromRequest(this.request) - }; - } + private sessionService: DatabaseSessionService; + private request: Request; + private isStarted: boolean = false; + + constructor(db: D1Database, request: Request) { + this.sessionService = new DatabaseSessionService(db); + this.request = request; + } + + /** + * Start a session using bookmark from request headers or specified options + */ + public startSession(options: Omit = {}): void { + if (this.isStarted) { + return; // Already started + } + + const bookmark = BookmarkManager.getBookmarkFromRequest(this.request); + const sessionOptions: SessionOptions = { + ...options, + bookmark: bookmark || options.mode || 'first-unconstrained', + }; + + this.sessionService.startSession(sessionOptions); + this.isStarted = true; + } + + /** + * Get the database session service + */ + public get db(): DatabaseSessionService { + if (!this.isStarted) { + this.startSession(); + } + return this.sessionService; + } + + /** + * Create a JSON response with bookmark header + */ + public jsonResponse(data: any, init: ResponseInit = {}): Response { + const bookmark = this.sessionService.getBookmark(); + + const headers = new Headers(init.headers); + headers.set('Content-Type', 'application/json'); + + return BookmarkManager.responseWithBookmark(JSON.stringify(data), bookmark, { ...init, headers }); + } + + /** + * Create a text response with bookmark header + */ + public textResponse(text: string, init: ResponseInit = {}): Response { + const bookmark = this.sessionService.getBookmark(); + return BookmarkManager.responseWithBookmark(text, bookmark, init); + } + + /** + * Close the session and clean up + */ + public close(): void { + this.sessionService.closeSession(); + this.isStarted = false; + } + + /** + * Get current session info for debugging + */ + public getSessionInfo() { + return { + ...this.sessionService.getSessionInfo(), + isStarted: this.isStarted, + requestBookmark: BookmarkManager.getBookmarkFromRequest(this.request), + }; + } } /** * Factory for creating database contexts */ export class DatabaseContextFactory { - /** - * Create a new request database context - */ - public static createRequestContext(db: D1Database, request: Request): RequestDatabaseContext { - return new RequestDatabaseContext(db, request); - } - - /** - * Create a simple session service for background operations - */ - public static createSessionService(db: D1Database): DatabaseSessionService { - return new DatabaseSessionService(db); - } - - /** - * Quick read operation for simple queries - */ - public static async quickRead( - db: D1Database, - query: string, - params: any[] = [] - ) { - return DatabaseSessionService.simpleRead(db, query, params); - } - - /** - * Quick write operation for simple queries - */ - public static async quickWrite( - db: D1Database, - query: string, - params: any[] = [] - ) { - return DatabaseSessionService.simpleWrite(db, query, params); - } + /** + * Create a new request database context + */ + public static createRequestContext(db: D1Database, request: Request): RequestDatabaseContext { + return new RequestDatabaseContext(db, request); + } + + /** + * Create a simple session service for background operations + */ + public static createSessionService(db: D1Database): DatabaseSessionService { + return new DatabaseSessionService(db); + } + + /** + * Quick read operation for simple queries + */ + public static async quickRead(db: D1Database, query: string, params: any[] = []) { + return DatabaseSessionService.simpleRead(db, query, params); + } + + /** + * Quick write operation for simple queries + */ + public static async quickWrite(db: D1Database, query: string, params: any[] = []) { + return DatabaseSessionService.simpleWrite(db, query, params); + } } diff --git a/src/services/database-session.ts b/src/services/database-session.ts index 16e0115..038ee9e 100644 --- a/src/services/database-session.ts +++ b/src/services/database-session.ts @@ -1,40 +1,40 @@ // D1 types are available globally in Cloudflare Workers environment export interface SessionOptions { - /** - * Session mode for D1 read replication - * - 'first-primary': Start with latest data from primary (use for writes or critical reads) - * - 'first-unconstrained': Start with any available instance (use for non-critical reads) - * - bookmark string: Start from a specific bookmark - */ - mode?: 'first-primary' | 'first-unconstrained' | string; - - /** - * Optional bookmark from a previous session for sequential consistency - */ - bookmark?: string; + /** + * Session mode for D1 read replication + * - 'first-primary': Start with latest data from primary (use for writes or critical reads) + * - 'first-unconstrained': Start with any available instance (use for non-critical reads) + * - bookmark string: Start from a specific bookmark + */ + mode?: 'first-primary' | 'first-unconstrained' | string; + + /** + * Optional bookmark from a previous session for sequential consistency + */ + bookmark?: string; } export interface DatabaseMeta { - served_by_region?: string; - served_by_primary?: boolean; - duration?: number; - changes?: number; - last_row_id?: number; - changed_db?: boolean; - size_after?: number; + served_by_region?: string; + served_by_primary?: boolean; + duration?: number; + changes?: number; + last_row_id?: number; + changed_db?: boolean; + size_after?: number; } export interface DatabaseResult { - results: T[]; - success: boolean; - meta?: DatabaseMeta; + results: T[]; + success: boolean; + meta?: DatabaseMeta; } export interface DatabaseResponse { - results?: T | null; - success: boolean; - meta?: DatabaseMeta; + results?: T | null; + success: boolean; + meta?: DatabaseMeta; } export type DatabaseSerializable = null | number | string | boolean | ArrayBuffer; @@ -49,194 +49,183 @@ export type DatabaseBinding = Record; * - Optimized routing for read vs write operations */ export class DatabaseSessionService { - private session: D1DatabaseSession | null = null; - private currentBookmark: string | null = null; - private readonly db: D1Database; - - constructor(db: D1Database) { - this.db = db; - } - - /** - * Start a new database session with optional configuration - */ - public startSession(options: SessionOptions = {}): void { - let sessionParam: string | undefined; - - if (options.bookmark) { - // Use provided bookmark for sequential consistency - sessionParam = options.bookmark; - } else if (options.mode === 'first-primary') { - // Start with latest data from primary - sessionParam = 'first-primary'; - } else { - // Default to unconstrained for better performance - sessionParam = 'first-unconstrained'; - } - - this.session = this.db.withSession(sessionParam); - this.currentBookmark = null; - } - - /** - * Get the current session bookmark for maintaining consistency - */ - public getBookmark(): string | null { - if (!this.session) { - return null; - } - - const bookmark = this.session.getBookmark(); - if (bookmark) { - this.currentBookmark = bookmark; - } - return bookmark; - } + private session: D1DatabaseSession | null = null; + private currentBookmark: string | null = null; + private readonly db: D1Database; + + constructor(db: D1Database) { + this.db = db; + } + + /** + * Start a new database session with optional configuration + */ + public startSession(options: SessionOptions = {}): void { + let sessionParam: string | undefined; + + if (options.bookmark) { + // Use provided bookmark for sequential consistency + sessionParam = options.bookmark; + } else if (options.mode === 'first-primary') { + // Start with latest data from primary + sessionParam = 'first-primary'; + } else { + // Default to unconstrained for better performance + sessionParam = 'first-unconstrained'; + } + + this.session = this.db.withSession(sessionParam); + this.currentBookmark = null; + } + + /** + * Get the current session bookmark for maintaining consistency + */ + public getBookmark(): string | null { + if (!this.session) { + return null; + } + + const bookmark = this.session.getBookmark(); + if (bookmark) { + this.currentBookmark = bookmark; + } + return bookmark; + } /** * Create a type-safe prepared statement */ - public prepare( - query: string, - bindings: (keyof T)[], - ): PreparedStatement { + public prepare(query: string, bindings: (keyof T)[]): PreparedStatement { return new PreparedStatement(this.db.prepare(query), bindings); } - /** - * Execute a prepared statement with session awareness - * Automatically starts a session if none exists - */ - public async execute( - query: string, - params: any[] = [], - options: SessionOptions = {} - ): Promise> { - // Start session if not already started - if (!this.session) { - this.startSession(options); - } - - try { - const stmt = this.session!.prepare(query); - let boundStmt = stmt; - - // Bind parameters if provided - if (params.length > 0) { - boundStmt = stmt.bind(...params); - } - - const result = await boundStmt.first(); - - // Update bookmark after operation - this.getBookmark(); - - return { - results: result, - success: true, - meta: {} - }; - } catch (error) { - console.error('Database execution error:', error); - throw error; - } - } - - /** - * Execute a query that returns all results - */ - public async executeAll( - query: string, - params: any[] = [], - options: SessionOptions = {} - ): Promise> { - // Start session if not already started - if (!this.session) { - this.startSession(options); - } - - try { - const stmt = this.session!.prepare(query); - let boundStmt = stmt; - - // Bind parameters if provided - if (params.length > 0) { - boundStmt = stmt.bind(...params); - } - - const result = await boundStmt.all(); - - // Update bookmark after operation - this.getBookmark(); - - return { - results: result.results || [], - success: true, - meta: result.meta || {} - }; - } catch (error) { - console.error('Database executeAll error:', error); - throw error; - } - } - - /** - * Execute a query that modifies data (INSERT, UPDATE, DELETE) - * Always uses primary database for consistency - */ - public async executeWrite( - query: string, - params: any[] = [] - ): Promise> { - // Force primary mode for write operations - if (!this.session) { - this.startSession({ mode: 'first-primary' }); - } - - try { - const stmt = this.session!.prepare(query); - let boundStmt = stmt; - - // Bind parameters if provided - if (params.length > 0) { - boundStmt = stmt.bind(...params); - } - - const result = await boundStmt.run(); - - // Update bookmark after write operation - this.getBookmark(); - - return { - results: result.results || null, - success: result.success, - meta: result.meta || {} - }; - } catch (error) { - console.error('Database write error:', error); - throw error; - } - } - - /** - * Execute multiple statements in a batch - * Uses primary database for consistency - */ - public async executeBatch( - statements: Array<{ - query: string; - params?: any[]; - } | D1PreparedStatement> + /** + * Execute a prepared statement with session awareness + * Automatically starts a session if none exists + */ + public async execute(query: string, params: any[] = [], options: SessionOptions = {}): Promise> { + // Start session if not already started + if (!this.session) { + this.startSession(options); + } + + try { + const stmt = this.session!.prepare(query); + let boundStmt = stmt; + + // Bind parameters if provided + if (params.length > 0) { + boundStmt = stmt.bind(...params); + } + + const result = await boundStmt.first(); + + // Update bookmark after operation + this.getBookmark(); + + return { + results: result, + success: true, + meta: {}, + }; + } catch (error) { + console.error('Database execution error:', error); + throw error; + } + } + + /** + * Execute a query that returns all results + */ + public async executeAll(query: string, params: any[] = [], options: SessionOptions = {}): Promise> { + // Start session if not already started + if (!this.session) { + this.startSession(options); + } + + try { + const stmt = this.session!.prepare(query); + let boundStmt = stmt; + + // Bind parameters if provided + if (params.length > 0) { + boundStmt = stmt.bind(...params); + } + + const result = await boundStmt.all(); + + // Update bookmark after operation + this.getBookmark(); + + return { + results: result.results || [], + success: true, + meta: result.meta || {}, + }; + } catch (error) { + console.error('Database executeAll error:', error); + throw error; + } + } + + /** + * Execute a query that modifies data (INSERT, UPDATE, DELETE) + * Always uses primary database for consistency + */ + public async executeWrite(query: string, params: any[] = []): Promise> { + // Force primary mode for write operations + if (!this.session) { + this.startSession({ mode: 'first-primary' }); + } + + try { + const stmt = this.session!.prepare(query); + let boundStmt = stmt; + + // Bind parameters if provided + if (params.length > 0) { + boundStmt = stmt.bind(...params); + } + + const result = await boundStmt.run(); + + // Update bookmark after write operation + this.getBookmark(); + + return { + results: result.results || null, + success: result.success, + meta: result.meta || {}, + }; + } catch (error) { + console.error('Database write error:', error); + throw error; + } + } + + /** + * Execute multiple statements in a batch + * Uses primary database for consistency + */ + public async executeBatch( + statements: Array< + | { + query: string; + params?: any[]; + } + | D1PreparedStatement + >, ): Promise[]> { if (statements.length === 0) return []; - // Force primary mode for batch operations - if (!this.session) { - this.startSession({ mode: 'first-primary' }); - } + // Force primary mode for batch operations + if (!this.session) { + this.startSession({ mode: 'first-primary' }); + } - try { - const preparedStatements = statements.map((statement) => { + try { + const preparedStatements = statements.map((statement) => { if ('query' in statement && typeof statement.query === 'string') { const { query, params = [] } = statement; const stmt = this.session!.prepare(query); @@ -244,109 +233,92 @@ export class DatabaseSessionService { } else { return statement as D1PreparedStatement; } - }); - - const results = await this.session!.batch(preparedStatements); - - // Update bookmark after batch operation - this.getBookmark(); - - return results; - } catch (error) { - console.error('Database batch error:', error); - throw error; - } - } - - /** - * Execute a read-only query optimized for performance - * Uses unconstrained mode for best performance - */ - public async executeRead( - query: string, - params: any[] = [], - bookmark?: string - ): Promise> { - // Use unconstrained mode for reads unless bookmark is provided - const sessionOptions: SessionOptions = bookmark - ? { bookmark } - : { mode: 'first-unconstrained' }; - - return this.executeAll(query, params, sessionOptions); - } - - /** - * Execute a query that requires the latest data - * Uses primary mode to ensure fresh data - */ - public async executeLatest( - query: string, - params: any[] = [] - ): Promise> { - return this.executeAll(query, params, { mode: 'first-primary' }); - } - - /** - * Close the current session and clean up resources - */ - public closeSession(): void { - this.session = null; - this.currentBookmark = null; - } - - /** - * Get current session statistics for observability - */ - public getSessionInfo(): { - hasSession: boolean; - hasBookmark: boolean; - bookmark: string | null; - } { - return { - hasSession: this.session !== null, - hasBookmark: this.currentBookmark !== null, - bookmark: this.currentBookmark - }; - } - - /** - * Static helper to create a session-aware database service - */ - public static create(db: D1Database): DatabaseSessionService { - return new DatabaseSessionService(db); - } - - /** - * Static helper for simple read operations - */ - public static async simpleRead( - db: D1Database, - query: string, - params: any[] = [] - ): Promise> { - const session = new DatabaseSessionService(db); - try { - return await session.executeRead(query, params); - } finally { - session.closeSession(); - } - } - - /** - * Static helper for simple write operations - */ - public static async simpleWrite( - db: D1Database, - query: string, - params: any[] = [] - ): Promise> { - const session = new DatabaseSessionService(db); - try { - return await session.executeWrite(query, params); - } finally { - session.closeSession(); - } - } + }); + + const results = await this.session!.batch(preparedStatements); + + // Update bookmark after batch operation + this.getBookmark(); + + return results; + } catch (error) { + console.error('Database batch error:', error); + throw error; + } + } + + /** + * Execute a read-only query optimized for performance + * Uses unconstrained mode for best performance + */ + public async executeRead(query: string, params: any[] = [], bookmark?: string): Promise> { + // Use unconstrained mode for reads unless bookmark is provided + const sessionOptions: SessionOptions = bookmark ? { bookmark } : { mode: 'first-unconstrained' }; + + return this.executeAll(query, params, sessionOptions); + } + + /** + * Execute a query that requires the latest data + * Uses primary mode to ensure fresh data + */ + public async executeLatest(query: string, params: any[] = []): Promise> { + return this.executeAll(query, params, { mode: 'first-primary' }); + } + + /** + * Close the current session and clean up resources + */ + public closeSession(): void { + this.session = null; + this.currentBookmark = null; + } + + /** + * Get current session statistics for observability + */ + public getSessionInfo(): { + hasSession: boolean; + hasBookmark: boolean; + bookmark: string | null; + } { + return { + hasSession: this.session !== null, + hasBookmark: this.currentBookmark !== null, + bookmark: this.currentBookmark, + }; + } + + /** + * Static helper to create a session-aware database service + */ + public static create(db: D1Database): DatabaseSessionService { + return new DatabaseSessionService(db); + } + + /** + * Static helper for simple read operations + */ + public static async simpleRead(db: D1Database, query: string, params: any[] = []): Promise> { + const session = new DatabaseSessionService(db); + try { + return await session.executeRead(query, params); + } finally { + session.closeSession(); + } + } + + /** + * Static helper for simple write operations + */ + public static async simpleWrite(db: D1Database, query: string, params: any[] = []): Promise> { + const session = new DatabaseSessionService(db); + try { + return await session.executeWrite(query, params); + } finally { + session.closeSession(); + } + } } /** @@ -356,10 +328,7 @@ export class PreparedStatement { private statement: D1PreparedStatement; private bindings: (keyof T)[]; - constructor( - statement: D1PreparedStatement, - bindings: (keyof T)[], - ) { + constructor(statement: D1PreparedStatement, bindings: (keyof T)[]) { this.statement = statement; this.bindings = bindings; } diff --git a/src/services/divisions.ts b/src/services/divisions.ts index 4a19094..2f5a727 100644 --- a/src/services/divisions.ts +++ b/src/services/divisions.ts @@ -29,79 +29,77 @@ interface DivisionAirport { export class DivisionService { private dbSession: DatabaseSessionService; - constructor(private db: D1Database, private posthog?: PostHogService) { + constructor( + private db: D1Database, + private posthog?: PostHogService, + ) { this.dbSession = new DatabaseSessionService(db); } async createDivision(name: string, headVatsimId: string): Promise { - const result = await this.dbSession.executeWrite( - 'INSERT INTO divisions (name) VALUES (?) RETURNING *', - [name] - ); + const result = await this.dbSession.executeWrite('INSERT INTO divisions (name) VALUES (?) RETURNING *', [name]); const division = result.results[0] as Division; if (!division) throw new Error('Failed to create division'); await this.addMember(division.id, headVatsimId, 'nav_head'); - try { this.posthog?.track('Division Created', { divisionId: division.id, name }); } catch { } + try { + this.posthog?.track('Division Created', { divisionId: division.id, name }); + } catch {} return division; } async updateDivisionName(id: number, newName: string): Promise { - const result = await this.dbSession.executeWrite( - 'UPDATE divisions SET name = ? WHERE id = ? RETURNING *', - [newName, id] - ); + const result = await this.dbSession.executeWrite('UPDATE divisions SET name = ? WHERE id = ? RETURNING *', [newName, id]); const division = result.results[0] as Division; if (!division) throw new Error('Division not found'); - try { this.posthog?.track('Division Renamed', { divisionId: id, name: newName }); } catch { } + try { + this.posthog?.track('Division Renamed', { divisionId: id, name: newName }); + } catch {} return division; } async deleteDivision(id: number): Promise { - const result = await this.dbSession.executeWrite( - 'DELETE FROM divisions WHERE id = ? RETURNING id', - [id] - ); + const result = await this.dbSession.executeWrite('DELETE FROM divisions WHERE id = ? RETURNING id', [id]); const deleted = !!result.results[0]; if (deleted) { - try { this.posthog?.track('Division Deleted', { divisionId: id }); } catch { } + try { + this.posthog?.track('Division Deleted', { divisionId: id }); + } catch {} } return deleted; } async getDivision(id: number): Promise { - const result = await this.dbSession.executeRead( - 'SELECT * FROM divisions WHERE id = ?', - [id] - ); + const result = await this.dbSession.executeRead('SELECT * FROM divisions WHERE id = ?', [id]); return result.results[0] || null; } async addMember(divisionId: number, vatsimId: string, role: 'nav_head' | 'nav_member'): Promise { const result = await this.dbSession.executeWrite( 'INSERT INTO division_members (division_id, vatsim_id, role) VALUES (?, ?, ?) RETURNING *', - [divisionId, vatsimId, role] + [divisionId, vatsimId, role], ); const member = result.results[0] as DivisionMember; if (!member) throw new Error('Failed to add member to division'); - try { this.posthog?.track('Division Member Added', { divisionId, vatsimId, role }); } catch { } + try { + this.posthog?.track('Division Member Added', { divisionId, vatsimId, role }); + } catch {} return member; } async removeMember(divisionId: number, vatsimId: string): Promise { - await this.dbSession.executeWrite( - 'DELETE FROM division_members WHERE division_id = ? AND vatsim_id = ?', - [divisionId, vatsimId] - ); - try { this.posthog?.track('Division Member Removed', { divisionId, vatsimId }); } catch { } + await this.dbSession.executeWrite('DELETE FROM division_members WHERE division_id = ? AND vatsim_id = ?', [divisionId, vatsimId]); + try { + this.posthog?.track('Division Member Removed', { divisionId, vatsimId }); + } catch {} } async getMemberRole(divisionId: number, vatsimId: string): Promise<'nav_head' | 'nav_member' | null> { const result = await this.dbSession.executeRead<{ role: 'nav_head' | 'nav_member' }>( 'SELECT role FROM division_members WHERE division_id = ? AND vatsim_id = ?', - [divisionId, vatsimId] + [divisionId, vatsimId], ); return result.results[0]?.role || null; @@ -112,12 +110,14 @@ export class DivisionService { const result = await this.dbSession.executeWrite( 'INSERT INTO division_airports (division_id, icao, requested_by) VALUES (?, ?, ?) RETURNING *', - [divisionId, icao, requestedBy] + [divisionId, icao, requestedBy], ); const request = result.results[0] as DivisionAirport; if (!request) throw new Error('Failed to create airport request'); - try { this.posthog?.track('Division Airport Access Requested', { divisionId, icao, requestedBy }); } catch { } + try { + this.posthog?.track('Division Airport Access Requested', { divisionId, icao, requestedBy }); + } catch {} return request; } async approveAirport(airportId: number, approvedBy: string, approved: boolean): Promise { @@ -128,20 +128,25 @@ export class DivisionService { WHERE id = ? RETURNING * `, - [approved ? 'approved' : 'rejected', approvedBy, airportId] + [approved ? 'approved' : 'rejected', approvedBy, airportId], ); const airport = result.results[0] as DivisionAirport; if (!airport) throw new Error('Airport request not found'); - try { this.posthog?.track(approved ? 'Division Airport Request Approved' : 'Division Airport Request Rejected', { airportId, approvedBy, approved }); } catch { } + try { + this.posthog?.track(approved ? 'Division Airport Request Approved' : 'Division Airport Request Rejected', { + airportId, + approvedBy, + approved, + }); + } catch {} return airport; } async getDivisionAirports(divisionId: number): Promise { - const result = await this.dbSession.executeRead( - 'SELECT * FROM division_airports WHERE division_id = ?', - [divisionId] - ); + const result = await this.dbSession.executeRead('SELECT * FROM division_airports WHERE division_id = ?', [ + divisionId, + ]); return result.results; } @@ -153,15 +158,13 @@ export class DivisionService { FROM division_members dm LEFT JOIN users u ON u.vatsim_id = dm.vatsim_id WHERE dm.division_id = ?`, - [divisionId] + [divisionId], ); return result.results; } async getAllDivisions(): Promise { - const result = await this.dbSession.executeRead( - 'SELECT * FROM divisions' - ); + const result = await this.dbSession.executeRead('SELECT * FROM divisions'); return result.results; } @@ -173,7 +176,7 @@ export class DivisionService { JOIN division_members dm ON d.id = dm.division_id WHERE dm.vatsim_id = ? `, - [vatsimId] + [vatsimId], ); return result.results; } @@ -185,7 +188,7 @@ export class DivisionService { JOIN division_members dm ON da.division_id = dm.division_id WHERE dm.vatsim_id = ? AND da.icao = ? AND da.status = 'approved' `, - [userId, airportIcao] + [userId, airportIcao], ); return result.results.length > 0; @@ -202,7 +205,7 @@ export class DivisionService { AND da.status = 'approved' LIMIT 1 `, - [userId, airportIcao] + [userId, airportIcao], ); return result.results[0]?.role || null; diff --git a/src/services/github.ts b/src/services/github.ts index 9e94d87..6b09366 100644 --- a/src/services/github.ts +++ b/src/services/github.ts @@ -3,207 +3,209 @@ */ interface GitHubContributor { - id: number; - login: string; - avatar_url: string; - html_url: string; - type: string; - contributions: number; - repositories: { - name: string; - contributions: number; - }[]; + id: number; + login: string; + avatar_url: string; + html_url: string; + type: string; + contributions: number; + repositories: { + name: string; + contributions: number; + }[]; } interface GitHubRepository { - name: string; - full_name: string; - html_url: string; - description: string | null; - stargazers_count: number; - language: string | null; - private: boolean; - created_at: string; - updated_at: string; + name: string; + full_name: string; + html_url: string; + description: string | null; + stargazers_count: number; + language: string | null; + private: boolean; + created_at: string; + updated_at: string; } interface GitHubContributorResponse { - id: number; - login: string; - avatar_url: string; - html_url: string; - type: string; - contributions: number; + id: number; + login: string; + avatar_url: string; + html_url: string; + type: string; + contributions: number; } interface ContributorsData { - contributors: GitHubContributor[]; - repositories: { - name: string; - fullName: string; - url: string; - description: string | null; - stars: number; - language: string | null; - contributorCount: number; - createdAt: string; - updatedAt: string; - }[]; - statistics: { - totalContributors: number; - totalRepositories: number; - totalContributions: number; - }; + contributors: GitHubContributor[]; + repositories: { + name: string; + fullName: string; + url: string; + description: string | null; + stars: number; + language: string | null; + contributorCount: number; + createdAt: string; + updatedAt: string; + }[]; + statistics: { + totalContributors: number; + totalRepositories: number; + totalContributions: number; + }; } export class GitHubService { - private readonly GITHUB_ORG = 'stopbars'; - - constructor() { } - - /** - * Get all public repositories for the organization - */ - private async getOrganizationRepositories(): Promise { - const repos: GitHubRepository[] = []; - let page = 1; - const perPage = 100; - - while (true) { - const res = await fetch(`https://api.github.com/orgs/${this.GITHUB_ORG}/repos?page=${page}&per_page=${perPage}&type=public`, { - headers: { - "User-Agent": "BARS-API", - "Accept": "application/vnd.github.v3+json", - }, - }); - - if (!res.ok) { - throw new Error(`Failed to fetch GitHub org repos: ${res.status}`); - } - - const pageRepos: GitHubRepository[] = await res.json(); - - if (pageRepos.length === 0) { - break; - } - - repos.push(...pageRepos); - - if (pageRepos.length < perPage) { - break; - } - - page++; - } - - return repos; - } - - /** - * Get contributors for a specific repository - */ - private async getRepositoryContributors(repoFullName: string): Promise { - try { - const res = await fetch(`https://api.github.com/repos/${repoFullName}/contributors?per_page=100`, { - headers: { - "User-Agent": "BARS-API", - "Accept": "application/vnd.github.v3+json", - }, - }); - - if (!res.ok) { - if (res.status === 404) { - // Repository might not exist or be accessible, skip it - return []; - } - throw new Error(`Failed to fetch GitHub contributors: ${res.status}`); - } - - const contributors: GitHubContributorResponse[] = await res.json(); - return contributors || []; - } catch (error) { - console.error(`Error fetching contributors for ${repoFullName}:`, error); - return []; - } - } - - /** - * Get all contributors across all organization repositories - */ - async getAllContributors(): Promise { - const allContributors = new Map(); - const repoData: ContributorsData['repositories'] = []; - - // Get all organization repositories - const orgRepos = await this.getOrganizationRepositories(); - - // Fetch contributors from each repository - for (const repoInfo of orgRepos) { - try { - // Skip private repositories (should already be filtered but double-check) - if (repoInfo.private) { - continue; - } - - const repoContributors = await this.getRepositoryContributors(repoInfo.full_name); - - repoData.push({ - name: repoInfo.name, - fullName: repoInfo.full_name, - url: repoInfo.html_url, - description: repoInfo.description, - stars: repoInfo.stargazers_count, - language: repoInfo.language, - contributorCount: repoContributors.length, - createdAt: repoInfo.created_at, - updatedAt: repoInfo.updated_at, - }); - - // Merge contributors (avoid duplicates) - repoContributors.forEach(contributor => { - if (contributor.type === 'User') { // Exclude bots - if (allContributors.has(contributor.id)) { - // Add contributions from this repo - const existing = allContributors.get(contributor.id)!; - existing.contributions += contributor.contributions; - existing.repositories.push({ - name: repoInfo.name, - contributions: contributor.contributions, - }); - } else { - // New contributor - allContributors.set(contributor.id, { - ...contributor, - repositories: [{ - name: repoInfo.name, - contributions: contributor.contributions, - }], - }); - } - } - }); - } catch (err) { - console.error(`Error fetching ${repoInfo.full_name}:`, err); - } - } - - // Convert Map to Array and sort by contributions - const contributorList = Array.from(allContributors.values()) - .sort((a, b) => b.contributions - a.contributions); - - // Sort repositories by stars - repoData.sort((a, b) => b.stars - a.stars); - - const totalContributions = contributorList.reduce((sum, contributor) => sum + contributor.contributions, 0); - - return { - contributors: contributorList, - repositories: repoData, - statistics: { - totalContributors: contributorList.length, - totalRepositories: repoData.length, - totalContributions, - }, - }; - } + private readonly GITHUB_ORG = 'stopbars'; + + constructor() {} + + /** + * Get all public repositories for the organization + */ + private async getOrganizationRepositories(): Promise { + const repos: GitHubRepository[] = []; + let page = 1; + const perPage = 100; + + while (true) { + const res = await fetch(`https://api.github.com/orgs/${this.GITHUB_ORG}/repos?page=${page}&per_page=${perPage}&type=public`, { + headers: { + 'User-Agent': 'BARS-API', + Accept: 'application/vnd.github.v3+json', + }, + }); + + if (!res.ok) { + throw new Error(`Failed to fetch GitHub org repos: ${res.status}`); + } + + const pageRepos: GitHubRepository[] = await res.json(); + + if (pageRepos.length === 0) { + break; + } + + repos.push(...pageRepos); + + if (pageRepos.length < perPage) { + break; + } + + page++; + } + + return repos; + } + + /** + * Get contributors for a specific repository + */ + private async getRepositoryContributors(repoFullName: string): Promise { + try { + const res = await fetch(`https://api.github.com/repos/${repoFullName}/contributors?per_page=100`, { + headers: { + 'User-Agent': 'BARS-API', + Accept: 'application/vnd.github.v3+json', + }, + }); + + if (!res.ok) { + if (res.status === 404) { + // Repository might not exist or be accessible, skip it + return []; + } + throw new Error(`Failed to fetch GitHub contributors: ${res.status}`); + } + + const contributors: GitHubContributorResponse[] = await res.json(); + return contributors || []; + } catch (error) { + console.error(`Error fetching contributors for ${repoFullName}:`, error); + return []; + } + } + + /** + * Get all contributors across all organization repositories + */ + async getAllContributors(): Promise { + const allContributors = new Map(); + const repoData: ContributorsData['repositories'] = []; + + // Get all organization repositories + const orgRepos = await this.getOrganizationRepositories(); + + // Fetch contributors from each repository + for (const repoInfo of orgRepos) { + try { + // Skip private repositories (should already be filtered but double-check) + if (repoInfo.private) { + continue; + } + + const repoContributors = await this.getRepositoryContributors(repoInfo.full_name); + + repoData.push({ + name: repoInfo.name, + fullName: repoInfo.full_name, + url: repoInfo.html_url, + description: repoInfo.description, + stars: repoInfo.stargazers_count, + language: repoInfo.language, + contributorCount: repoContributors.length, + createdAt: repoInfo.created_at, + updatedAt: repoInfo.updated_at, + }); + + // Merge contributors (avoid duplicates) + repoContributors.forEach((contributor) => { + if (contributor.type === 'User') { + // Exclude bots + if (allContributors.has(contributor.id)) { + // Add contributions from this repo + const existing = allContributors.get(contributor.id)!; + existing.contributions += contributor.contributions; + existing.repositories.push({ + name: repoInfo.name, + contributions: contributor.contributions, + }); + } else { + // New contributor + allContributors.set(contributor.id, { + ...contributor, + repositories: [ + { + name: repoInfo.name, + contributions: contributor.contributions, + }, + ], + }); + } + } + }); + } catch (err) { + console.error(`Error fetching ${repoInfo.full_name}:`, err); + } + } + + // Convert Map to Array and sort by contributions + const contributorList = Array.from(allContributors.values()).sort((a, b) => b.contributions - a.contributions); + + // Sort repositories by stars + repoData.sort((a, b) => b.stars - a.stars); + + const totalContributions = contributorList.reduce((sum, contributor) => sum + contributor.contributions, 0); + + return { + contributors: contributorList, + repositories: repoData, + statistics: { + totalContributors: contributorList.length, + totalRepositories: repoData.length, + totalContributions, + }, + }; + } } diff --git a/src/services/id.ts b/src/services/id.ts index 791f6a8..5fd45a5 100644 --- a/src/services/id.ts +++ b/src/services/id.ts @@ -17,10 +17,7 @@ export class IDService { while (true) { const uniqueId = nanoid(); const barsId = `${this.BARS_ID_PREFIX}_${uniqueId}`; - const result = await this.dbSession.executeRead<{ id: string }>( - 'SELECT id FROM points WHERE id = ?', - [barsId] - ); + const result = await this.dbSession.executeRead<{ id: string }>('SELECT id FROM points WHERE id = ?', [barsId]); if (!result.results[0]) { return barsId; } diff --git a/src/services/notam.ts b/src/services/notam.ts index ae9458d..53d1cd3 100644 --- a/src/services/notam.ts +++ b/src/services/notam.ts @@ -14,7 +14,7 @@ export class NotamService { try { const result = await this.dbSession.executeRead<{ content: string; type: string }>( 'SELECT id, content, type FROM notams WHERE id = ?', - ['global'] + ['global'], ); if (!result.results[0]) { return null; @@ -40,7 +40,7 @@ export class NotamService { } await this.dbSession.executeWrite( 'INSERT OR REPLACE INTO notams (id, content, type, updated_by, updated_at) VALUES (?, ?, ?, ?, datetime("now"))', - ['global', content, type, userId] + ['global', content, type, userId], ); return true; } catch (error) { diff --git a/src/services/points.ts b/src/services/points.ts index fb00106..eb35f61 100644 --- a/src/services/points.ts +++ b/src/services/points.ts @@ -13,10 +13,12 @@ export class PointsService { id: string; airportId: string; }>; - private stmtInsert: PreparedStatement<{ - coordinates: string; - createdAt: string; - } & Omit>; + private stmtInsert: PreparedStatement< + { + coordinates: string; + createdAt: string; + } & Omit + >; private stmtUpdate: PreparedStatement<{ id: string; airportId: string; @@ -49,7 +51,7 @@ export class PointsService { type, name, coordinates, directionality, orientation, color, elevated, ihp FROM points WHERE id = ? AND airport_id = ?;`, - ['id', 'airportId'] + ['id', 'airportId'], ); this.stmtInsert = this.dbSession.prepare( `INSERT @@ -59,10 +61,20 @@ export class PointsService { ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, [ - 'id', 'airportId', 'type', 'name', 'coordinates', 'directionality', - 'orientation', 'color', 'elevated', 'ihp', 'createdAt', 'createdAt', - 'createdBy' - ] + 'id', + 'airportId', + 'type', + 'name', + 'coordinates', + 'directionality', + 'orientation', + 'color', + 'elevated', + 'ihp', + 'createdAt', + 'createdAt', + 'createdBy', + ], ); this.stmtUpdate = this.dbSession.prepare( `UPDATE points @@ -77,22 +89,12 @@ export class PointsService { ihp = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND airport_id = ?;`, - [ - 'type', 'name', 'coordinates', 'directionality', 'orientation', 'color', - 'elevated', 'ihp', 'id', 'airportId' - ] - ); - this.stmtDelete = this.dbSession.prepare( - 'DELETE FROM points WHERE id = ? AND airport_id = ?;', - ['id', 'airportId'] + ['type', 'name', 'coordinates', 'directionality', 'orientation', 'color', 'elevated', 'ihp', 'id', 'airportId'], ); + this.stmtDelete = this.dbSession.prepare('DELETE FROM points WHERE id = ? AND airport_id = ?;', ['id', 'airportId']); } - async createPoint( - airportId: string, - userId: string, - point: PointData, - ): Promise { + async createPoint(airportId: string, userId: string, point: PointData): Promise { // Check if user has permission for this airport const hasDivisionAccess = await this.divisions.userHasAirportAccess(userId, airportId); if (!hasDivisionAccess) { @@ -137,17 +139,15 @@ export class PointsService { newPoint.createdAt, newPoint.updatedAt, newPoint.createdBy, - ] + ], ); - try { this.posthog?.track('Point Created', { airportId, userId, type: point.type }); } catch { } + try { + this.posthog?.track('Point Created', { airportId, userId, type: point.type }); + } catch {} return newPoint; } - async updatePoint( - pointId: string, - userId: string, - updates: Partial, - ): Promise { + async updatePoint(pointId: string, userId: string, updates: Partial): Promise { // Get existing point const point = await this.getPoint(pointId); if (!point) { @@ -165,10 +165,7 @@ export class PointsService { this.validatePoint(mergedPoint); // Define allowed fields for updates - const allowedFields = [ - 'type', 'name', 'coordinates', 'directionality', - 'orientation', 'color', 'elevated', 'ihp' - ]; + const allowedFields = ['type', 'name', 'coordinates', 'directionality', 'orientation', 'color', 'elevated', 'ihp']; const processedUpdates: Record = {}; Object.entries(updates).forEach(([key, value]) => { if (allowedFields.includes(key)) { @@ -179,14 +176,14 @@ export class PointsService { return this.getPoint(pointId) as Promise; } const fieldMappings: Record = { - 'type': 'type', - 'name': 'name', - 'coordinates': 'coordinates', - 'directionality': 'directionality', - 'orientation': 'orientation', - 'color': 'color', - 'elevated': 'elevated', - 'ihp': 'ihp' + type: 'type', + name: 'name', + coordinates: 'coordinates', + directionality: 'directionality', + orientation: 'orientation', + color: 'color', + elevated: 'elevated', + ihp: 'ihp', }; const updateFields = Object.keys(processedUpdates) @@ -199,11 +196,18 @@ export class PointsService { SET ${updateFields}, updated_at = ? WHERE id = ? `, - [...Object.values(processedUpdates), new Date().toISOString(), pointId] + [...Object.values(processedUpdates), new Date().toISOString(), pointId], ); - const finalPoint = await this.getPoint(pointId) as Point; - try { this.posthog?.track('Point Updated', { pointId, airportId: finalPoint.airportId, userId, fields: Object.keys(processedUpdates) }); } catch { } + const finalPoint = (await this.getPoint(pointId)) as Point; + try { + this.posthog?.track('Point Updated', { + pointId, + airportId: finalPoint.airportId, + userId, + fields: Object.keys(processedUpdates), + }); + } catch {} return finalPoint; } @@ -221,25 +225,19 @@ export class PointsService { } // Delete from database - await this.dbSession.executeWrite( - 'DELETE FROM points WHERE id = ?', - [pointId] - ); - try { this.posthog?.track('Point Deleted', { pointId, airportId: point.airportId, userId }); } catch { } + await this.dbSession.executeWrite('DELETE FROM points WHERE id = ?', [pointId]); + try { + this.posthog?.track('Point Deleted', { pointId, airportId: point.airportId, userId }); + } catch {} } - async applyChangeset( - airportId: string, - userId: string, - changeset: PointChangeset - ): Promise { + async applyChangeset(airportId: string, userId: string, changeset: PointChangeset): Promise { const hasDivisionAccess = await this.divisions.userHasAirportAccess(userId, airportId); if (!hasDivisionAccess) { throw new Error('User does not have permission to apply this changeset'); } - const selects = Object.keys(changeset.modify ?? {}) - .map((id) => this.stmtSelect.bindAll({ id, airportId })); + const selects = Object.keys(changeset.modify ?? {}).map((id) => this.stmtSelect.bindAll({ id, airportId })); const modifiedPoints = (await this.dbSession.executeBatch(selects)) .map((result) => { if (!result.results || result.results.length === 0) { @@ -268,16 +266,17 @@ export class PointsService { createdAt: now, updatedAt: now, createdBy: userId, - })) + })), ); - const inserts = createdPoints - .map((point) => this.stmtInsert.bindAll({ + const inserts = createdPoints.map((point) => + this.stmtInsert.bindAll({ ...point, - coordinates: JSON.stringify(point.coordinates) - })); - const updates = modifiedPoints - .map((point) => this.stmtUpdate.bindAll({ + coordinates: JSON.stringify(point.coordinates), + }), + ); + const updates = modifiedPoints.map((point) => + this.stmtUpdate.bindAll({ id: point.id, airportId, type: point.type ?? null, @@ -288,30 +287,32 @@ export class PointsService { color: point.color ?? null, elevated: point.elevated ?? null, ihp: point.ihp ?? null, - })); - const deletes = (changeset.delete ?? []) - .map((id) => this.stmtDelete.bindAll({ id, airportId })); + }), + ); + const deletes = (changeset.delete ?? []).map((id) => this.stmtDelete.bindAll({ id, airportId })); await this.dbSession.executeBatch(inserts.concat(updates).concat(deletes)); - try { this.posthog?.track('Points Changeset Applied', { airportId, userId, created: createdPoints.length, modified: modifiedPoints.length, deleted: (changeset.delete ?? []).length }); } catch { } + try { + this.posthog?.track('Points Changeset Applied', { + airportId, + userId, + created: createdPoints.length, + modified: modifiedPoints.length, + deleted: (changeset.delete ?? []).length, + }); + } catch {} return createdPoints; } async getPoint(pointId: string): Promise { - const result = await this.dbSession.executeRead( - 'SELECT * FROM points WHERE id = ?', - [pointId] - ); + const result = await this.dbSession.executeRead('SELECT * FROM points WHERE id = ?', [pointId]); if (!result.results[0]) return null; return this.mapPointFromDb(result.results[0]); } async getAirportPoints(airportId: string): Promise { - const results = await this.dbSession.executeRead( - 'SELECT * FROM points WHERE airport_id = ?', - [airportId] - ); + const results = await this.dbSession.executeRead('SELECT * FROM points WHERE airport_id = ?', [airportId]); return results.results.map(this.mapPointFromDb); } diff --git a/src/services/polygons.ts b/src/services/polygons.ts index 4ac869e..10b2152 100644 --- a/src/services/polygons.ts +++ b/src/services/polygons.ts @@ -69,7 +69,7 @@ export class PolygonService { FROM points WHERE id = ? `, - [barsId] + [barsId], ); if (!result.results[0]) { return null; @@ -175,6 +175,7 @@ export class PolygonService { // Add each object for (const obj of processedObjects) { + // stateId moved to per-light level (previously on BarsObject) xml += `\t\n`; // Add properties @@ -192,7 +193,13 @@ export class PolygonService { // Add light points for (const point of obj.points) { - xml += '\t\t\n'; + // Determine per-light orientation & color (point overrides object) + const lightOrientation: 'left' | 'right' | 'both' = + (point.properties?.orientation as any) || (obj.properties.orientation as any) || 'both'; + const lightColor = (point.properties?.color || obj.properties.color || '').toLowerCase(); + const lightStateId = this.mapLightStateId(lightOrientation, lightColor); + const lightStateAttr = lightStateId !== undefined ? ` stateId="${lightStateId}"` : ''; + xml += `\t\t\n`; xml += `\t\t\t${point.lat},${point.lon}\n`; xml += `\t\t\t${point.heading.toFixed(2)}\n`; @@ -202,35 +209,30 @@ export class PolygonService { const needsPropertiesTag = this.lightsNeedsPropertiesTag(point, props, obj.type); if (needsPropertiesTag) { - xml += '\t\t\t\n'; - - // Include color if it differs from the object-level defaults + let lightPropsContent = ''; if (point.properties.color && point.properties.color !== props.color) { - xml += `\t\t\t\t${point.properties.color}\n`; + lightPropsContent += `\t\t\t\t${point.properties.color}\n`; } - if (point.properties.ihp === true && obj.type === 'stopbar' && point.properties.color === 'yellow') { - xml += `\t\t\t\t${point.properties.ihp}\n`; + lightPropsContent += `\t\t\t\t${point.properties.ihp}\n`; } - - // Only include elevated property when it's explicitly true if (point.properties.elevated === true) { - xml += `\t\t\t\ttrue\n`; + lightPropsContent += `\t\t\t\ttrue\n`; } - - // For orientation, only output for stopbar type if ( point.properties.orientation && obj.type === 'stopbar' && - // Don't include "both" for elevated stopbar lights !(point.properties.elevated === true && point.properties.orientation === 'both') && - // Only include if it differs from the object's orientation point.properties.orientation !== props.orientation ) { - xml += `\t\t\t\t${point.properties.orientation}\n`; + lightPropsContent += `\t\t\t\t${point.properties.orientation}\n`; } - xml += '\t\t\t\n'; + if (lightPropsContent.length > 0) { + xml += '\t\t\t\n'; + xml += lightPropsContent; + xml += '\t\t\t\n'; + } } } @@ -246,6 +248,65 @@ export class PolygonService { return xml; } + /** + * Map a processed BARS object to a light stateId used by pilot client. + * Mapping provided: + * Uni (orientation !== 'both'): + * red=1, green=2, yellow=3, blue=4, orange=5 + * Bi (orientation === 'both') same color both dirs: + * red=20, green=21, yellow=22, blue=23, orange=24 + * Bi mixed (Dir2 green, Dir1 other): + * green-yellow=25, green-blue=26, green-orange=27 + */ + private mapLightStateId(orientation: 'left' | 'right' | 'both', rawColor: string): number | undefined { + if (!rawColor) return undefined; + // Normalize color string(s) + const color = rawColor.toLowerCase(); + // For mapping, strip trailing -uni markers on entire string and on segments + const normalized = color + .split('-') + .map((seg) => seg.replace(/uni$/i, '')) + .join('-') + .replace(/--+/g, '-'); + + if (orientation === 'both') { + // Mixed combos first (order-insensitive) + if (/(green-yellow|yellow-green)/.test(normalized)) return 25; + if (/(green-blue|blue-green)/.test(normalized)) return 26; + if (/(green-orange|orange-green)/.test(normalized)) return 27; + // Same color both directions + switch (normalized) { + case 'red': + return 20; + case 'green': + return 21; + case 'yellow': + return 22; + case 'blue': + return 23; + case 'orange': + return 24; + } + return undefined; + } + + // Uni-directional: take first segment (after normalization) + const base = normalized.split('-')[0]; + switch (base) { + case 'red': + return 1; + case 'green': + return 2; + case 'yellow': + return 3; + case 'blue': + return 4; + case 'orange': + return 5; + default: + return undefined; + } + } /** * Helper method to determine if a light needs properties in its XML output */ @@ -392,8 +453,6 @@ export class PolygonService { xml += ''; - // Stats tracking removed - return xml; } } diff --git a/src/services/posthog.ts b/src/services/posthog.ts index fe1dca5..323d893 100644 --- a/src/services/posthog.ts +++ b/src/services/posthog.ts @@ -5,125 +5,144 @@ import { waitUntil as cfWaitUntil } from 'cloudflare:workers'; interface PostHogCapturePayload { - api_key: string; - event: string; - properties: Record; - timestamp?: string; // ISO 8601 - $process_person_profile?: boolean; + api_key: string; + event: string; + properties: Record; + timestamp?: string; // ISO 8601 + $process_person_profile?: boolean; } export interface TrackOptions { - timestamp?: Date | string; - product?: string; - omitProduct?: boolean; - inline?: boolean; // if true, don't background + timestamp?: Date | string; + product?: string; + omitProduct?: boolean; + inline?: boolean; // if true, don't background } export class PostHogService { - private readonly apiKey: string | undefined; - private readonly host: string; - private readonly enabled: boolean; - private readonly piiKeyMatchers: Array<(k: string) => boolean> = [ - (k) => k === 'userId', - (k) => k === 'vatsimId', - (k) => k === 'requestedBy', - (k) => k === 'approvedBy', - (k) => k === 'decidedBy', - (k) => k === 'createdBy', - (k) => k === 'email', - (k) => k === 'cid', - (k) => k === 'callsign', - (k) => k.includes('vatsim'), - ]; + private readonly apiKey: string | undefined; + private readonly host: string; + private readonly enabled: boolean; + private readonly piiKeyMatchers: Array<(k: string) => boolean> = [ + (k) => k === 'userId', + (k) => k === 'vatsimId', + (k) => k === 'requestedBy', + (k) => k === 'approvedBy', + (k) => k === 'decidedBy', + (k) => k === 'createdBy', + (k) => k === 'email', + (k) => k === 'cid', + (k) => k === 'callsign', + (k) => k.includes('vatsim'), + ]; - constructor(env: Env) { - this.apiKey = (env as any).POSTHOG_API_KEY - this.host = (env as any).POSTHOG_HOST || 'https://eu.i.posthog.com'; - this.enabled = !!this.apiKey; - } + constructor(env: Env) { + this.apiKey = (env as any).POSTHOG_API_KEY; + this.host = (env as any).POSTHOG_HOST || 'https://eu.i.posthog.com'; + this.enabled = !!this.apiKey; + } - private isPIIKey(key: string): boolean { - const lk = key.toLowerCase(); - return this.piiKeyMatchers.some(fn => fn(lk)); - } + private isPIIKey(key: string): boolean { + const lk = key.toLowerCase(); + return this.piiKeyMatchers.some((fn) => fn(lk)); + } - private async hashValue(value: unknown): Promise { - try { - const encoder = new TextEncoder(); - const data = encoder.encode(String(value)); - const digest = await crypto.subtle.digest('SHA-256', data); - return Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join(''); - } catch { - // Fallback simple hash (non-crypto) if subtle fails - const s = String(value); - let h = 0; for (let i = 0; i < s.length; i++) { h = (h * 31 + s.charCodeAt(i)) >>> 0; } - return h.toString(16); - } - } + private async hashValue(value: unknown): Promise { + try { + const encoder = new TextEncoder(); + const data = encoder.encode(String(value)); + const digest = await crypto.subtle.digest('SHA-256', data); + return Array.from(new Uint8Array(digest)) + .map((b) => b.toString(16).padStart(2, '0')) + .join(''); + } catch { + // Fallback simple hash (non-crypto) if subtle fails + const s = String(value); + let h = 0; + for (let i = 0; i < s.length; i++) { + h = (h * 31 + s.charCodeAt(i)) >>> 0; + } + return h.toString(16); + } + } - private async sanitizeProperties(props: Record): Promise> { - const entries = await Promise.all(Object.entries(props).map(async ([k, v]) => { - if (v == null) return [k, v]; - if (this.isPIIKey(k)) { - return [k, await this.hashValue(v)]; - } - return [k, v]; - })); - return Object.fromEntries(entries); - } + private async sanitizeProperties(props: Record): Promise> { + const entries = await Promise.all( + Object.entries(props).map(async ([k, v]) => { + if (v == null) return [k, v]; + if (this.isPIIKey(k)) { + return [k, await this.hashValue(v)]; + } + return [k, v]; + }), + ); + return Object.fromEntries(entries); + } - track(event: string, properties: Record = {}, distinctId = 'anonymous', options: TrackOptions = {}): void | Promise { - if (!this.enabled) return; - const mergedProps: Record = { - ...properties, - }; - if (!options.omitProduct) { - if (mergedProps.product === undefined) mergedProps.product = options.product || 'Core'; - } - try { - const approxSize = JSON.stringify(mergedProps).length; - if (approxSize > 45_000) { - mergedProps._truncated = true; - } - } catch { /* ignore */ } - const buildBody = async () => { - const sanitized = await this.sanitizeProperties(mergedProps); - const payload: PostHogCapturePayload = { - api_key: this.apiKey!, - event, - properties: { - distinct_id: distinctId, - ...sanitized, - }, - $process_person_profile: false, - }; - if (options.timestamp) { - payload.timestamp = typeof options.timestamp === 'string' ? options.timestamp : options.timestamp.toISOString(); - } - return JSON.stringify(payload); - }; + track(event: string, properties: Record = {}, distinctId = 'anonymous', options: TrackOptions = {}): void | Promise { + if (!this.enabled) return; + const mergedProps: Record = { + ...properties, + }; + if (!options.omitProduct) { + if (mergedProps.product === undefined) mergedProps.product = options.product || 'Core'; + } + try { + const approxSize = JSON.stringify(mergedProps).length; + if (approxSize > 45_000) { + mergedProps._truncated = true; + } + } catch { + /* ignore */ + } + const buildBody = async () => { + const sanitized = await this.sanitizeProperties(mergedProps); + const payload: PostHogCapturePayload = { + api_key: this.apiKey!, + event, + properties: { + distinct_id: distinctId, + ...sanitized, + }, + $process_person_profile: false, + }; + if (options.timestamp) { + payload.timestamp = typeof options.timestamp === 'string' ? options.timestamp : options.timestamp.toISOString(); + } + return JSON.stringify(payload); + }; - const doFetch = () => buildBody().then(body => fetch(`${this.host.replace(/\/$/, '')}/capture/`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body, - })).then(res => { - if (!res.ok) { - console.warn('[PostHog] Non-OK response', res.status); - } - }).catch(err => { - console.warn('[PostHog] Track failed', err instanceof Error ? err.message : err); - }); - if (options.inline) return doFetch(); - try { - if (typeof cfWaitUntil === 'function') { - cfWaitUntil(doFetch()); - return; - } - } catch { /* ignore */ } - try { - (globalThis as any).waitUntil?.(doFetch()); - } catch { /* ignore */ } - return; - } + const doFetch = () => + buildBody() + .then((body) => + fetch(`${this.host.replace(/\/$/, '')}/capture/`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body, + }), + ) + .then((res) => { + if (!res.ok) { + console.warn('[PostHog] Non-OK response', res.status); + } + }) + .catch((err) => { + console.warn('[PostHog] Track failed', err instanceof Error ? err.message : err); + }); + if (options.inline) return doFetch(); + try { + if (typeof cfWaitUntil === 'function') { + cfWaitUntil(doFetch()); + return; + } + } catch { + /* ignore */ + } + try { + (globalThis as any).waitUntil?.(doFetch()); + } catch { + /* ignore */ + } + return; + } } diff --git a/src/services/roles.ts b/src/services/roles.ts index 034ca96..befe3ce 100644 --- a/src/services/roles.ts +++ b/src/services/roles.ts @@ -33,19 +33,13 @@ export class RoleService { } async isStaff(userId: number): Promise { - const staffResult = await this.dbSession.executeRead( - 'SELECT * FROM staff WHERE user_id = ?', - [userId] - ); + const staffResult = await this.dbSession.executeRead('SELECT * FROM staff WHERE user_id = ?', [userId]); const staff = staffResult.results[0]; return !!staff && !!staff.role && staff.role in roleHierarchy; } async getUserRole(userId: number): Promise { - const staffResult = await this.dbSession.executeRead( - 'SELECT * FROM staff WHERE user_id = ?', - [userId] - ); + const staffResult = await this.dbSession.executeRead('SELECT * FROM staff WHERE user_id = ?', [userId]); const staff = staffResult.results[0]; if (!staff?.role) return null; return staff.role as StaffRole; @@ -73,7 +67,7 @@ export class RoleService { JOIN users u ON u.vatsim_id = dm.vatsim_id WHERE u.id = ? `, - [userId] + [userId], ); return rolesResult.results.reduce( (acc, { role }) => ({ diff --git a/src/services/service-pool.ts b/src/services/service-pool.ts index 5bd031c..fdf091b 100644 --- a/src/services/service-pool.ts +++ b/src/services/service-pool.ts @@ -16,112 +16,118 @@ import { GitHubService } from './github'; import { PostHogService } from './posthog'; export const ServicePool = (() => { - let vatsim: VatsimService; - let auth: AuthService; - let roles: RoleService; - let cache: CacheService; - let airport: AirportService; - let divisions: DivisionService; - let id: IDService; - let points: PointsService; - let polygons: PolygonService; - let support: SupportService; - let notam: NotamService; - let contributions: ContributionService; - let storage: StorageService; - let github: GitHubService; - let posthog: PostHogService; + let vatsim: VatsimService; + let auth: AuthService; + let roles: RoleService; + let cache: CacheService; + let airport: AirportService; + let divisions: DivisionService; + let id: IDService; + let points: PointsService; + let polygons: PolygonService; + let support: SupportService; + let notam: NotamService; + let contributions: ContributionService; + let storage: StorageService; + let github: GitHubService; + let posthog: PostHogService; - return { - getVatsim(env: Env) { - if (!vatsim) { - vatsim = new VatsimService(env.VATSIM_CLIENT_ID, env.VATSIM_CLIENT_SECRET); - } - return vatsim; - }, - getAuth(env: Env) { - if (!auth) { - auth = new AuthService(env.DB, this.getVatsim(env), this.getPostHog(env)); - } - return auth; - }, - getRoles(env: Env) { - if (!roles) { - roles = new RoleService(env.DB); - } - return roles; - }, - getCache(env: Env) { - if (!cache) { - cache = new CacheService(env); - } - return cache; - }, - getAirport(env: Env) { - if (!airport) { - airport = new AirportService(env.DB, env.AIRPORTDB_API_KEY, this.getPostHog(env)); - } - return airport; - }, - getDivisions(env: Env) { - if (!divisions) { - divisions = new DivisionService(env.DB, this.getPostHog(env)); - } - return divisions; - }, - getID(env: Env) { - if (!id) { - id = new IDService(env.DB); - } - return id; - }, - getPoints(env: Env) { - if (!points) { - points = new PointsService(env.DB, this.getID(env), this.getDivisions(env), this.getAuth(env), this.getPostHog(env)); - } - return points; - }, - getPolygons(env: Env) { - if (!polygons) { - polygons = new PolygonService(env.DB); - } - return polygons; - }, - getSupport(env: Env) { - if (!support) { - support = new SupportService(env.DB); - } - return support; - }, - getNotam(env: Env) { - if (!notam) { - notam = new NotamService(env.DB); - } - return notam; - }, - getContributions(env: Env) { - if (!contributions) { - contributions = new ContributionService(env.DB, this.getRoles(env), env.AIRPORTDB_API_KEY, env.BARS_STORAGE, this.getPostHog(env)); - } - return contributions; - }, - getStorage(env: Env) { - if (!storage) { - storage = new StorageService(env.BARS_STORAGE); - } - return storage; - }, - getGitHub(env: Env) { - if (!github) { - github = new GitHubService(); - } - return github; - }, - getPostHog(env: Env) { - if (!posthog) { - posthog = new PostHogService(env); - } - return posthog; - } - }; + return { + getVatsim(env: Env) { + if (!vatsim) { + vatsim = new VatsimService(env.VATSIM_CLIENT_ID, env.VATSIM_CLIENT_SECRET); + } + return vatsim; + }, + getAuth(env: Env) { + if (!auth) { + auth = new AuthService(env.DB, this.getVatsim(env), this.getPostHog(env)); + } + return auth; + }, + getRoles(env: Env) { + if (!roles) { + roles = new RoleService(env.DB); + } + return roles; + }, + getCache(env: Env) { + if (!cache) { + cache = new CacheService(env); + } + return cache; + }, + getAirport(env: Env) { + if (!airport) { + airport = new AirportService(env.DB, env.AIRPORTDB_API_KEY, this.getPostHog(env)); + } + return airport; + }, + getDivisions(env: Env) { + if (!divisions) { + divisions = new DivisionService(env.DB, this.getPostHog(env)); + } + return divisions; + }, + getID(env: Env) { + if (!id) { + id = new IDService(env.DB); + } + return id; + }, + getPoints(env: Env) { + if (!points) { + points = new PointsService(env.DB, this.getID(env), this.getDivisions(env), this.getAuth(env), this.getPostHog(env)); + } + return points; + }, + getPolygons(env: Env) { + if (!polygons) { + polygons = new PolygonService(env.DB); + } + return polygons; + }, + getSupport(env: Env) { + if (!support) { + support = new SupportService(env.DB); + } + return support; + }, + getNotam(env: Env) { + if (!notam) { + notam = new NotamService(env.DB); + } + return notam; + }, + getContributions(env: Env) { + if (!contributions) { + contributions = new ContributionService( + env.DB, + this.getRoles(env), + env.AIRPORTDB_API_KEY, + env.BARS_STORAGE, + this.getPostHog(env), + ); + } + return contributions; + }, + getStorage(env: Env) { + if (!storage) { + storage = new StorageService(env.BARS_STORAGE); + } + return storage; + }, + getGitHub(env: Env) { + if (!github) { + github = new GitHubService(); + } + return github; + }, + getPostHog(env: Env) { + if (!posthog) { + posthog = new PostHogService(env); + } + return posthog; + }, + }; })(); diff --git a/src/services/support.ts b/src/services/support.ts index ee2c837..a527aea 100644 --- a/src/services/support.ts +++ b/src/services/support.ts @@ -136,7 +136,7 @@ export class SupportService { public lat: number, public lon: number, public used: boolean = false, - ) { } + ) {} } const bounds = getBounds(); diff --git a/src/services/users.ts b/src/services/users.ts index 87e6822..5b1ef74 100644 --- a/src/services/users.ts +++ b/src/services/users.ts @@ -38,11 +38,9 @@ export class UserService { ORDER BY u.created_at DESC LIMIT ? OFFSET ? `, - [limit, offset] - ), - this.dbSession.executeRead<{ count: number }>( - 'SELECT COUNT(*) as count FROM users' + [limit, offset], ), + this.dbSession.executeRead<{ count: number }>('SELECT COUNT(*) as count FROM users'), ]); if (!usersResult || !countResult) { throw new Error('Failed to fetch users'); @@ -76,7 +74,7 @@ export class UserService { ORDER BY u.created_at DESC LIMIT 50 `, - [`%${query}%`, `%${query}%`] + [`%${query}%`, `%${query}%`], ); if (!result) { throw new Error('Failed to search users'); @@ -97,10 +95,9 @@ export class UserService { try { // Get the user to delete - const userToDeleteResult = await this.dbSession.executeRead<{ vatsim_id: string }>( - 'SELECT vatsim_id FROM users WHERE id = ?', - [userId] - ); + const userToDeleteResult = await this.dbSession.executeRead<{ vatsim_id: string }>('SELECT vatsim_id FROM users WHERE id = ?', [ + userId, + ]); const userToDelete = userToDeleteResult.results[0]; if (!userToDelete) { throw new Error('User not found'); @@ -110,7 +107,9 @@ export class UserService { if (!deleted) { throw new Error('Failed to delete user'); } - try { this.posthog?.track('Admin Deleted User', { userId, requestingUserId }); } catch { } + try { + this.posthog?.track('Admin Deleted User', { userId, requestingUserId }); + } catch {} return true; } catch (error) { throw new Error('Failed to delete user'); @@ -127,17 +126,16 @@ export class UserService { try { // Get the user by VATSIM ID - const userResult = await this.dbSession.executeRead<{ id: number }>( - 'SELECT id FROM users WHERE vatsim_id = ?', - [vatsimId] - ); + const userResult = await this.dbSession.executeRead<{ id: number }>('SELECT id FROM users WHERE vatsim_id = ?', [vatsimId]); const user = userResult.results[0]; if (!user) { throw new Error('User not found'); } // Use the auth service to regenerate the API key const newApiKey = await this.auth.regenerateApiKey(user.id); - try { this.posthog?.track('Admin Regenerated User API Key', { vatsimId, requestingUserId }); } catch { } + try { + this.posthog?.track('Admin Regenerated User API Key', { vatsimId, requestingUserId }); + } catch {} return newApiKey; } catch (error) { console.error('Error refreshing user API token:', error); diff --git a/src/services/vatsim.ts b/src/services/vatsim.ts index afa02dd..f200e05 100644 --- a/src/services/vatsim.ts +++ b/src/services/vatsim.ts @@ -4,7 +4,7 @@ export class VatsimService { constructor( private clientId: string, private clientSecret: string, - ) { } + ) {} async getToken(code: string): Promise { const res = await fetch('https://auth.vatsim.net/oauth/token', { diff --git a/src/types.ts b/src/types.ts index aaeca31..4e6d081 100644 --- a/src/types.ts +++ b/src/types.ts @@ -33,7 +33,6 @@ export interface VatsimUserResponse { }; } - import { Role } from './services/roles'; export interface StaffResponse { @@ -92,16 +91,17 @@ export interface AirportState { export interface Packet { type: - | 'STATE_UPDATE' - | 'INITIAL_STATE' - | 'CONTROLLER_CONNECT' - | 'CONTROLLER_DISCONNECT' - | 'SHARED_STATE_UPDATE' - | 'ERROR' - | 'HEARTBEAT' - | 'HEARTBEAT_ACK' - | 'CLOSE'; - airport?: string; data?: { + | 'STATE_UPDATE' + | 'INITIAL_STATE' + | 'CONTROLLER_CONNECT' + | 'CONTROLLER_DISCONNECT' + | 'SHARED_STATE_UPDATE' + | 'ERROR' + | 'HEARTBEAT' + | 'HEARTBEAT_ACK' + | 'CLOSE'; + airport?: string; + data?: { objectId?: string; state?: boolean; patch?: Record; // New field for patch-based updates @@ -147,7 +147,7 @@ export type PointData = Omit>; // Keyed by ID delete?: string[]; // IDs }; diff --git a/worker-configuration.d.ts b/worker-configuration.d.ts index 9da729e..69ccb50 100644 --- a/worker-configuration.d.ts +++ b/worker-configuration.d.ts @@ -3,11 +3,11 @@ // Runtime types generated with workerd@1.20250803.0 2024-12-18 nodejs_compat declare namespace Cloudflare { interface Env { - VATSIM_CLIENT_ID: "1562"; - POSTHOG_HOST: "https://eu.i.posthog.com"; + VATSIM_CLIENT_ID: '1562'; + POSTHOG_HOST: 'https://eu.i.posthog.com'; VATSIM_CLIENT_SECRET: string; AIRPORTDB_API_KEY: string; - BARS: DurableObjectNamespace; + BARS: DurableObjectNamespace; BARS_STORAGE: R2Bucket; DB: D1Database; } @@ -38,165 +38,176 @@ declare var onmessage: never; * [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); + 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; + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; }; declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof 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; + '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; +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; + 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. @@ -205,86 +216,94 @@ declare namespace WebAssembly { * [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; + 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. * @@ -317,207 +336,228 @@ declare function reportError(error: any): void; 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/) -*/ + * 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/) -*/ + * 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/) -*/ + * 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 TestController {} interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - props: any; -} -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; + 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 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; + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; } interface StructuredSerializeOptions { - transfer?: any[]; + 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; + /* [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; + sendBeacon( + url: string, + body?: ReadableStream | string | (ArrayBuffer | ArrayBufferView) | Blob | FormData | URLSearchParams | URLSearchParams, + ): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; } /** -* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, -* as well as timing of subrequests and other operations. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) -*/ + * 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; + /* [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; + readonly isRetry: boolean; + readonly retryCount: number; } interface Cloudflare { - readonly compatibilityFlags: Record; + 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; + 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< + T, + 'alarm' | 'webSocketMessage' | 'webSocketClose' | 'webSocketError' +> & { + readonly id: DurableObjectId; + readonly name?: string; }; interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; + 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; + 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"; +type DurableObjectJurisdiction = 'eu' | 'fedramp' | 'fedramp-high'; interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; + jurisdiction?: DurableObjectJurisdiction; } -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; +type DurableObjectLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'oc' | 'afr' | 'me'; interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; + 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; + 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; + 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; + 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; + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; + allowConcurrency?: boolean; } interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; } interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; } declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; + constructor(request: string, response: string); + get request(): string; + get response(): string; } interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; + writeDataPoint(event?: AnalyticsEngineDataPoint): void; } interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; } /** * An event which takes place in the DOM. @@ -525,128 +565,128 @@ interface AnalyticsEngineDataPoint { * [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; + 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; + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; } type EventListener = (event: EventType) => void; interface EventListenerObject { - handleEvent(event: EventType): void; + handleEvent(event: EventType): void; } type EventListenerOrEventListenerObject = EventListener | EventListenerObject; /** @@ -655,49 +695,57 @@ type EventListenerOrEventListenerObject = Event * [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; + 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; + capture?: boolean; } interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; } interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; + handleEvent: (event: Event) => any | undefined; } /** * A controller object that allows you to abort one or more DOM requests as and when desired. @@ -705,19 +753,19 @@ interface EventTargetHandlerObject { * [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; + 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. @@ -725,32 +773,32 @@ declare class AbortController { * [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; + /* [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; + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; } interface SchedulerWaitOptions { - signal?: AbortSignal; + 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. @@ -758,24 +806,24 @@ interface SchedulerWaitOptions { * [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/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; + 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; + 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. @@ -783,24 +831,24 @@ interface CustomEventCustomEventInit { * [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; + 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; + type?: string; } /** * Provides information about files and allows JavaScript in a web page to access their content. @@ -808,66 +856,68 @@ interface BlobOptions { * [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; + 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; + 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/) -*/ + * 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; + /* [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/) -*/ + * 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; + /* [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; + 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/) -*/ + * 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; + /** + * 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< + T extends Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array, + >(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). @@ -876,31 +926,73 @@ declare abstract class Crypto { * [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; + /* [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. @@ -909,117 +1001,123 @@ declare abstract class SubtleCrypto { * [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[]; + /* [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; + 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; + 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; + r?: string; + d?: string; + t?: string; } interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: (ArrayBuffer | ArrayBufferView); - iterations?: number; - hash?: (string | SubtleCryptoHashAlgorithm); - $public?: CryptoKey; - info?: (ArrayBuffer | ArrayBufferView); + 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); + 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; + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + modulusLength?: number; + publicExponent?: ArrayBuffer | ArrayBufferView; + length?: number; + namedCurve?: string; } interface SubtleCryptoHashAlgorithm { - name: string; + name: string; } interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - length?: number; - namedCurve?: string; - compressed?: boolean; + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + length?: number; + namedCurve?: string; + compressed?: boolean; } interface SubtleCryptoSignAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - dataLength?: number; - saltLength?: number; + name: string; + hash?: string | SubtleCryptoHashAlgorithm; + dataLength?: number; + saltLength?: number; } interface CryptoKeyKeyAlgorithm { - name: string; + name: string; } interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; + name: string; + length: number; } interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; } interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; } interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; + name: string; + namedCurve: string; } interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; } declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; + 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. @@ -1027,26 +1125,26 @@ declare class DigestStream extends WritableStream * [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; + 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. @@ -1054,31 +1152,31 @@ declare class TextDecoder { * [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; + 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; + fatal: boolean; + ignoreBOM: boolean; } interface TextDecoderDecodeOptions { - stream: boolean; + stream: boolean; } interface TextEncoderEncodeIntoResult { - read: number; - written: number; + read: number; + written: number; } /** * Events providing information related to errors in scripts or in files. @@ -1086,24 +1184,24 @@ interface TextEncoderEncodeIntoResult { * [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; + 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; + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; } /** * A message received by a target object. @@ -1111,40 +1209,40 @@ interface ErrorEventErrorEventInit { * [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: any; - /** - * Returns the origin of the message, for server-sent events and cross-document messaging. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) - */ - readonly origin: string | null; - /** - * Returns the last event ID string, for server-sent events. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) - */ - readonly lastEventId: string; - /** - * Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null; - /** - * Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) - */ - readonly ports: MessagePort[]; + constructor(type: string, initializer: MessageEventInit); + /** + * Returns the data of the message. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: any; + /** + * Returns the origin of the message, for server-sent events and cross-document messaging. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null; + /** + * Returns the last event ID string, for server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string; + /** + * Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null; + /** + * Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[]; } interface MessageEventInit { - data: ArrayBuffer | string; + data: ArrayBuffer | string; } /** * 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". @@ -1152,107 +1250,101 @@ interface MessageEventInit { * [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 - ]>; + 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; + 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; + html?: boolean; } declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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. @@ -1260,11 +1352,11 @@ interface DocumentEnd { * [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; + /* [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; /** @@ -1273,53 +1365,47 @@ type HeadersInit = Headers | Iterable> | Record * [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 - ]>; + 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; + /* [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. @@ -1327,11 +1413,11 @@ declare abstract class Body { * [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; + 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. @@ -1339,32 +1425,32 @@ declare var Response: { * [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"; + /* [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"; + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: WebSocket | null; + encodeBody?: 'automatic' | 'manual'; } type RequestInfo> = Request | string; /** @@ -1373,8 +1459,11 @@ type RequestInfo> = * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ declare var Request: { - prototype: Request; - new >(input: RequestInfo | URL, init?: RequestInit): Request; + prototype: Request; + new >( + input: RequestInfo | URL, + init?: RequestInit, + ): Request; }; /** * This Fetch API interface represents a resource request. @@ -1382,428 +1471,497 @@ declare var 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"; + /* [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 Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; -type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; + /* 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< + T extends + | (new (...args: any[]) => Rpc.WorkerEntrypointBranded) + | Rpc.WorkerEntrypointBranded + | ExportedHandler + | undefined = undefined, +> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded + ? Fetcher> + : T extends Rpc.WorkerEntrypointBranded + ? Fetcher + : T extends Exclude + ? never + : Fetcher; +type Fetcher = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; }; interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; -} | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; -}; + 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; + 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); + limit?: number; + prefix?: string | null; + cursor?: string | null; } interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; + type: Type; + cacheTtl?: number; } interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); + expiration?: number; + expirationTtl?: number; + metadata?: any | null; } interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; } -type QueueContentType = "text" | "bytes" | "json" | "v8"; +type QueueContentType = 'text' | 'bytes' | 'json' | 'v8'; interface Queue { - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; } interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueSendBatchOptions { - delaySeconds?: number; + delaySeconds?: number; } interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueRetryOptions { - delaySeconds?: number; + delaySeconds?: number; } interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; + 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; + 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; + 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; + 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")[]; + 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; + 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; + 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; + 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; + 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; -}; + 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; + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; } interface R2GetOptions { - onlyIf?: (R2Conditional | Headers); - range?: (R2Range | Headers); - ssecKey?: (ArrayBuffer | string); + 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); + 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); + 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; + 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; + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; } interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; } type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; -} & ({ - truncated: true; - cursor: string; -} | { - truncated: false; -}); + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ( + | { + truncated: true; + cursor: string; + } + | { + truncated: false; + } +); interface R2UploadPartOptions { - ssecKey?: (ArrayBuffer | string); + ssecKey?: ArrayBuffer | string; } declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface QueuingStrategy { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; + 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; + 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; + 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); + 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; + 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; -}; + /** + * 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; + /* [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. @@ -1811,75 +1969,75 @@ interface ReadableStream { * [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; + 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; + 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>; + 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; + 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"; + /** + * 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/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/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; + /* [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. @@ -1887,30 +2045,30 @@ declare abstract class ReadableByteStreamController { * [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/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; + /* [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; + /** + * 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. @@ -1918,15 +2076,15 @@ interface ReadableWritablePair { * [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; + 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. @@ -1934,65 +2092,65 @@ declare class WritableStream { * [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; + 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; + 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); + constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); } declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); } interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); + highWaterMark?: number | bigint; } interface ReadableStreamValuesOptions { - preventCancel?: boolean; + preventCancel?: boolean; } /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); + 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"); + 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; + 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; + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; + fatal?: boolean; + ignoreBOM?: boolean; } /** * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. @@ -2000,11 +2158,11 @@ interface TextDecoderStreamTextDecoderStreamInit { * [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; + 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. @@ -2012,123 +2170,137 @@ declare class ByteLengthQueuingStrategy implements QueuingStrategy number; + 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; + /** + * 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; + id?: string; + tag?: string; + message?: string; } declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; + 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; + 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 { + readonly scheduledTime: Date; } +interface TraceItemCustomEventInfo {} interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; + readonly scheduledTime: number; + readonly cron: string; } interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; + readonly queue: string; + readonly batchSize: number; } interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; } interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; } interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; + readonly scriptName: string | null; } interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoResponse { - readonly status: number; + readonly status: number; } interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; + readonly rpcMethod: string; } interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError; } interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; } interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; + readonly webSocketEventType: string; } interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; + readonly timestamp: number; + readonly level: string; + readonly message: any; } interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; } interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; + readonly timestamp: number; + readonly channel: string; + readonly message: any; } interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; + readonly cpuTime: number; + readonly wallTime: number; } interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; + fromTrace(item: TraceItem): TraceMetrics; } /** * The URL interface represents an object providing static methods used for creating object URLs. @@ -2136,165 +2308,159 @@ interface UnsafeTraceMetrics { * [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; + 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 - ]>; + 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; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; + 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; + 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; + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; } interface URLPatternComponentResult { - input: string; - groups: Record; + 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; + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; } interface URLPatternOptions { - ignoreCase?: boolean; + 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. @@ -2302,36 +2468,36 @@ interface URLPatternOptions { * [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; + 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; + code?: number; + reason?: string; + wasClean?: boolean; } type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; + 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. @@ -2339,16 +2505,16 @@ type WebSocketEventMap = { * [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; + 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. @@ -2356,163 +2522,164 @@ declare var WebSocket: { * [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; + 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; - }; + 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 { + 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; + 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; + 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); + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: number | bigint; } interface SocketAddress { - hostname: string; - port: number; + hostname: string; + port: number; } interface TlsOptions { - expectedServerHostname?: string; + expectedServerHostname?: string; } interface SocketInfo { - remoteAddress?: string; - localAddress?: string; + 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; + 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; + 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; + 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; + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; } /** * This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. @@ -2520,3051 +2687,3155 @@ interface ContainerStartupOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) */ interface MessagePort extends EventTarget { - /** - * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. - * - * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) - */ - postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; - /** - * Disconnects the port, so that it is no longer active. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) - */ - close(): void; - /** - * Begins dispatching messages received on the port. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) - */ - start(): void; - get onmessage(): any | null; - set onmessage(value: any | null); + /** + * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. + * + * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: any[] | MessagePortPostMessageOptions): void; + /** + * Disconnects the port, so that it is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void; + /** + * Begins dispatching messages received on the port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void; + get onmessage(): any | null; + set onmessage(value: any | null); } interface MessagePortPostMessageOptions { - transfer?: any[]; + transfer?: any[]; } type AiImageClassificationInput = { - image: number[]; + image: number[]; }; type AiImageClassificationOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; + 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[]; + 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; + description: string; }; declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; + 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[]; + 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; + description: string; }; declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } type AiObjectDetectionInput = { - image: number[]; + image: number[]; }; type AiObjectDetectionOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; } type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; + source: string; + sentences: string[]; }; type AiSentenceSimilarityOutput = number[]; declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; } type AiAutomaticSpeechRecognitionInput = { - audio: number[]; + audio: number[]; }; type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; }; declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; } type AiSummarizationInput = { - input_text: string; - max_length?: number; + input_text: string; + max_length?: number; }; type AiSummarizationOutput = { - summary: string; + summary: string; }; declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; } type AiTextClassificationInput = { - text: string; + text: string; }; type AiTextClassificationOutput = { - score?: number; - label?: string; + score?: number; + label?: string; }[]; declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; } type AiTextEmbeddingsInput = { - text: string | string[]; + text: string | string[]; }; type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; + shape: number[]; + data: number[][]; }; declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; } type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; + 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[]; - }; + 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: '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; + name: string; + code: string; }; type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; + 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[]; + 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; - }[]; + response?: string; + tool_calls?: { + name: string; + arguments: unknown; + }[]; }; declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; } type AiTextToSpeechInput = { - prompt: string; - lang?: string; -}; -type AiTextToSpeechOutput = Uint8Array | { - audio: string; + prompt: string; + lang?: string; }; +type AiTextToSpeechOutput = + | Uint8Array + | { + audio: string; + }; declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; + 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; + 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; + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; } type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; + text: string; + target_lang: string; + source_lang?: string; }; type AiTranslationOutput = { - translated_text?: string; + 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; + 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; + /** + * 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[]; -}; + 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; + /** + * 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; + 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; + 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; + 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; -}; + 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; + 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[]; -}; + 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; + /** + * 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; + 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; + /** + * 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; + 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)[]; -}; + 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; + /** + * 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; + 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; + /** + * 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; + 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; - }[]; + 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"; + 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"; + 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; + 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; + /** + * 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; + /** + * 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; + 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; + /** + * 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; + /** + * 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; - }[]; + /** + * 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; + 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; +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; + /** + * 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; + 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; + /** + * 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; + 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; + 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; - }; + /** + * 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; - }; + 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; + 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; - }[]; + /** + * 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; - }[]; + 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; + 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; + /** + * 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; + /** + * 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; - }[]; + /** + * 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; + 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; + /** + * 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; + /** + * 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; - }[]; + /** + * 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; + 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; + /** + * 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; + /** + * 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; - }[]; + /** + * 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; + 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; + /** + * 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; + /** + * 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; - }[]; + /** + * 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; + 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; + /** + * 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; + /** + * 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; - }; - }[]; + /** + * 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; + 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; + '@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; + /** + * 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; + 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; + 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; - }[]; + 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 { -} +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; + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + autorag(autoragId?: string): AutoRAG; + run( + model: Name, + inputs: InputOptions, + options?: Options, + ): Promise< + Options extends { + returnRawResponse: true; + } + ? Response + : InputOptions extends { + stream: true; + } + ? ReadableStream + : AiModelList[Name]['postProcessedOutputs'] + >; + 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'; + 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; + 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; + 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; + 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 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; + '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; + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; }; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { -} +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 { -} + 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; + key: string; + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + value: string | number | boolean; }; type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; + 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; + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + rewrite_query?: boolean; }; type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean; + stream?: boolean; }; type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; + 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; + 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; + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; }[]; type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string; + response: string; }; declare abstract class AutoRAG { - list(): Promise; - search(params: AutoRagSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; - aiSearch(params: AutoRagAiSearchRequest): Promise; + 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; + /** + * 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'; + x?: number; + y?: number; + mode?: 'remainder' | 'box-center'; } /** * In addition to the properties you can set in the RequestInit dict @@ -5576,746 +5847,1004 @@ interface BasicImageTransformationsGravityCoordinates { * 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; + 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; + /** + * 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"; + /** + * 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; + javascript?: boolean; + css?: boolean; + html?: boolean; } interface RequestInitCfPropertiesR2 { - /** - * Colo id of bucket that an object is stored in - */ - bucketColoId?: number; + /** + * 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; +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; + /** + * [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[]; + /** + * 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; + /** + * 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; - }; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** 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: ""; + 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"; +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 */ +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"; +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"; +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; - }; + 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; + success: true; + meta: D1Meta & Record; + error?: never; } type D1Result = D1Response & { - results: T[]; + 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"; + 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; + 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; + 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; + 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. @@ -6323,743 +6852,835 @@ declare abstract class D1PreparedStatement { // 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 { -} +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; + /** + * 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; + /** + * 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; + 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 }; + 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 }; } /** * Hello World binding to serve as an explanatory example. DO NOT USE */ interface HelloWorldBinding { - /** - * Retrieve the current stored value - */ - get(): Promise<{ - value: string; - ms?: number; - }>; - /** - * Set a new stored value - */ - set(value: string): Promise; + /** + * Retrieve the current stored value + */ + get(): Promise<{ + value: string; + ms?: number; + }>; + /** + * Set a new stored value + */ + set(value: string): Promise; } interface Hyperdrive { - /** - * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. - * - * Calling this method returns an 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; + /** + * 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 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; - }; - }; + 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; + opacity?: number; + repeat?: boolean | string; + top?: number; + left?: number; + bottom?: number; + right?: number; }; type ImageInputOptions = { - encoding?: 'base64'; + encoding?: 'base64'; }; type ImageOutputOptions = { - format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; - quality?: number; - background?: string; + 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, options?: ImageInputOptions): Promise; - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; + /** + * Get image metadata (type, width and height) + * @throws {@link ImagesError} with code 9412 if input is not an image + * @param stream The image bytes + */ + info(stream: ReadableStream, options?: ImageInputOptions): Promise; + /** + * Begin applying a series of transformations to an image + * @param stream The image bytes + * @returns A transform handle + */ + input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; } 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; + /** + * Apply transform next, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param transform + */ + transform(transform: ImageTransform): ImageTransformer; + /** + * Draw an image on this transformer, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param image The image (or transformer that will give the image) to draw + * @param options The options configuring how to draw the image + */ + draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; + /** + * Retrieve the image that results from applying the transforms to the + * provided input + * @param options Options that apply to the output e.g. output format + */ + output(options: ImageOutputOptions): Promise; } type ImageTransformationOutputOptions = { - encoding?: 'base64'; + encoding?: 'base64'; }; interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream; + /** + * The image as a response, ready to store in cache or return to users + */ + response(): Response; + /** + * The content type of the returned image + */ + contentType(): string; + /** + * The bytes of the response + */ + image(options?: ImageTransformationOutputOptions): ReadableStream; } interface ImagesError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; + 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; + 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 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; + 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; +type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = 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; - } +declare module 'cloudflare:pipelines' { + export abstract class PipelineTransformationEntrypoint< + Env = unknown, + I extends PipelineRecord = PipelineRecord, + O extends PipelineRecord = PipelineRecord, + > { + protected env: Env; + protected ctx: ExecutionContext; + constructor(ctx: ExecutionContext, env: Env); + /** + * run 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; + // 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; + // Key Identifier of the JWK + readonly kid: string; } interface RateLimitOptions { - key: string; + key: string; } interface RateLimitOutcome { - success: boolean; + 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; + /** + * 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 { + // 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 { + // 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; - }; + 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 { - } + interface Env {} } declare module 'cloudflare:node' { - export interface DefaultHandler { - 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 function httpServerHandler(options: { - port: number; - }, handlers?: Omit): DefaultHandler; + export interface DefaultHandler { + 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 function httpServerHandler( + options: { + port: number; + }, + handlers?: Omit, + ): DefaultHandler; } 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 function waitUntil(promise: Promise): void; - export const env: Cloudflare.Env; + 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 function waitUntil(promise: Promise): void; + 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; + /** + * 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 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?: object; - 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: object; - } - 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[]; - } - type EventType = Onset | Outcome | Hibernate | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Link | Attributes; - interface TailEvent { - readonly invocationId: string; - readonly spanId: string; - readonly timestamp: Date; - readonly sequence: number; - readonly event: Event; - } - type TailEventHandler = (event: TailEvent) => void | Promise; - type TailEventHandlerObject = { - outcome?: TailEventHandler; - hibernate?: TailEventHandler; - spanOpen?: TailEventHandler; - spanClose?: TailEventHandler; - diagnosticChannel?: TailEventHandler; - exception?: TailEventHandler; - log?: TailEventHandler; - return?: TailEventHandler; - link?: TailEventHandler; - attributes?: TailEventHandler; - }; - type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; + interface Header { + readonly name: string; + readonly value: string; + } + interface FetchEventInfo { + readonly type: 'fetch'; + readonly method: string; + readonly url: string; + readonly cfJson?: object; + readonly headers: Header[]; + } + interface JsRpcEventInfo { + readonly type: 'jsrpc'; + 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: object; + } + 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[]; + } + type EventType = + | Onset + | Outcome + | Hibernate + | SpanOpen + | SpanClose + | DiagnosticChannelEvent + | Exception + | Log + | Return + | Link + | Attributes; + interface TailEvent { + readonly invocationId: string; + readonly spanId: string; + readonly timestamp: Date; + readonly sequence: number; + readonly event: Event; + } + type TailEventHandler = (event: TailEvent) => void | Promise; + type TailEventHandlerObject = { + outcome?: TailEventHandler; + hibernate?: TailEventHandler; + spanOpen?: TailEventHandler; + spanClose?: TailEventHandler; + diagnosticChannel?: TailEventHandler; + exception?: TailEventHandler; + log?: TailEventHandler; + return?: TailEventHandler; + link?: TailEventHandler; + attributes?: TailEventHandler; + }; + type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: @@ -7074,28 +7695,31 @@ type VectorizeVectorMetadataValue = string | number | boolean | string[]; type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; type VectorFloatArray = Float32Array | Float64Array; interface VectorizeError { - code?: number; - error: string; + 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"; +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; - }; + [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"; +type VectorizeDistanceMetric = 'euclidean' | 'cosine' | 'dot-product'; /** * Metadata return levels for a Vectorize query. * @@ -7105,23 +7729,25 @@ type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; * @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"; +type VectorizeMetadataRetrievalLevel = 'all' | 'indexed' | 'none'; interface VectorizeQueryOptions { - topK?: number; - namespace?: string; - returnValues?: boolean; - returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; - filter?: VectorizeVectorMetadataFilter; + 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 -}; +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. * @@ -7129,56 +7755,57 @@ type VectorizeIndexConfig = { * 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; + /** 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; + /** 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; + /** 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; -}; +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; + matches: VectorizeMatch[]; + count: number; } /** * Results of an operation that performed a mutation on a set of vectors. @@ -7188,18 +7815,18 @@ interface VectorizeMatches { * 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; + /* 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; + /** The unique identifier for the async mutation operation containing the changeset. */ + mutationId: string; } /** * A Vectorize Vector Search Index for querying vectors/embeddings. @@ -7208,42 +7835,42 @@ interface VectorizeAsyncMutation { * 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; + /** + * 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. @@ -7251,187 +7878,193 @@ declare abstract class VectorizeIndex { * 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; + /** + * 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; + /** 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; + /** + * 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; - }; + /** + * 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; + /** + * @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); - } + /** + * 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; + /** + * 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; - }; + /** + * 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; + 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; + 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; + 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; } From 1bc1f65e05a6ca95f5f616587f9df1017777e260 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Mon, 11 Aug 2025 17:03:16 +0800 Subject: [PATCH 04/17] Update stopbar light positioning and state handling in BARS processing --- src/services/bars/handlers.ts | 16 ++++++++-------- src/services/polygons.ts | 7 +++++-- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/services/bars/handlers.ts b/src/services/bars/handlers.ts index 1c299a4..cedf196 100644 --- a/src/services/bars/handlers.ts +++ b/src/services/bars/handlers.ts @@ -237,23 +237,23 @@ export class StopbarHandler extends BarsTypeHandler { ); // Step 2: Move the lights inward by the defined inward offset (0.3 meters) - // We move perpendicular to the stopbar line + // Now place them on the OPPOSITE side of the stopbar (flip from previous -90 to +90) const startInwardPoint = calculateDestinationPoint( startElevatedPoint, ELEVATED_LIGHT_INWARD_OFFSET, - (baseLineHeading - 90) % 360, // 90 degrees right of stopbar direction + (baseLineHeading + 90) % 360, // opposite side perpendicular ); const endInwardPoint = calculateDestinationPoint( endElevatedPoint, ELEVATED_LIGHT_INWARD_OFFSET, - (baseLineHeading - 90) % 360, // 90 degrees right of stopbar direction - ); // Step 3: Calculate the inward headings to make the lights point toward the center of the stopbar - // For the first elevated light at the start of the stopbar: angle inward by the inward angle - const firstElevatedHeading = (baseLineHeading + ELEVATED_LIGHT_INWARD_ANGLE) % 360; + (baseLineHeading + 90) % 360, // opposite side perpendicular + ); - // For the last elevated light at the end of the stopbar: angle inward by the inward angle (opposite direction) - const lastElevatedHeading = (baseLineHeading + 180 - ELEVATED_LIGHT_INWARD_ANGLE) % 360; + // Step 3: Flip headings 180° so elevated lights face the correct (opposite) way after side switch + // Original inward headings: base+angle and base+180-angle. We add 180 to both to flip them. + const firstElevatedHeading = (baseLineHeading + ELEVATED_LIGHT_INWARD_ANGLE + 90) % 360; + const lastElevatedHeading = (baseLineHeading - ELEVATED_LIGHT_INWARD_ANGLE + 90) % 360; // Add the elevated lights with correct positions and inward headings elevatedLights.push({ diff --git a/src/services/polygons.ts b/src/services/polygons.ts index 10b2152..76b63b0 100644 --- a/src/services/polygons.ts +++ b/src/services/polygons.ts @@ -197,7 +197,8 @@ export class PolygonService { const lightOrientation: 'left' | 'right' | 'both' = (point.properties?.orientation as any) || (obj.properties.orientation as any) || 'both'; const lightColor = (point.properties?.color || obj.properties.color || '').toLowerCase(); - const lightStateId = this.mapLightStateId(lightOrientation, lightColor); + const isElevatedStopbar = obj.type === 'stopbar' && point.properties?.elevated === true; + const lightStateId = this.mapLightStateId(lightOrientation, lightColor, isElevatedStopbar); const lightStateAttr = lightStateId !== undefined ? ` stateId="${lightStateId}"` : ''; xml += `\t\t\n`; xml += `\t\t\t${point.lat},${point.lon}\n`; @@ -258,7 +259,9 @@ export class PolygonService { * Bi mixed (Dir2 green, Dir1 other): * green-yellow=25, green-blue=26, green-orange=27 */ - private mapLightStateId(orientation: 'left' | 'right' | 'both', rawColor: string): number | undefined { + private mapLightStateId(orientation: 'left' | 'right' | 'both', rawColor: string, elevatedStopbar?: boolean): number | undefined { + // Elevated stopbar special state + if (elevatedStopbar) return 6; if (!rawColor) return undefined; // Normalize color string(s) const color = rawColor.toLowerCase(); From 61caa2773ff30352e75449172d7b653a1d67cd2e Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Mon, 11 Aug 2025 21:34:47 +0800 Subject: [PATCH 05/17] Add GET_STATE and STATE_SNAPSHOT packet types; enhance state handling logic --- src/network/connection.ts | 69 +++++++++++++++++++++++++-------------- src/types.ts | 21 +++++++----- 2 files changed, 57 insertions(+), 33 deletions(-) diff --git a/src/network/connection.ts b/src/network/connection.ts index 342fc93..287232f 100644 --- a/src/network/connection.ts +++ b/src/network/connection.ts @@ -557,17 +557,13 @@ export class Connection { ); } // Determine if there's an active state with controllers const now = Date.now(); - // Only consider controllers for determining if state is active const hasActiveControllers = state.controllers.size > 0; - const hasRecentUpdates = now - state.lastUpdate <= this.TWO_MINUTES; - const hasActiveState = hasActiveControllers && hasRecentUpdates; + const hasActiveState = hasActiveControllers; let stateObjects; let isOffline = false; if (clientType === 'controller' || hasActiveState) { - // Controllers always get the current state - // Pilots get active state only if controllers are online and have recent updates stateObjects = Array.from(state.objects.values()); isOffline = false; } else { @@ -643,6 +639,41 @@ export class Connection { ); break; + case 'GET_STATE': { + // Provide current state snapshot (controllers + pilots can request; observers too) + const airport = packet.airport || socketInfo.airport; + const state = this.airportStates.get(airport); + let offline = false; + let objects: AirportObject[] = []; + + // Determine if controllers currently connected for this airport + const hasControllers = Array.from(this.sockets.values()).some( + (c) => c.airport === airport && c.type === 'controller', + ); + + if (state && hasControllers) { + // If any controller currently connected, treat state as online regardless of recency + objects = Array.from(state.objects.values()); + } else { + offline = true; + objects = await this.getOfflineStateFromPoints(airport); + } + + const snapshot: Packet = { + type: 'STATE_SNAPSHOT', + airport, + data: { + objects, + sharedState: this.getSharedStateSnapshot(airport), + offline, + requestedAt: packet.timestamp || now, + }, + timestamp: Date.now(), + }; + server.send(JSON.stringify(snapshot)); + break; + } + case 'STATE_UPDATE': if (clientType === 'pilot') { throw new Error('Pilots cannot send state updates'); @@ -845,25 +876,13 @@ export class Connection { const connectedControllers = connectedClients.controllers.length > 0; if (state && connectedControllers) { - const now = Date.now(); - // Check if there's a recent state from controllers - const hasRecentState = now - state.lastUpdate <= this.TWO_MINUTES; - - if (hasRecentState) { - // Return active state with actual objects - objects = Array.from(state.objects.values()) - .filter((obj) => obj.state) - .map((obj) => ({ - id: obj.id, - state: obj.state, - controllerId: obj.controllerId, - timestamp: obj.timestamp, - })); - } else { - // Recent controllers but no recent state, use offline - isOffline = true; - objects = await this.getOfflineStateFromPoints(airport); - } + // Return active state with all objects regardless of recency since controllers are connected + objects = Array.from(state.objects.values()).map((obj) => ({ + id: obj.id, + state: obj.state, + controllerId: obj.controllerId, + timestamp: obj.timestamp, + })); } else { // No controllers connected or no state exists, mark as offline isOffline = true; @@ -1014,6 +1033,8 @@ export class Connection { 'CONTROLLER_CONNECT', 'CONTROLLER_DISCONNECT', 'ERROR', + 'GET_STATE', + 'STATE_SNAPSHOT', ]; if (!validTypes.includes(packet.type)) { diff --git a/src/types.ts b/src/types.ts index 4e6d081..9184ed2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -91,15 +91,17 @@ export interface AirportState { export interface Packet { type: - | 'STATE_UPDATE' - | 'INITIAL_STATE' - | 'CONTROLLER_CONNECT' - | 'CONTROLLER_DISCONNECT' - | 'SHARED_STATE_UPDATE' - | 'ERROR' - | 'HEARTBEAT' - | 'HEARTBEAT_ACK' - | 'CLOSE'; + | 'STATE_UPDATE' + | 'INITIAL_STATE' + | 'CONTROLLER_CONNECT' + | 'CONTROLLER_DISCONNECT' + | 'SHARED_STATE_UPDATE' + | 'ERROR' + | 'HEARTBEAT' + | 'HEARTBEAT_ACK' + | 'CLOSE' + | 'GET_STATE' + | 'STATE_SNAPSHOT'; airport?: string; data?: { objectId?: string; @@ -112,6 +114,7 @@ export interface Packet { message?: string; // For error messages connectionType?: ClientType; // Add connection type to data offline?: boolean; // Flag to indicate if state is offline (no controllers) + requestedAt?: number; // For STATE_SNAPSHOT - when request was made }; timestamp?: number; // Optional since server will set it } From 9948c2fd63fa40e8857f3113ae8bcddef8bc8ccc Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Mon, 11 Aug 2025 21:48:18 +0800 Subject: [PATCH 06/17] Update BARS map endpoint to include package parameter and enhance contribution retrieval logic --- openapi.json | 12 ++++++++++-- src/index.ts | 16 ++++++++++------ src/services/contributions.ts | 19 ++++++++++++------- 3 files changed, 32 insertions(+), 15 deletions(-) diff --git a/openapi.json b/openapi.json index 3f4e42d..02d1f05 100644 --- a/openapi.json +++ b/openapi.json @@ -1560,9 +1560,9 @@ } } }, - "/maps/{icao}/latest": { + "/maps/{icao}/packages/{package}/latest": { "get": { - "summary": "Get latest approved BARS map XML (raw content) for an airport", + "summary": "Get latest approved BARS map XML (raw content) for an airport & package", "tags": [ "Generation" ], @@ -1574,6 +1574,14 @@ "schema": { "type": "string" } + }, + { + "in": "path", + "name": "package", + "required": true, + "schema": { + "type": "string" + } } ], "responses": { diff --git a/src/index.ts b/src/index.ts index 63b1720..c73ef82 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2445,12 +2445,12 @@ app.route('/contributions', contributionsApp); // CDN Endpoints const cdnApp = new Hono<{ Bindings: Env }>(); -// Latest approved BARS map for an airport +// Latest approved BARS map for an airport & specific package /** * @openapi - * /maps/{icao}/latest: + * /maps/{icao}/packages/{package}/latest: * get: - * summary: Get latest approved BARS map XML (raw content) for an airport + * summary: Get latest approved BARS map XML (raw content) for an airport & package * tags: * - Generation * parameters: @@ -2458,18 +2458,23 @@ const cdnApp = new Hono<{ Bindings: Env }>(); * name: icao * required: true * schema: { type: string } + * - in: path + * name: package + * required: true + * schema: { type: string } * responses: * 200: * description: BARS XML document returned inline (application/xml) * 404: * description: Not found */ -app.get('/maps/:icao/latest', withCache(CacheKeys.fromUrl, 900, 'airports'), async (c) => { +app.get('/maps/:icao/packages/:package/latest', withCache(CacheKeys.fromUrl, 900, 'airports'), async (c) => { const icao = c.req.param('icao').toUpperCase(); + const pkg = c.req.param('package'); const contributions = ServicePool.getContributions(c.env); const storage = ServicePool.getStorage(c.env); - const latest = await contributions.getLatestApprovedContributionForAirport(icao); + const latest = await contributions.getLatestApprovedContributionForAirportPackage(icao, pkg); if (!latest) { return c.text('No approved map found', 404); } @@ -2477,7 +2482,6 @@ app.get('/maps/:icao/latest', withCache(CacheKeys.fromUrl, 900, 'airports'), asy const safePackageName = latest.packageName.replace(/[^a-zA-Z0-9.-]/g, '-'); const fileKey = `Maps/${icao}_${safePackageName}_bars.xml`; - // Fetch stored XML; if missing, return 404 const stored = await storage.getFile(fileKey); if (!stored) { return c.text('Map file not found', 404); diff --git a/src/services/contributions.ts b/src/services/contributions.ts index a5a4100..5312fe6 100644 --- a/src/services/contributions.ts +++ b/src/services/contributions.ts @@ -132,7 +132,7 @@ export class ContributionService { packageName: submission.packageName, userId: submission.userId, }); - } catch {} + } catch { } return contribution; } async getContribution(id: string): Promise { @@ -153,10 +153,15 @@ export class ContributionService { } /** - * Get the most recently approved contribution for an airport (by decision_date) + * Get the most recently approved contribution for an airport & package (by decision_date) + * Case-insensitive package name match. * @param airportIcao ICAO code + * @param packageName Package name (case-insensitive) */ - async getLatestApprovedContributionForAirport(airportIcao: string): Promise { + async getLatestApprovedContributionForAirportPackage( + airportIcao: string, + packageName: string, + ): Promise { const result = await this.dbSession.executeRead( ` SELECT @@ -166,11 +171,11 @@ export class ContributionService { submission_date as submissionDate, status, rejection_reason as rejectionReason, decision_date as decisionDate FROM contributions - WHERE airport_icao = ? AND status = 'approved' + WHERE airport_icao = ? AND lower(package_name) = lower(?) AND status = 'approved' ORDER BY datetime(decision_date) DESC LIMIT 1 `, - [airportIcao], + [airportIcao, packageName], ); return result.results[0] || null; } @@ -340,7 +345,7 @@ export class ContributionService { decidedBy: userId, rejectionReason: decision.approved ? undefined : decision.rejectionReason || 'No reason provided', }); - } catch {} + } catch { } return updated; } async getContributionStats(): Promise<{ @@ -394,7 +399,7 @@ export class ContributionService { if (result.success) { try { this.posthog?.track('Contribution Deleted', { id, userId }); - } catch {} + } catch { } } return result.success; } From 9310a6ee6f0977c6c48e87d3a260d9fba92d1bfc Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Tue, 12 Aug 2025 16:07:57 +0800 Subject: [PATCH 07/17] Add XML sanitization for contribution submissions to enhance security --- src/index.ts | 50 +++++++++++++++-------------------- src/services/contributions.ts | 11 +++++--- src/services/xml-sanitizer.ts | 47 ++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 31 deletions(-) create mode 100644 src/services/xml-sanitizer.ts diff --git a/src/index.ts b/src/index.ts index c73ef82..8b61d5c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ import { DatabaseContextFactory } from './services/database-context'; import { withCache, CacheKeys } from './services/cache'; import { ServicePool } from './services/service-pool'; import { PostHogService } from './services/posthog'; +import { sanitizeContributionXml } from './services/xml-sanitizer'; // Shared point regex const POINT_ID_REGEX = /^[A-Z0-9-_]+$/; @@ -1748,46 +1749,39 @@ app.post('/supports/generate', async (c) => { const icao = formData.get('icao')?.toString(); if (!xmlFile || !(xmlFile instanceof File)) { - return c.json( - { - error: 'XML file is required', - }, - 400, - ); + return c.json({ error: 'XML file is required' }, 400); } - if (!icao) { - return c.json( - { - error: 'ICAO code is required', - }, - 400, - ); + return c.json({ error: 'ICAO code is required' }, 400); + } + + const MAX_XML_BYTES = 200_000; + if (xmlFile.size > MAX_XML_BYTES) { + return c.json({ error: `XML file too large (>${MAX_XML_BYTES} bytes)` }, 400); + } + + const rawXml = await xmlFile.text(); + + let sanitized: string; + try { + sanitized = sanitizeContributionXml(rawXml, { maxBytes: MAX_XML_BYTES }); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Invalid XML'; + return c.json({ error: msg }, 400); } - const xmlContent = await xmlFile.text(); const supportService = ServicePool.getSupport(c.env); const polygonService = ServicePool.getPolygons(c.env); - // Generate both XML files in parallel const [supportsXml, barsXml] = await Promise.all([ - supportService.generateLightSupportsXML(xmlContent, icao), - polygonService.processBarsXML(xmlContent, icao), + supportService.generateLightSupportsXML(sanitized, icao), + polygonService.processBarsXML(sanitized, icao), ]); - // Return both XMLs as a JSON response - return c.json({ - supportsXml, - barsXml, - }); + return c.json({ supportsXml, barsXml }); } catch (error) { console.error('Error generating XMLs:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Unknown error generating XMLs', - }, - 500, - ); + return c.json({ error: error instanceof Error ? error.message : 'Unknown error generating XMLs' }, 500); } }); diff --git a/src/services/contributions.ts b/src/services/contributions.ts index 5312fe6..e8831de 100644 --- a/src/services/contributions.ts +++ b/src/services/contributions.ts @@ -5,6 +5,7 @@ import { SupportService } from './support'; import { PolygonService } from './polygons'; import { ServicePool } from './service-pool'; import { PostHogService } from './posthog'; +import { sanitizeContributionXml } from './xml-sanitizer'; export interface Contribution { id: string; @@ -78,9 +79,13 @@ export class ContributionService { throw new Error(`Airport with ICAO ${submission.airportIcao} not found`); } - const trimmedXml = submission.submittedXml.trim(); - if (!trimmedXml || !trimmedXml.startsWith(' maxBytes) { + throw new Error(`Submitted XML too large (> ${maxBytes} chars)`); + } + + const trimmed = raw.trim(); + if (!trimmed.startsWith(' = [ + { re: /]/.test(trimmed)) { + throw new Error('Invalid XML: Missing FSData root element'); + } + + // Remove any processing instructions after the first line (except XML declaration). Conservative approach. + let sanitized = trimmed.replace(/(<\?)(?!xml)([\s\S]*?\?>)/gi, ''); + + // Strip disallowed control chars (anything below 0x20 except TAB (0x09), LF (0x0A), CR (0x0D)) + sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, ''); + + // Optional: collapse repeated spaces between tags to keep storage predictable (small normalization) + sanitized = sanitized.replace(/>\s+<'); + + // Final sanity checks + if (sanitized.length === 0) throw new Error('Sanitized XML empty'); + if (!sanitized.startsWith(' Date: Tue, 12 Aug 2025 16:56:42 +0800 Subject: [PATCH 08/17] Add FAQ management endpoints and database schema --- openapi.json | 198 ++++++++++++++++++++++++++++++++++ schema.sql | 14 ++- scripts/generate-openapi.mjs | 1 + src/index.ts | 200 +++++++++++++++++++++++++++++++++++ src/services/faqs.ts | 72 +++++++++++++ src/services/service-pool.ts | 8 ++ 6 files changed, 492 insertions(+), 1 deletion(-) create mode 100644 src/services/faqs.ts diff --git a/openapi.json b/openapi.json index 02d1f05..d1fa625 100644 --- a/openapi.json +++ b/openapi.json @@ -69,6 +69,10 @@ "name": "CDN", "description": "File storage, upload, listing, and deletion via CDN-backed storage." }, + { + "name": "FAQ", + "description": "Frequently Asked Questions (FAQ) management and retrieval." + }, { "name": "EuroScope", "description": "EuroScope sector file upload, listing, and permission checks by ICAO." @@ -1910,6 +1914,200 @@ } } }, + "/faqs": { + "get": { + "summary": "List public FAQs", + "tags": [ + "FAQ" + ], + "responses": { + "200": { + "description": "FAQs returned" + } + } + } + }, + "/staff/faqs": { + "post": { + "x-hidden": true, + "summary": "Create FAQ", + "tags": [ + "Staff", + "FAQ" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "question", + "answer", + "order_position" + ], + "properties": { + "question": { + "type": "string" + }, + "answer": { + "type": "string" + }, + "order_position": { + "type": "integer" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Created" + } + } + } + }, + "/staff/faqs/{id}": { + "put": { + "x-hidden": true, + "summary": "Update FAQ", + "tags": [ + "Staff", + "FAQ" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "question": { + "type": "string" + }, + "answer": { + "type": "string" + }, + "order_position": { + "type": "integer" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Updated" + }, + "404": { + "description": "Not found" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete FAQ", + "tags": [ + "Staff", + "FAQ" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Deletion result" + } + } + } + }, + "/staff/faqs/reorder": { + "post": { + "x-hidden": true, + "summary": "Bulk reorder FAQs", + "tags": [ + "Staff", + "FAQ" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "updates" + ], + "properties": { + "updates": { + "type": "array", + "items": { + "type": "object", + "required": [ + "id", + "order_position" + ], + "properties": { + "id": { + "type": "string" + }, + "order_position": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Reordered" + } + } + } + }, "/health": { "get": { "summary": "System/service health check", diff --git a/schema.sql b/schema.sql index 6acb16f..8bb8bf7 100644 --- a/schema.sql +++ b/schema.sql @@ -157,4 +157,16 @@ CREATE INDEX IF NOT EXISTS idx_division_airports_composite ON division_airports( CREATE INDEX IF NOT EXISTS idx_division_airports_icao ON division_airports(icao); -- Points table composite index -CREATE INDEX IF NOT EXISTS idx_points_airport_type ON points(airport_id, type); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_points_airport_type ON points(airport_id, type); + +-- FAQs table for public frequently asked questions +CREATE TABLE IF NOT EXISTS faqs ( + id TEXT PRIMARY KEY, + question TEXT NOT NULL, + answer TEXT NOT NULL, + order_position INTEGER NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX IF NOT EXISTS idx_faqs_order ON faqs(order_position ASC); \ No newline at end of file diff --git a/scripts/generate-openapi.mjs b/scripts/generate-openapi.mjs index 0a8515d..a068bf8 100644 --- a/scripts/generate-openapi.mjs +++ b/scripts/generate-openapi.mjs @@ -41,6 +41,7 @@ const options = { { name: 'Contributions', description: 'Community lighting package submission, review, and leaderboard.' }, { name: 'Staff', description: 'Restricted staff-only operational and moderation endpoints (hidden from public docs).' }, { name: 'CDN', description: 'File storage, upload, listing, and deletion via CDN-backed storage.' }, + { name: 'FAQ', description: 'Frequently Asked Questions (FAQ) management and retrieval.' }, { name: 'EuroScope', description: 'EuroScope sector file upload, listing, and permission checks by ICAO.' }, { name: 'Cache', description: 'Administrative cache management operations.' }, { name: 'GitHub', description: 'Repository contributor information.' }, diff --git a/src/index.ts b/src/index.ts index 8b61d5c..e19acdf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3282,6 +3282,206 @@ app.get( }, ); +// FAQs public endpoint +/** + * @openapi + * /faqs: + * get: + * summary: List public FAQs + * tags: + * - FAQ + * responses: + * 200: + * description: FAQs returned + */ +app.get( + '/faqs', + withCache(() => 'faqs-public', 900, 'faq'), + async (c) => { + const faqService = ServicePool.getFAQs(c.env); + const data = await faqService.list(); + return c.json(data); + }, +); + +// Staff FAQ management endpoints +const faqStaffApp = new Hono<{ Bindings: Env; Variables: { user?: any } }>(); + +faqStaffApp.use('*', async (c, next) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return c.text('User not found', 404); + // Require product manager or higher + const allowed = await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER); + if (!allowed) return c.text('Forbidden', 403); + c.set('user', user); + await next(); +}); + +/** + * @openapi + * /staff/faqs: + * post: + * x-hidden: true + * summary: Create FAQ + * tags: + * - Staff + * - FAQ + * security: + * - VatsimToken: [] + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: [question, answer, order_position] + * properties: + * question: { type: string } + * answer: { type: string } + * order_position: { type: integer } + * responses: + * 201: + * description: Created + */ +faqStaffApp.post('/', async (c) => { + let body: any; + try { body = await c.req.json(); } catch { return c.json({ error: 'Invalid JSON' }, 400); } + const { question, answer } = body; + let order_position = Number(body.order_position); + if (!question || !answer || !Number.isInteger(order_position)) { + return c.json({ error: 'question, answer, order_position required' }, 400); + } + if (order_position < 0) order_position = 0; + const faqService = ServicePool.getFAQs(c.env); + const created = await faqService.create({ question, answer, order_position }); + // Purge public cache + try { await ServicePool.getCache(c.env).delete('faqs-public', 'faq'); } catch { } + return c.json(created, 201); +}); + +/** + * @openapi + * /staff/faqs/{id}: + * put: + * x-hidden: true + * summary: Update FAQ + * tags: + * - Staff + * - FAQ + * security: + * - VatsimToken: [] + * parameters: + * - in: path + * name: id + * required: true + * schema: { type: string } + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * properties: + * question: { type: string } + * answer: { type: string } + * order_position: { type: integer } + * responses: + * 200: + * description: Updated + * 404: + * description: Not found + */ +faqStaffApp.put('/:id', async (c) => { + const id = c.req.param('id'); + let body: any; try { body = await c.req.json(); } catch { body = {}; } + const faqService = ServicePool.getFAQs(c.env); + const updated = await faqService.update(id, { + question: body.question, + answer: body.answer, + order_position: Number.isInteger(body.order_position) ? body.order_position : undefined, + }); + if (!updated) return c.text('Not found', 404); + try { await ServicePool.getCache(c.env).delete('faqs-public', 'faq'); } catch { } + return c.json(updated); +}); + +/** + * @openapi + * /staff/faqs/{id}: + * delete: + * x-hidden: true + * summary: Delete FAQ + * tags: + * - Staff + * - FAQ + * security: + * - VatsimToken: [] + * parameters: + * - in: path + * name: id + * required: true + * schema: { type: string } + * responses: + * 200: + * description: Deletion result + */ +faqStaffApp.delete('/:id', async (c) => { + const id = c.req.param('id'); + const faqService = ServicePool.getFAQs(c.env); + const success = await faqService.delete(id); + if (success) { try { await ServicePool.getCache(c.env).delete('faqs-public', 'faq'); } catch { } } + return c.json({ success }); +}); + +/** + * @openapi + * /staff/faqs/reorder: + * post: + * x-hidden: true + * summary: Bulk reorder FAQs + * tags: + * - Staff + * - FAQ + * security: + * - VatsimToken: [] + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: [updates] + * properties: + * updates: + * type: array + * items: + * type: object + * required: [id, order_position] + * properties: + * id: { type: string } + * order_position: { type: integer } + * responses: + * 200: + * description: Reordered + */ +faqStaffApp.post('/reorder', async (c) => { + let body: any; try { body = await c.req.json(); } catch { return c.json({ error: 'Invalid JSON' }, 400); } + if (!Array.isArray(body.updates)) return c.json({ error: 'updates array required' }, 400); + const updates = body.updates.filter((u: any) => typeof u.id === 'string' && Number.isInteger(u.order_position)); + const faqService = ServicePool.getFAQs(c.env); + await faqService.reorder(updates); + try { await ServicePool.getCache(c.env).delete('faqs-public', 'faq'); } catch { } + return c.json({ success: true }); +}); + +app.route('/staff/faqs', faqStaffApp); + // Health endpoint /** * @openapi diff --git a/src/services/faqs.ts b/src/services/faqs.ts new file mode 100644 index 0000000..31347bb --- /dev/null +++ b/src/services/faqs.ts @@ -0,0 +1,72 @@ +import { DatabaseSessionService } from './database-session'; + +export interface FAQRecord { + id: string; + question: string; + answer: string; + order_position: number; + created_at: string; + updated_at: string; +} + +export class FAQService { + private dbSession: DatabaseSessionService; + constructor(private db: D1Database) { + this.dbSession = new DatabaseSessionService(db); + } + + async list(): Promise<{ faqs: FAQRecord[]; total: number }> { + const result = await this.dbSession.executeRead( + `SELECT id, question, answer, order_position, created_at, updated_at FROM faqs ORDER BY order_position ASC, datetime(created_at) ASC`, + [], + ); + return { faqs: result.results, total: result.results.length }; + } + + async get(id: string): Promise { + const result = await this.dbSession.executeRead( + `SELECT id, question, answer, order_position, created_at, updated_at FROM faqs WHERE id = ?`, + [id], + ); + return result.results[0] || null; + } + + async create(data: { question: string; answer: string; order_position: number }): Promise { + const id = crypto.randomUUID(); + await this.dbSession.executeWrite( + `INSERT INTO faqs (id, question, answer, order_position, created_at, updated_at) VALUES (?, ?, ?, ?, datetime('now'), datetime('now'))`, + [id, data.question, data.answer, data.order_position], + ); + const created = await this.get(id); + if (!created) throw new Error('Failed to create FAQ'); + return created; + } + + async update(id: string, data: Partial<{ question: string; answer: string; order_position: number }>): Promise { + const existing = await this.get(id); + if (!existing) return null; + const question = data.question ?? existing.question; + const answer = data.answer ?? existing.answer; + const order_position = data.order_position ?? existing.order_position; + await this.dbSession.executeWrite( + `UPDATE faqs SET question = ?, answer = ?, order_position = ?, updated_at = datetime('now') WHERE id = ?`, + [question, answer, order_position, id], + ); + return this.get(id); + } + + async delete(id: string): Promise { + const result = await this.dbSession.executeWrite(`DELETE FROM faqs WHERE id = ?`, [id]); + return result.success; // DatabaseSessionService returns success boolean + } + + async reorder(updates: { id: string; order_position: number }[]): Promise { + // Simple transactional reorder + for (const u of updates) { + await this.dbSession.executeWrite(`UPDATE faqs SET order_position = ?, updated_at = datetime('now') WHERE id = ?`, [ + u.order_position, + u.id, + ]); + } + } +} diff --git a/src/services/service-pool.ts b/src/services/service-pool.ts index fdf091b..ec089cb 100644 --- a/src/services/service-pool.ts +++ b/src/services/service-pool.ts @@ -14,6 +14,7 @@ import { ContributionService } from './contributions'; import { StorageService } from './storage'; import { GitHubService } from './github'; import { PostHogService } from './posthog'; +import { FAQService } from './faqs'; export const ServicePool = (() => { let vatsim: VatsimService; @@ -31,6 +32,7 @@ export const ServicePool = (() => { let storage: StorageService; let github: GitHubService; let posthog: PostHogService; + let faqs: FAQService; return { getVatsim(env: Env) { @@ -129,5 +131,11 @@ export const ServicePool = (() => { } return posthog; }, + getFAQs(env: Env) { + if (!faqs) { + faqs = new FAQService(env.DB); + } + return faqs; + }, }; })(); From 25f87b45c57d3e1aa7f8a27c583dfa8d0381f8c4 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Tue, 12 Aug 2025 17:50:14 +0800 Subject: [PATCH 09/17] Add installer releases management endpoints and database schema --- openapi.json | 115 ++++++++++++++++++++++++++++ schema.sql | 17 ++++- src/index.ts | 141 +++++++++++++++++++++++++++++++++++ src/services/releases.ts | 61 +++++++++++++++ src/services/service-pool.ts | 8 ++ 5 files changed, 341 insertions(+), 1 deletion(-) create mode 100644 src/services/releases.ts diff --git a/openapi.json b/openapi.json index d1fa625..ac8baad 100644 --- a/openapi.json +++ b/openapi.json @@ -1857,6 +1857,121 @@ } } }, + "/releases": { + "get": { + "summary": "List all product releases (optionally filtered)", + "tags": [ + "Installer" + ], + "parameters": [ + { + "in": "query", + "name": "product", + "schema": { + "type": "string", + "enum": [ + "Pilot-Client", + "vatSys-Plugin", + "EuroScope-Plugin" + ] + } + } + ], + "responses": { + "200": { + "description": "Releases listed" + } + } + } + }, + "/releases/latest": { + "get": { + "summary": "Get latest release for a product", + "tags": [ + "Installer" + ], + "parameters": [ + { + "in": "query", + "name": "product", + "required": true, + "schema": { + "type": "string", + "enum": [ + "Pilot-Client", + "vatSys-Plugin", + "EuroScope-Plugin" + ] + } + } + ], + "responses": { + "200": { + "description": "Latest release returned" + }, + "404": { + "description": "Not found" + } + } + } + }, + "/releases/upload": { + "post": { + "x-hidden": true, + "summary": "Create a new product release (lead developer only)", + "tags": [ + "Installer" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "required": [ + "file", + "product", + "version" + ], + "properties": { + "file": { + "type": "string", + "format": "binary" + }, + "product": { + "type": "string", + "enum": [ + "Pilot-Client", + "vatSys-Plugin", + "EuroScope-Plugin" + ] + }, + "version": { + "type": "string" + }, + "changelog": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Release created" + }, + "403": { + "description": "Forbidden" + } + } + } + }, "/purge-cache": { "post": { "x-hidden": true, diff --git a/schema.sql b/schema.sql index 8bb8bf7..4d0ac93 100644 --- a/schema.sql +++ b/schema.sql @@ -169,4 +169,19 @@ CREATE TABLE IF NOT EXISTS faqs ( updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ); -CREATE INDEX IF NOT EXISTS idx_faqs_order ON faqs(order_position ASC); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_faqs_order ON faqs(order_position ASC); + +-- Installer releases table for distributable products +CREATE TABLE IF NOT EXISTS installer_releases ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + product TEXT NOT NULL, -- Pilot-Client | vatSys-Plugin | EuroScope-Plugin + version TEXT NOT NULL, + file_key TEXT NOT NULL, + file_size INTEGER NOT NULL, + file_hash TEXT NOT NULL, -- sha256 hex + changelog TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(product, version) +); +CREATE INDEX IF NOT EXISTS idx_installer_releases_product ON installer_releases(product); +CREATE INDEX IF NOT EXISTS idx_installer_releases_created_at ON installer_releases(created_at DESC); \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index e19acdf..b0b6b49 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,7 @@ import { PointChangeset, PointData } from './types'; import { VatsimService } from './services/vatsim'; import { AuthService } from './services/auth'; import { StaffRole } from './services/roles'; +import { InstallerProduct } from './services/releases'; import { Connection } from './network/connection'; import { UserService } from './services/users'; import { DatabaseContextFactory } from './services/database-context'; @@ -3172,6 +3173,146 @@ euroscopeApp.get('/:icao/editable', async (c) => { }); app.route('/euroscope', euroscopeApp); +// Installer / Releases endpoints +/** + * @openapi + * /releases: + * get: + * summary: List all product releases (optionally filtered) + * tags: + * - Installer + * parameters: + * - in: query + * name: product + * schema: { type: string, enum: [Pilot-Client, vatSys-Plugin, EuroScope-Plugin] } + * responses: + * 200: + * description: Releases listed + */ +app.get( + '/releases', + withCache(CacheKeys.fromUrl, 300, 'installer'), // cache 5m + async (c) => { + const product = c.req.query('product') as InstallerProduct | undefined; + const channel = c.req.query('channel') as 'stable' | 'beta' | undefined; + const releasesService = ServicePool.getReleases(c.env); + const releases = await releasesService.listReleases(product); + return c.json({ releases }); + } +); + +/** + * @openapi + * /releases/latest: + * get: + * summary: Get latest release for a product + * tags: + * - Installer + * parameters: + * - in: query + * name: product + * required: true + * schema: { type: string, enum: [Pilot-Client, vatSys-Plugin, EuroScope-Plugin] } + * responses: + * 200: + * description: Latest release returned + * 404: + * description: Not found + */ +app.get('/releases/latest', withCache(CacheKeys.fromUrl, 120, 'installer'), async (c) => { + const product = c.req.query('product') as InstallerProduct | undefined; + if (!product) return c.text('product required', 400); + const releasesService = ServicePool.getReleases(c.env); + const latest = await releasesService.getLatest(product); + if (!latest) return c.text('Not found', 404); + // Provide direct download URL via CDN domain + const downloadUrl = new URL(`https://dev-cdn.stopbars.com/${latest.file_key}`, c.req.url).toString(); + return c.json({ ...latest, downloadUrl }); +}); + +/** + * @openapi + * /releases/upload: + * post: + * x-hidden: true + * summary: Create a new product release (lead developer only) + * tags: + * - Installer + * security: + * - VatsimToken: [] + * requestBody: + * required: true + * content: + * multipart/form-data: + * schema: + * type: object + * required: [file, product, version] + * properties: + * file: + * type: string + * format: binary + * product: + * type: string + * enum: [Pilot-Client, vatSys-Plugin, EuroScope-Plugin] + * version: + * type: string + * changelog: + * type: string + * responses: + * 201: + * description: Release created + * 403: + * description: Forbidden + */ +app.post('/releases/upload', async (c) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return c.text('User not found', 404); + const isLeadDev = await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER); + if (!isLeadDev) return c.text('Forbidden', 403); + try { + const formData = await c.req.formData(); + const file = formData.get('file'); + const product = formData.get('product')?.toString() as InstallerProduct | undefined; + const version = formData.get('version')?.toString(); + const changelog = formData.get('changelog')?.toString(); + if (!file || !(file instanceof File)) return c.json({ error: 'file required' }, 400); + if (!product || !version) return c.json({ error: 'product & version required' }, 400); + const MAX = 50 * 1024 * 1024; + if (file.size > MAX) return c.json({ error: 'File too large (50MB max)' }, 400); + const storage = ServicePool.getStorage(c.env); + const fileKey = `releases/${product}/${version}/${file.name}`; + const bytes = await file.arrayBuffer(); + const digest = await crypto.subtle.digest('SHA-256', bytes); + const sha256 = Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join(''); + await storage.uploadFile(fileKey, bytes, file.type || 'application/zip', { + uploadedBy: user.vatsim_id, + product, + version, + size: file.size.toString(), + sha256 + }); + const releasesService = ServicePool.getReleases(c.env); + const release = await releasesService.createRelease({ + product, + version, + fileKey, + fileSize: file.size, + fileHash: sha256, + changelog + }); + return c.json({ success: true, release, downloadUrl: `https://dev-cdn.stopbars.com/${fileKey}` }, 201); + } catch (err) { + console.error('Release upload error', err); + return c.json({ error: err instanceof Error ? err.message : 'upload failed' }, 500); + } +}); + /** * @openapi * /purge-cache: diff --git a/src/services/releases.ts b/src/services/releases.ts new file mode 100644 index 0000000..7dc8a10 --- /dev/null +++ b/src/services/releases.ts @@ -0,0 +1,61 @@ +import { DatabaseSessionService } from './database-session'; +import { StorageService } from './storage'; + +export type InstallerProduct = 'Pilot-Client' | 'vatSys-Plugin' | 'EuroScope-Plugin'; +export interface ReleaseRecord { + id: number; + product: InstallerProduct; + version: string; + file_key: string; + file_size: number; + file_hash: string; + changelog?: string; + created_at: string; +} + +export interface CreateReleaseInput { + product: InstallerProduct; + version: string; + fileKey: string; + fileSize: number; + fileHash: string; // sha256 hex + changelog?: string; +} + +export class ReleaseService { + private dbSession: DatabaseSessionService; + constructor(private db: D1Database, private storage: StorageService) { + this.dbSession = new DatabaseSessionService(db); + } + + async createRelease(input: CreateReleaseInput): Promise { + const { product, version, fileKey, fileSize, fileHash, changelog } = input; + const result = await this.dbSession.executeWrite( + `INSERT INTO installer_releases (product, version, file_key, file_size, file_hash, changelog) VALUES (?,?,?,?,?,?) RETURNING *`, + [product, version, fileKey, fileSize, fileHash, changelog || null], + ); + const release = result.results[0] as ReleaseRecord; + if (!release) throw new Error('Failed to create release'); + return release; + } + + async listReleases(product?: InstallerProduct): Promise { + if (product) { + const res = await this.dbSession.executeRead( + 'SELECT * FROM installer_releases WHERE product = ? ORDER BY created_at DESC', + [product], + ); + return res.results; + } + const res = await this.dbSession.executeRead('SELECT * FROM installer_releases ORDER BY created_at DESC'); + return res.results; + } + + async getLatest(product: InstallerProduct): Promise { + const res = await this.dbSession.executeRead( + `SELECT * FROM installer_releases WHERE product = ? ORDER BY created_at DESC LIMIT 1`, + [product], + ); + return res.results[0] || null; + } +} diff --git a/src/services/service-pool.ts b/src/services/service-pool.ts index ec089cb..3800640 100644 --- a/src/services/service-pool.ts +++ b/src/services/service-pool.ts @@ -15,6 +15,7 @@ import { StorageService } from './storage'; import { GitHubService } from './github'; import { PostHogService } from './posthog'; import { FAQService } from './faqs'; +import { ReleaseService } from './releases'; export const ServicePool = (() => { let vatsim: VatsimService; @@ -33,6 +34,7 @@ export const ServicePool = (() => { let github: GitHubService; let posthog: PostHogService; let faqs: FAQService; + let releases: ReleaseService; return { getVatsim(env: Env) { @@ -137,5 +139,11 @@ export const ServicePool = (() => { } return faqs; }, + getReleases(env: Env) { + if (!releases) { + releases = new ReleaseService(env.DB, this.getStorage(env)); + } + return releases; + }, }; })(); From 571e628764ace848aa1b7cf593f5c22543aeaa68 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Thu, 14 Aug 2025 14:42:10 +0800 Subject: [PATCH 10/17] Add staff management endpoints and update release schema to include image URL --- openapi.json | 166 ++++++++++++++++++++ schema.sql | 1 + src/index.ts | 288 ++++++++++++++++++++++++++++++++-- src/services/contributions.ts | 23 +++ src/services/releases.ts | 16 +- src/services/roles.ts | 55 ++++++- 6 files changed, 529 insertions(+), 20 deletions(-) diff --git a/openapi.json b/openapi.json index ac8baad..60766cf 100644 --- a/openapi.json +++ b/openapi.json @@ -1321,6 +1321,106 @@ } } }, + "/staff/manage": { + "get": { + "x-hidden": true, + "summary": "List staff members", + "tags": [ + "Staff" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Staff listed" + }, + "403": { + "description": "Forbidden" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Add or update a staff member", + "tags": [ + "Staff" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "vatsimId", + "role" + ], + "properties": { + "vatsimId": { + "type": "string" + }, + "role": { + "type": "string", + "enum": [ + "LEAD_DEVELOPER", + "PRODUCT_MANAGER" + ] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Staff added/updated" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/staff/manage/{vatsimId}": { + "delete": { + "x-hidden": true, + "summary": "Remove staff member", + "tags": [ + "Staff" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "vatsimId", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Staff removed" + }, + "403": { + "description": "Forbidden" + } + } + } + }, "/contributions": { "get": { "summary": "List contributions", @@ -1956,6 +2056,11 @@ }, "changelog": { "type": "string" + }, + "image": { + "type": "string", + "format": "binary", + "description": "Optional promotional image (PNG/JPEG, max 5MB)" } } } @@ -1972,6 +2077,67 @@ } } }, + "/releases/{id}/changelog": { + "put": { + "x-hidden": true, + "summary": "Update changelog content for a release", + "description": "Update only the changelog text of an existing release record.", + "tags": [ + "Installer" + ], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "changelog" + ], + "properties": { + "changelog": { + "type": "string", + "maxLength": 20000 + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Changelog updated" + }, + "400": { + "description": "Validation error" + }, + "401": { + "description": "Unauthorized" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Release not found" + } + } + } + }, "/purge-cache": { "post": { "x-hidden": true, diff --git a/schema.sql b/schema.sql index 4d0ac93..71e2a78 100644 --- a/schema.sql +++ b/schema.sql @@ -180,6 +180,7 @@ CREATE TABLE IF NOT EXISTS installer_releases ( file_size INTEGER NOT NULL, file_hash TEXT NOT NULL, -- sha256 hex changelog TEXT, + image_url TEXT, -- Optional promotional image created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(product, version) ); diff --git a/src/index.ts b/src/index.ts index b0b6b49..058eda5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2087,6 +2087,126 @@ staffUsersApp.delete('/:id', async (c) => { app.route('/staff/users', staffUsersApp); +// Staff management (lead developer only) – manage staff roles +const staffManageApp = new Hono<{ Bindings: Env }>(); + +/** + * @openapi + * /staff/manage: + * get: + * x-hidden: true + * summary: List staff members + * tags: [Staff] + * security: + * - VatsimToken: [] + * responses: + * 200: { description: Staff listed } + * 403: { description: Forbidden } + */ +staffManageApp.get('/', async (c) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return c.text('User not found', 404); + const allowed = await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER); + if (!allowed) return c.text('Forbidden', 403); + const staff = await roles.listStaff(); + return c.json({ staff }); +}); + +/** + * @openapi + * /staff/manage: + * post: + * x-hidden: true + * summary: Add or update a staff member + * tags: [Staff] + * security: + * - VatsimToken: [] + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: [vatsimId, role] + * properties: + * vatsimId: { type: string } + * role: { type: string, enum: [LEAD_DEVELOPER, PRODUCT_MANAGER] } + * responses: + * 200: { description: Staff added/updated } + * 403: { description: Forbidden } + */ +staffManageApp.post('/', async (c) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + let body: any; try { body = await c.req.json(); } catch { return c.json({ error: 'Invalid JSON' }, 400); } + const { vatsimId, role } = body || {}; + if (!vatsimId || !role || !(role in StaffRole)) return c.json({ error: 'vatsimId and valid role required' }, 400); + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return c.text('User not found', 404); + const allowed = await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER); + if (!allowed) return c.text('Forbidden', 403); + const targetUser = await auth.getUserByVatsimId(vatsimId); + if (!targetUser) return c.json({ error: 'Target user not found' }, 404); + try { + const staff = await roles.addStaff(targetUser.id, role as StaffRole); + return c.json({ success: true, staff }); + } catch (e) { + return c.json({ error: e instanceof Error ? e.message : 'Failed to add/update staff' }, 400); + } +}); + +/** + * @openapi + * /staff/manage/{vatsimId}: + * delete: + * x-hidden: true + * summary: Remove staff member + * tags: [Staff] + * security: + * - VatsimToken: [] + * parameters: + * - in: path + * name: vatsimId + * required: true + * schema: { type: string } + * responses: + * 200: { description: Staff removed } + * 403: { description: Forbidden } + */ +staffManageApp.delete('/:vatsimId', async (c) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + const targetVatsimId = c.req.param('vatsimId'); + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return c.text('User not found', 404); + const allowed = await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER); + if (!allowed) return c.text('Forbidden', 403); + const targetUser = await auth.getUserByVatsimId(targetVatsimId); + if (!targetUser) return c.json({ error: 'Target user not found' }, 404); + try { + const removed = await roles.removeStaff(targetUser.id); + return c.json({ success: removed }); + } catch (e) { + return c.json({ error: e instanceof Error ? e.message : 'Failed to remove staff' }, 400); + } +}); + +app.route('/staff/manage', staffManageApp); + // Contributions endpoints const contributionsApp = new Hono<{ Bindings: Env }>(); @@ -3194,7 +3314,6 @@ app.get( withCache(CacheKeys.fromUrl, 300, 'installer'), // cache 5m async (c) => { const product = c.req.query('product') as InstallerProduct | undefined; - const channel = c.req.query('channel') as 'stable' | 'beta' | undefined; const releasesService = ServicePool.getReleases(c.env); const releases = await releasesService.listReleases(product); return c.json({ releases }); @@ -3227,7 +3346,9 @@ app.get('/releases/latest', withCache(CacheKeys.fromUrl, 120, 'installer'), asyn if (!latest) return c.text('Not found', 404); // Provide direct download URL via CDN domain const downloadUrl = new URL(`https://dev-cdn.stopbars.com/${latest.file_key}`, c.req.url).toString(); - return c.json({ ...latest, downloadUrl }); + const imageUrl = latest.image_url ? new URL(latest.image_url, c.req.url).toString() : undefined; + const { image_url: _omitImage, ...rest } = latest as any; + return c.json({ ...rest, downloadUrl, imageUrl }); }); /** @@ -3258,6 +3379,10 @@ app.get('/releases/latest', withCache(CacheKeys.fromUrl, 120, 'installer'), asyn * type: string * changelog: * type: string + * image: + * type: string + * format: binary + * description: Optional promotional image (PNG/JPEG, max 5MB) * responses: * 201: * description: Release created @@ -3270,33 +3395,80 @@ app.post('/releases/upload', async (c) => { const vatsim = ServicePool.getVatsim(c.env); const auth = ServicePool.getAuth(c.env); const roles = ServicePool.getRoles(c.env); - const vatsimUser = await vatsim.getUser(vatsimToken); + + // Start remote VATSIM lookup early while we parse form data (minor latency win) + const vatsimUserPromise = vatsim.getUser(vatsimToken); + + let formData: FormData; + try { + formData = await c.req.formData(); + } catch { + return c.json({ error: 'Invalid form-data' }, 400); + } + + const file = formData.get('file'); + const product = formData.get('product')?.toString() as InstallerProduct | undefined; + const version = formData.get('version')?.toString(); + const changelog = formData.get('changelog')?.toString(); + const image = formData.get('image'); + + // Await user info only after fast local parsing work is done + let vatsimUser; + try { + vatsimUser = await vatsimUserPromise; + } catch (e) { + return c.text('Failed to validate user', 401); + } const user = await auth.getUserByVatsimId(vatsimUser.id); if (!user) return c.text('User not found', 404); const isLeadDev = await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER); if (!isLeadDev) return c.text('Forbidden', 403); + + if (!file || !(file instanceof File)) return c.json({ error: 'file required' }, 400); + if (!product || !version) return c.json({ error: 'product & version required' }, 400); + const MAX = 90 * 1024 * 1024; + if (file.size > MAX) return c.json({ error: 'File too large (90MB max)' }, 400); try { - const formData = await c.req.formData(); - const file = formData.get('file'); - const product = formData.get('product')?.toString() as InstallerProduct | undefined; - const version = formData.get('version')?.toString(); - const changelog = formData.get('changelog')?.toString(); - if (!file || !(file instanceof File)) return c.json({ error: 'file required' }, 400); - if (!product || !version) return c.json({ error: 'product & version required' }, 400); - const MAX = 50 * 1024 * 1024; - if (file.size > MAX) return c.json({ error: 'File too large (50MB max)' }, 400); const storage = ServicePool.getStorage(c.env); const fileKey = `releases/${product}/${version}/${file.name}`; const bytes = await file.arrayBuffer(); + let imageBytesPromise: Promise | undefined; + if (image && image instanceof File) { + imageBytesPromise = image.arrayBuffer(); + } + const digest = await crypto.subtle.digest('SHA-256', bytes); const sha256 = Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join(''); - await storage.uploadFile(fileKey, bytes, file.type || 'application/zip', { + + // Validate image (after its bytes read started) before uploads + let imageUrl: string | undefined; + let imageUploadPromise: Promise | undefined; + let imageKey: string | undefined; + if (image && image instanceof File) { + const ALLOWED = ['image/png', 'image/jpeg']; + const MAX_IMAGE = 5 * 1024 * 1024; // 5MB + if (!ALLOWED.includes(image.type)) return c.json({ error: 'Invalid image type (png or jpeg only)' }, 400); + if (image.size > MAX_IMAGE) return c.json({ error: 'Image too large (5MB max)' }, 400); + const imageExt = image.type === 'image/png' ? 'png' : 'jpg'; + imageKey = `releases/${product}/${version}/promo.${imageExt}`; + // Wait for image bytes only when needed (likely already resolved by now) + const imgBytes = await imageBytesPromise!; + imageUploadPromise = storage.uploadFile(imageKey, imgBytes, image.type || 'image/png', { + uploadedBy: user.vatsim_id, + product, + version, + }); + imageUrl = `https://dev-cdn.stopbars.com/${imageKey}`; + } + const fileUploadPromise = storage.uploadFile(fileKey, bytes, file.type || 'application/zip', { uploadedBy: user.vatsim_id, product, version, size: file.size.toString(), sha256 }); + + await Promise.all([fileUploadPromise, imageUploadPromise].filter(Boolean)); const releasesService = ServicePool.getReleases(c.env); const release = await releasesService.createRelease({ product, @@ -3304,15 +3476,101 @@ app.post('/releases/upload', async (c) => { fileKey, fileSize: file.size, fileHash: sha256, - changelog + changelog, + imageUrl }); - return c.json({ success: true, release, downloadUrl: `https://dev-cdn.stopbars.com/${fileKey}` }, 201); + return c.json({ success: true, release, downloadUrl: `https://dev-cdn.stopbars.com/${fileKey}`, imageUrl }, 201); } catch (err) { console.error('Release upload error', err); return c.json({ error: err instanceof Error ? err.message : 'upload failed' }, 500); } }); +/** + * @openapi + * /releases/{id}/changelog: + * put: + * x-hidden: true + * summary: Update changelog content for a release + * description: Update only the changelog text of an existing release record. + * tags: + * - Installer + * security: + * - VatsimToken: [] + * parameters: + * - in: path + * name: id + * required: true + * schema: { type: integer } + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: [changelog] + * properties: + * changelog: + * type: string + * maxLength: 20000 + * responses: + * 200: + * description: Changelog updated + * 400: + * description: Validation error + * 401: + * description: Unauthorized + * 403: + * description: Forbidden + * 404: + * description: Release not found + */ +app.put('/releases/:id/changelog', async (c) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + const idRaw = c.req.param('id'); + const id = parseInt(idRaw, 10); + if (Number.isNaN(id) || id <= 0) return c.text('Invalid id', 400); + + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); + const releasesService = ServicePool.getReleases(c.env); + + try { + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return c.text('User not found', 404); + // Allow Lead Developer or Product Manager + const canEdit = (await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER)) || (await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER)); + if (!canEdit) return c.text('Forbidden', 403); + + let body: any; + try { body = await c.req.json(); } catch { return c.json({ error: 'Invalid JSON body' }, 400); } + const changelog = typeof body?.changelog === 'string' ? body.changelog.trim() : ''; + if (!changelog) return c.json({ error: 'changelog required' }, 400); + if (changelog.length > 20000) return c.json({ error: 'changelog too long (max 20000 chars)' }, 400); + + // Ensure release exists first (so we differentiate 404 vs silent update) + // Reusing listReleases would be inefficient; perform direct lookup. + const dbContext = DatabaseContextFactory.createRequestContext(c.env.DB, c.req.raw); + try { + const existing = await dbContext.db.executeRead('SELECT * FROM installer_releases WHERE id = ?', [id]); + if (!existing.results[0]) return dbContext.textResponse('Release not found', { status: 404 }); + } finally { + // close early; release update uses its own session service + // (ReleaseService internally manages its session.) + } + + const updated = await releasesService.updateChangelog(id, changelog); + if (!updated) return c.text('Release not found', 404); + return c.json({ success: true, release: updated }); + } catch (err) { + console.error('Changelog update error', err); + return c.json({ error: err instanceof Error ? err.message : 'update failed' }, 500); + } +}); + /** * @openapi * /purge-cache: diff --git a/src/services/contributions.ts b/src/services/contributions.ts index e8831de..39ece40 100644 --- a/src/services/contributions.ts +++ b/src/services/contributions.ts @@ -88,6 +88,29 @@ export class ContributionService { throw new Error(msg); } + try { + const latestApproved = await this.getLatestApprovedContributionForAirportPackage( + submission.airportIcao, + submission.packageName, + ); + if (latestApproved) { + const normalize = (xml: string) => + xml + .trim() + .replace(/\r/g, '') + .replace(/[\t ]+/g, ' ') + .replace(/>\s+<'); + if (normalize(trimmedXml) === normalize(latestApproved.submittedXml)) { + throw new Error('Duplicate of current approved XML for this airport & package'); + } + } + } catch (e) { + if (e instanceof Error && e.message.startsWith('Duplicate')) { + // Re-throw duplicate error directly + throw e; + } + } + const id = crypto.randomUUID(); const now = new Date().toISOString(); diff --git a/src/services/releases.ts b/src/services/releases.ts index 7dc8a10..3654c81 100644 --- a/src/services/releases.ts +++ b/src/services/releases.ts @@ -10,6 +10,7 @@ export interface ReleaseRecord { file_size: number; file_hash: string; changelog?: string; + image_url?: string; created_at: string; } @@ -20,6 +21,7 @@ export interface CreateReleaseInput { fileSize: number; fileHash: string; // sha256 hex changelog?: string; + imageUrl?: string; } export class ReleaseService { @@ -29,10 +31,10 @@ export class ReleaseService { } async createRelease(input: CreateReleaseInput): Promise { - const { product, version, fileKey, fileSize, fileHash, changelog } = input; + const { product, version, fileKey, fileSize, fileHash, changelog, imageUrl } = input; const result = await this.dbSession.executeWrite( - `INSERT INTO installer_releases (product, version, file_key, file_size, file_hash, changelog) VALUES (?,?,?,?,?,?) RETURNING *`, - [product, version, fileKey, fileSize, fileHash, changelog || null], + `INSERT INTO installer_releases (product, version, file_key, file_size, file_hash, changelog, image_url) VALUES (?,?,?,?,?,?,?) RETURNING *`, + [product, version, fileKey, fileSize, fileHash, changelog || null, imageUrl || null], ); const release = result.results[0] as ReleaseRecord; if (!release) throw new Error('Failed to create release'); @@ -58,4 +60,12 @@ export class ReleaseService { ); return res.results[0] || null; } + + async updateChangelog(id: number, changelog: string): Promise { + const res = await this.dbSession.executeWrite( + `UPDATE installer_releases SET changelog = ? WHERE id = ? RETURNING *`, + [changelog, id], + ); + return (res.results[0] as ReleaseRecord) || null; + } } diff --git a/src/services/roles.ts b/src/services/roles.ts index befe3ce..f96d43a 100644 --- a/src/services/roles.ts +++ b/src/services/roles.ts @@ -1,13 +1,11 @@ export enum StaffRole { LEAD_DEVELOPER = 'LEAD_DEVELOPER', PRODUCT_MANAGER = 'PRODUCT_MANAGER', - MAP_APPROVER = 'MAP_APPROVER', // For approving contributions. } export const roleHierarchy: Record = { LEAD_DEVELOPER: 999, PRODUCT_MANAGER: 500, - MAP_APPROVER: 100, }; export type Role = 'lead_developer' | 'product_manager' | 'nav_head' | 'nav_member'; @@ -77,4 +75,57 @@ export class RoleService { {} as DivisionRoles, ); } + + // --- Staff management helpers (write) --- + private async getRoleCount(role: StaffRole): Promise { + const res = await this.dbSession.executeRead<{ cnt: number }>('SELECT COUNT(*) as cnt FROM staff WHERE role = ?', [role]); + return res.results[0]?.cnt || 0; + } + + private async ensureNotLastLeadDeveloper(userId: number, changingToRole?: StaffRole | null) { + const existing = await this.dbSession.executeRead('SELECT * FROM staff WHERE user_id = ?', [userId]); + const current = existing.results[0]; + if (!current) return; // not staff + if ((current.role as StaffRole) === StaffRole.LEAD_DEVELOPER && (changingToRole == null || changingToRole !== StaffRole.LEAD_DEVELOPER)) { + const count = await this.getRoleCount(StaffRole.LEAD_DEVELOPER); + if (count <= 1) throw new Error('Cannot modify or remove the last remaining lead developer'); + } + } + + async addStaff(userId: number, role: StaffRole): Promise<{ user_id: number; role: StaffRole; created_at: string }> { + const existing = await this.dbSession.executeRead('SELECT * FROM staff WHERE user_id = ?', [userId]); + if (existing.results[0]) { + await this.ensureNotLastLeadDeveloper(userId, role); + await this.dbSession.executeWrite('UPDATE staff SET role = ? WHERE user_id = ?', [role, userId]); + const updated = await this.dbSession.executeRead('SELECT * FROM staff WHERE user_id = ?', [userId]); + const row = updated.results[0]!; + return { user_id: row.user_id, role: row.role as StaffRole, created_at: row.created_at }; + } + const createdAt = new Date().toISOString(); + await this.dbSession.executeWrite('INSERT INTO staff (user_id, role, created_at) VALUES (?, ?, ?)', [userId, role, createdAt]); + return { user_id: userId, role, created_at: createdAt }; + } + + async updateStaffRole(userId: number, role: StaffRole): Promise { + await this.ensureNotLastLeadDeveloper(userId, role); + const result = await this.dbSession.executeWrite('UPDATE staff SET role = ? WHERE user_id = ?', [role, userId]); + return !!result.success; + } + + async removeStaff(userId: number): Promise { + await this.ensureNotLastLeadDeveloper(userId, null); + const result = await this.dbSession.executeWrite('DELETE FROM staff WHERE user_id = ?', [userId]); + return !!result.success; + } + + async listStaff(): Promise> { + const res = await this.dbSession.executeRead<{ user_id: number; role: string; created_at: string; vatsim_id: string; full_name: string | null }>( + `SELECT s.user_id, s.role, s.created_at, u.vatsim_id, u.full_name + FROM staff s + JOIN users u ON u.id = s.user_id + ORDER BY s.created_at DESC`, + [], + ); + return res.results.map((r) => ({ user_id: r.user_id, role: r.role as StaffRole, created_at: r.created_at, vatsim_id: r.vatsim_id, full_name: r.full_name })); + } } From 2d304bf28a61ddd3f7a35ed07fdc6c997c00e912 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Thu, 14 Aug 2025 14:49:59 +0800 Subject: [PATCH 11/17] Refactor index.ts by removing commented-out code and unnecessary comments for improved readability --- src/index.ts | 57 +--------------------------------------------------- 1 file changed, 1 insertion(+), 56 deletions(-) diff --git a/src/index.ts b/src/index.ts index 058eda5..9de2fdd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,8 +13,6 @@ import { withCache, CacheKeys } from './services/cache'; import { ServicePool } from './services/service-pool'; import { PostHogService } from './services/posthog'; import { sanitizeContributionXml } from './services/xml-sanitizer'; - -// Shared point regex const POINT_ID_REGEX = /^[A-Z0-9-_]+$/; interface CreateDivisionPayload { @@ -76,18 +74,15 @@ const app = new Hono<{ }; }>(); -// Analytics middleware (PostHog) – skip clearly useless noise (OPTIONS, favicon, configured ignores) app.use('*', async (c, next) => { const start = Date.now(); await next(); try { const url = new URL(c.req.url); const path = url.pathname; - // Basic noise filters - if (c.req.method === 'OPTIONS') return; // CORS preflight + if (c.req.method === 'OPTIONS') return; if (path === '/favicon.ico') return; if (path.includes('/health')) return; - // Env-driven ignore list: comma separated exact paths or prefix* globs const ignoreRaw = (c.env as any).ANALYTICS_IGNORE as string | undefined; if (ignoreRaw) { const ignores = ignoreRaw @@ -120,7 +115,6 @@ app.use('*', async (c, next) => { } }); -// Add CORS middleware app.use( '*', cors({ @@ -130,7 +124,6 @@ app.use( }), ); -// Connect endpoint /** * @openapi * /connect: @@ -474,7 +467,6 @@ app.put('/auth/display-mode', async (c) => { } }); -// Regenerate API key /** * @openapi * /auth/regenerate-api-key: @@ -569,7 +561,6 @@ app.post('/auth/regenerate-api-key', async (c) => { } }); -// Delete account /** * @openapi * /auth/delete: @@ -608,7 +599,6 @@ app.delete('/auth/delete', async (c) => { } }); -// Check if staff /** * @openapi * /auth/is-staff: @@ -649,7 +639,6 @@ app.get('/auth/is-staff', withCache(CacheKeys.withUser('is-staff'), 3600, 'auth' return c.json({ isStaff, role }); }); -// Airports endpoint /** * @openapi * /airports: @@ -716,7 +705,6 @@ app.get( }, ); -// Nearest airport (public, unauthenticated) /** * @openapi * /airports/nearest: @@ -784,7 +772,6 @@ app.get( }, ); -// Divisions routes const divisionsApp = new Hono<{ Bindings: Env; Variables: { @@ -795,7 +782,6 @@ const divisionsApp = new Hono<{ }; }>(); -// Middleware to get authenticated user for divisions divisionsApp.use('*', async (c, next) => { const vatsimToken = c.req.header('X-Vatsim-Token'); if (!vatsimToken) { @@ -819,7 +805,6 @@ divisionsApp.use('*', async (c, next) => { await next(); }); -// GET /divisions - List all divisions /** * @openapi * /divisions: @@ -841,7 +826,6 @@ divisionsApp.get('/', async (c) => { return c.json(allDivisions); }); -// POST /divisions - Create new division (requires lead_developer role) /** * @openapi * /divisions: @@ -885,7 +869,6 @@ divisionsApp.post('/', async (c) => { return c.json(division); }); -// PUT /divisions/:id - Update division name (lead_developer only) /** * @openapi * /divisions/{id}: @@ -938,7 +921,6 @@ divisionsApp.put('/:id', async (c) => { return c.json(updated); }); -// DELETE /divisions/:id - Delete division (lead_developer only) /** * @openapi * /divisions/{id}: @@ -978,7 +960,6 @@ divisionsApp.delete('/:id', async (c) => { return c.body(null, 204); }); -// GET /divisions/user - Get user's divisions /** * @openapi * /divisions/user: @@ -1000,7 +981,6 @@ divisionsApp.get('/user', withCache(CacheKeys.withUser('divisions'), 3600, 'divi return c.json(userDivisions); }); -// GET /divisions/:id - Get division details /** * @openapi * /divisions/{id}: @@ -1033,7 +1013,6 @@ divisionsApp.get('/:id', withCache(CacheKeys.fromParams('id'), 2592000, 'divisio return c.json(division); }); -// GET /divisions/:id/members - List division members /** * @openapi * /divisions/{id}/members: @@ -1068,7 +1047,6 @@ divisionsApp.get('/:id/members', async (c) => { return c.json(members); }); -// POST /divisions/:id/members - Add member (requires nav_head role) /** * @openapi * /divisions/{id}/members: @@ -1123,7 +1101,6 @@ divisionsApp.post('/:id/members', async (c) => { return c.json(member); }); -// DELETE /divisions/:id/members/:vatsimId - Remove member (requires nav_head role) /** * @openapi * /divisions/{id}/members/{vatsimId}: @@ -1175,7 +1152,6 @@ divisionsApp.delete('/:id/members/:vatsimId', async (c) => { return c.body(null, 204); }); -// GET /divisions/:id/airports - List division airports /** * @openapi * /divisions/{id}/airports: @@ -1210,7 +1186,6 @@ divisionsApp.get('/:id/airports', withCache(CacheKeys.fromParams('id'), 600, 'di return c.json(airports); }); -// POST /divisions/:id/airports - Request airport addition (requires division membership) /** * @openapi * /divisions/{id}/airports: @@ -1590,7 +1565,6 @@ app.delete('/airports/:icao/points/:id', async (c) => { } }); -// Get single point by ID /** * @openapi * /points/{id}: @@ -1715,7 +1689,6 @@ app.get('/points', withCache(CacheKeys.fromUrl, 3600, 'points'), async (c) => { }); }); -// MSFS Light Supports and BARS XML generation endpoint /** * @openapi * /supports/generate: @@ -1786,7 +1759,6 @@ app.post('/supports/generate', async (c) => { } }); -// NOTAM endpoints /** * @openapi * /notam: @@ -1874,7 +1846,6 @@ app.put('/notam', async (c) => { return c.json({ success: true }); }); -// User management endpoints const staffUsersApp = new Hono<{ Bindings: Env; Variables: { @@ -1883,7 +1854,6 @@ const staffUsersApp = new Hono<{ }; }>(); -// Middleware to authenticate staff users staffUsersApp.use('*', async (c, next) => { const vatsimToken = c.req.header('X-Vatsim-Token'); if (!vatsimToken) { @@ -1906,7 +1876,6 @@ staffUsersApp.use('*', async (c, next) => { await next(); }); -// GET /staff/users - Get all users with pagination /** * @openapi * /staff/users: @@ -1940,7 +1909,6 @@ staffUsersApp.get('/', async (c) => { } }); -// GET /staff/users/search - Search for users /** * @openapi * /staff/users/search: @@ -1986,7 +1954,6 @@ staffUsersApp.get('/search', async (c) => { } }); -// POST /staff/users/refresh-api-token - Refresh a user's API token by VATSIM ID /** * @openapi * /staff/users/refresh-api-token: @@ -2253,9 +2220,6 @@ contributionsApp.get('/', async (c) => { return c.json(result); }); -// (Removed) contribution statistics endpoint - -// GET /contributions/leaderboard - Get top contributors /** * @openapi * /contributions/leaderboard: @@ -2277,7 +2241,6 @@ contributionsApp.get( }, ); -// GET /contributions/top-packages - Get a list of most used packages /** * @openapi * /contributions/top-packages: @@ -2299,7 +2262,6 @@ contributionsApp.get( }, ); -// POST /contributions - Create a new contribution /** * @openapi * /contributions: @@ -2359,7 +2321,6 @@ contributionsApp.post('/', async (c) => { } }); -// GET /contributions/user - Get user's contributions /** * @openapi * /contributions/user: @@ -2408,7 +2369,6 @@ contributionsApp.get('/user', async (c) => { return c.json(result); }); -// GET /contributions/:id - Get specific contribution /** * @openapi * /contributions/{id}: @@ -2557,10 +2517,8 @@ contributionsApp.delete('/:id', async (c) => { app.route('/contributions', contributionsApp); -// CDN Endpoints const cdnApp = new Hono<{ Bindings: Env }>(); -// Latest approved BARS map for an airport & specific package /** * @openapi * /maps/{icao}/packages/{package}/latest: @@ -2607,7 +2565,6 @@ app.get('/maps/:icao/packages/:package/latest', withCache(CacheKeys.fromUrl, 900 return stored; }); -// Special case for direct file downloads /** * @openapi * /cdn/files/{fileKey}: @@ -2647,7 +2604,6 @@ cdnApp.get('/files/*', async (c) => { return fileResponse; }); -// Handle file management endpoints /** * @openapi * /cdn/upload: @@ -2757,7 +2713,6 @@ cdnApp.post('/upload', async (c) => { } }); -// List files /** * @openapi * /cdn/files: @@ -2830,7 +2785,6 @@ cdnApp.get('/files', async (c) => { } }); -// Delete a file /** * @openapi * /cdn/files/{fileKey}: @@ -2915,7 +2869,6 @@ cdnApp.delete('/files/*', async (c) => { app.route('/cdn', cdnApp); -// EuroScope public file listing endpoint /** * @openapi * /euroscope/files/{icao}: @@ -2976,7 +2929,6 @@ app.get('/euroscope/files/:icao', async (c) => { } }); -// EuroScope file management endpoints const euroscopeApp = new Hono<{ Bindings: Env; Variables: { @@ -2985,7 +2937,6 @@ const euroscopeApp = new Hono<{ }; }>(); -// Middleware for EuroScope endpoints to authenticate users euroscopeApp.use('*', async (c, next) => { const vatsimToken = c.req.header('X-Vatsim-Token'); if (!vatsimToken) { @@ -3007,7 +2958,6 @@ euroscopeApp.use('*', async (c, next) => { await next(); }); -// POST /euroscope/upload - Upload files to ICAO-specific folders /** * @openapi * /euroscope/upload: @@ -3151,7 +3101,6 @@ euroscopeApp.post('/upload', async (c) => { } }); -// DELETE /euroscope/files/:icao/:filename - Delete a specific file /** * @openapi * /euroscope/files/{icao}/{filename}: @@ -3236,7 +3185,6 @@ euroscopeApp.delete('/files/:icao/:filename', async (c) => { } }); -// GET /euroscope/:icao/editable - Check if user has permission to edit files for an airport /** * @openapi * /euroscope/{icao}/editable: @@ -3293,7 +3241,6 @@ euroscopeApp.get('/:icao/editable', async (c) => { }); app.route('/euroscope', euroscopeApp); -// Installer / Releases endpoints /** * @openapi * /releases: @@ -3344,7 +3291,6 @@ app.get('/releases/latest', withCache(CacheKeys.fromUrl, 120, 'installer'), asyn const releasesService = ServicePool.getReleases(c.env); const latest = await releasesService.getLatest(product); if (!latest) return c.text('Not found', 404); - // Provide direct download URL via CDN domain const downloadUrl = new URL(`https://dev-cdn.stopbars.com/${latest.file_key}`, c.req.url).toString(); const imageUrl = latest.image_url ? new URL(latest.image_url, c.req.url).toString() : undefined; const { image_url: _omitImage, ...rest } = latest as any; @@ -3648,7 +3594,6 @@ app.post('/purge-cache', async (c) => { } }); -// Contributors endpoint /** * @openapi * /contributors: From f41563383635221a5253cca8836c3393ef42710d Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Thu, 14 Aug 2025 14:50:21 +0800 Subject: [PATCH 12/17] Remove unused PostHogService import for cleaner code --- src/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 9de2fdd..4dea44c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,7 +11,6 @@ import { UserService } from './services/users'; import { DatabaseContextFactory } from './services/database-context'; import { withCache, CacheKeys } from './services/cache'; import { ServicePool } from './services/service-pool'; -import { PostHogService } from './services/posthog'; import { sanitizeContributionXml } from './services/xml-sanitizer'; const POINT_ID_REGEX = /^[A-Z0-9-_]+$/; From af44b9188347906a68b0c531115acee5c4a1e1f6 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Sat, 16 Aug 2025 17:31:25 +0800 Subject: [PATCH 13/17] Add contact form endpoints and service for message handling --- openapi.json | 72 +++++++++++++++++++ schema.sql | 14 +++- src/index.ts | 136 +++++++++++++++++++++++++++++++++++ src/services/contact.ts | 52 ++++++++++++++ src/services/service-pool.ts | 8 +++ 5 files changed, 281 insertions(+), 1 deletion(-) create mode 100644 src/services/contact.ts diff --git a/openapi.json b/openapi.json index 60766cf..97a694c 100644 --- a/openapi.json +++ b/openapi.json @@ -91,6 +91,78 @@ } ], "paths": { + "/contact": { + "post": { + "summary": "Submit a contact form", + "tags": [ + "Contact" + ], + "description": "Public endpoint to submit a contact/support message. Limited to 1 submission per 24 hours per IP.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "email", + "topic", + "message" + ], + "properties": { + "email": { + "type": "string", + "format": "email" + }, + "topic": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Message stored" + }, + "400": { + "description": "Validation error" + }, + "429": { + "description": "Rate limited (already submitted within 24h)" + } + } + }, + "get": { + "summary": "List submitted contact messages", + "x-hidden": true, + "tags": [ + "Contact", + "Staff" + ], + "description": "Returns all contact messages (newest first). Requires Product Manager or higher.", + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Messages returned" + }, + "401": { + "description": "Unauthorized" + }, + "403": { + "description": "Forbidden" + } + } + } + }, "/connect": { "get": { "summary": "Establish a WebSocket for an airport", diff --git a/schema.sql b/schema.sql index 71e2a78..751c635 100644 --- a/schema.sql +++ b/schema.sql @@ -185,4 +185,16 @@ CREATE TABLE IF NOT EXISTS installer_releases ( UNIQUE(product, version) ); CREATE INDEX IF NOT EXISTS idx_installer_releases_product ON installer_releases(product); -CREATE INDEX IF NOT EXISTS idx_installer_releases_created_at ON installer_releases(created_at DESC); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_installer_releases_created_at ON installer_releases(created_at DESC); + +-- Contact messages table for public contact form submissions +CREATE TABLE IF NOT EXISTS contact_messages ( + id TEXT PRIMARY KEY, -- uuid + email TEXT NOT NULL, + topic TEXT NOT NULL, + message TEXT NOT NULL, + ip_address TEXT NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX IF NOT EXISTS idx_contact_messages_created_at ON contact_messages(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_contact_messages_ip_created ON contact_messages(ip_address, created_at DESC); \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 4dea44c..f9934c5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -70,6 +70,7 @@ const app = new Hono<{ auth?: any; vatsim?: any; userService?: any; + clientIp?: string; }; }>(); @@ -123,6 +124,140 @@ app.use( }), ); +// Extract client IP (best-effort) and attach to context +app.use('*', async (c, next) => { + const cf = c.req.header('CF-Connecting-IP'); + const real = c.req.header('X-Real-IP'); + const fwdFor = c.req.header('X-Forwarded-For'); + const forwarded = c.req.header('Forwarded'); + let ip: string | undefined = cf || real; + if (!ip && fwdFor) { + ip = fwdFor.split(',')[0].trim(); + } + if (!ip && forwarded) { + // Forwarded: for=1.2.3.4; proto=http; by=... + const match = forwarded.match(/for=([^;]+)/i); + if (match) ip = match[1].replace(/"/g, ''); + } + c.set('clientIp', ip || '0.0.0.0'); + await next(); +}); + +/** + * @openapi + * /contact: + * post: + * summary: Submit a contact form + * tags: + * - Contact + * description: Public endpoint to submit a contact/support message. Limited to 1 submission per 24 hours per IP. + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: [email, topic, message] + * properties: + * email: + * type: string + * format: email + * topic: + * type: string + * message: + * type: string + * responses: + * 201: + * description: Message stored + * 400: + * description: Validation error + * 429: + * description: Rate limited (already submitted within 24h) + */ +app.post('/contact', async (c) => { + const dbContext = DatabaseContextFactory.createRequestContext(c.env.DB, c.req.raw); + try { + let body: any; + try { + body = await c.req.json(); + } catch { + return dbContext.jsonResponse({ error: 'Invalid JSON body' }, { status: 400 }); + } + const email = typeof body.email === 'string' ? body.email.trim() : ''; + const topic = typeof body.topic === 'string' ? body.topic.trim() : ''; + const message = typeof body.message === 'string' ? body.message.trim() : ''; + const ip = c.get('clientIp') || '0.0.0.0'; + + const emailRegex = /^[^@\s]+@[^@\s]+\.[^@\s]+$/; + if (!email || !emailRegex.test(email)) { + return dbContext.jsonResponse({ error: 'Invalid email' }, { status: 400 }); + } + if (!topic || topic.length < 3 || topic.length > 120) { + return dbContext.jsonResponse({ error: 'Invalid topic', message: 'topic must be 3-120 chars' }, { status: 400 }); + } + if (!message || message.length < 5 || message.length > 4000) { + return dbContext.jsonResponse({ error: 'Invalid message', message: 'message must be 5-4000 chars' }, { status: 400 }); + } + + const contact = ServicePool.getContact(c.env); + const already = await contact.hasRecentSubmissionFromIp(ip, 24); + if (already) { + return dbContext.jsonResponse( + { error: 'Rate limited', message: 'Only one submission per 24 hours from this IP' }, + { status: 429 }, + ); + } + const stored = await contact.createMessage(email, topic, message, ip); + return dbContext.jsonResponse({ success: true, id: stored.id, created_at: stored.created_at }, { status: 201 }); + } finally { + dbContext.close(); + } +}); + +/** + * @openapi + * /contact: + * get: + * summary: List submitted contact messages + * x-hidden: true + * tags: + * - Contact + * - Staff + * description: Returns all contact messages (newest first). Requires Product Manager or higher. + * security: + * - VatsimToken: [] + * responses: + * 200: + * description: Messages returned + * 401: + * description: Unauthorized + * 403: + * description: Forbidden + */ +app.get('/contact', async (c) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + + const dbContext = DatabaseContextFactory.createRequestContext(c.env.DB, c.req.raw); + try { + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return dbContext.textResponse('Unauthorized', { status: 401 }); + + const allowed = await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER); + if (!allowed) return dbContext.textResponse('Forbidden', { status: 403 }); + + const contact = ServicePool.getContact(c.env); + const messages = await contact.listMessages(); + return dbContext.jsonResponse({ messages }); + } finally { + dbContext.close(); + } +}); + /** * @openapi * /connect: @@ -1850,6 +1985,7 @@ const staffUsersApp = new Hono<{ Variables: { user?: any; userService?: any; + clientIp?: string; }; }>(); diff --git a/src/services/contact.ts b/src/services/contact.ts new file mode 100644 index 0000000..aecfdbb --- /dev/null +++ b/src/services/contact.ts @@ -0,0 +1,52 @@ +import { DatabaseSessionService } from './database-session'; + +export interface ContactMessageRecord { + id: string; + email: string; + topic: string; + message: string; + ip_address: string; + created_at: string; +} + +export class ContactService { + private dbSession: DatabaseSessionService; + constructor(private db: D1Database) { + this.dbSession = new DatabaseSessionService(db); + } + + async createMessage(email: string, topic: string, message: string, ip: string): Promise { + const id = crypto.randomUUID(); + await this.dbSession.executeWrite( + `INSERT INTO contact_messages (id, email, topic, message, ip_address, created_at) VALUES (?, ?, ?, ?, ?, datetime('now'))`, + [id, email, topic, message, ip], + ); + const created = await this.getMessage(id); + if (!created) throw new Error('Failed to create contact message'); + return created; + } + + async getMessage(id: string): Promise { + const res = await this.dbSession.executeRead( + `SELECT id, email, topic, message, ip_address, created_at FROM contact_messages WHERE id = ?`, + [id], + ); + return res.results[0] || null; + } + + async listMessages(): Promise { + const res = await this.dbSession.executeRead( + `SELECT id, email, topic, message, ip_address, created_at FROM contact_messages ORDER BY datetime(created_at) DESC`, + [], + ); + return res.results; + } + + async hasRecentSubmissionFromIp(ip: string, withinHours = 24): Promise { + const res = await this.dbSession.executeRead<{ cnt: number }>( + `SELECT COUNT(*) as cnt FROM contact_messages WHERE ip_address = ? AND datetime(created_at) >= datetime('now', ?)`, + [ip, `-${withinHours} hours`], + ); + return (res.results[0]?.cnt || 0) > 0; + } +} diff --git a/src/services/service-pool.ts b/src/services/service-pool.ts index 3800640..46a26d1 100644 --- a/src/services/service-pool.ts +++ b/src/services/service-pool.ts @@ -16,6 +16,7 @@ import { GitHubService } from './github'; import { PostHogService } from './posthog'; import { FAQService } from './faqs'; import { ReleaseService } from './releases'; +import { ContactService } from './contact'; export const ServicePool = (() => { let vatsim: VatsimService; @@ -35,6 +36,7 @@ export const ServicePool = (() => { let posthog: PostHogService; let faqs: FAQService; let releases: ReleaseService; + let contact: ContactService; return { getVatsim(env: Env) { @@ -145,5 +147,11 @@ export const ServicePool = (() => { } return releases; }, + getContact(env: Env) { + if (!contact) { + contact = new ContactService(env.DB); + } + return contact; + }, }; })(); From 6df154408c059b40b49a791b517cdc0e53c90d59 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Sat, 16 Aug 2025 17:38:36 +0800 Subject: [PATCH 14/17] Add endpoints for updating and deleting contact messages, and enhance contact message schema --- openapi.json | 106 ++++++++++++++++++++++++++++++++++ schema.sql | 6 +- src/index.ts | 123 ++++++++++++++++++++++++++++++++++++++++ src/services/contact.ts | 30 +++++++++- 4 files changed, 261 insertions(+), 4 deletions(-) diff --git a/openapi.json b/openapi.json index 97a694c..aa5d1e6 100644 --- a/openapi.json +++ b/openapi.json @@ -163,6 +163,112 @@ } } }, + "/contact/{id}/status": { + "patch": { + "summary": "Update contact message status", + "x-hidden": true, + "tags": [ + "Contact", + "Staff" + ], + "description": "Set status to pending, handling, or handled. Requires Product Manager or higher.", + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "status" + ], + "properties": { + "status": { + "type": "string", + "enum": [ + "pending", + "handling", + "handled" + ] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Updated message returned" + }, + "400": { + "description": "Invalid status" + }, + "401": { + "description": "Unauthorized" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Message not found" + } + } + } + }, + "/contact/{id}": { + "delete": { + "summary": "Delete a contact message", + "x-hidden": true, + "tags": [ + "Contact", + "Staff" + ], + "description": "Permanently deletes a contact message. Requires Product Manager or higher.", + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Deleted" + }, + "401": { + "description": "Unauthorized" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Not found" + } + } + } + }, "/connect": { "get": { "summary": "Establish a WebSocket for an airport", diff --git a/schema.sql b/schema.sql index 751c635..a1b8281 100644 --- a/schema.sql +++ b/schema.sql @@ -194,7 +194,11 @@ CREATE TABLE IF NOT EXISTS contact_messages ( topic TEXT NOT NULL, message TEXT NOT NULL, ip_address TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','handling','handled')), + handled_by TEXT, + handled_at DATETIME, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX IF NOT EXISTS idx_contact_messages_created_at ON contact_messages(created_at DESC); -CREATE INDEX IF NOT EXISTS idx_contact_messages_ip_created ON contact_messages(ip_address, created_at DESC); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_contact_messages_ip_created ON contact_messages(ip_address, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_contact_messages_status ON contact_messages(status); \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index f9934c5..9a0742a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -258,6 +258,129 @@ app.get('/contact', async (c) => { } }); +/** + * @openapi + * /contact/{id}/status: + * patch: + * summary: Update contact message status + * x-hidden: true + * tags: + * - Contact + * - Staff + * description: Set status to pending, handling, or handled. Requires Product Manager or higher. + * security: + * - VatsimToken: [] + * parameters: + * - in: path + * name: id + * required: true + * schema: + * type: string + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: [status] + * properties: + * status: + * type: string + * enum: [pending, handling, handled] + * responses: + * 200: + * description: Updated message returned + * 400: + * description: Invalid status + * 401: + * description: Unauthorized + * 403: + * description: Forbidden + * 404: + * description: Message not found + */ +app.patch('/contact/:id/status', async (c) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + const id = c.req.param('id'); + const dbContext = DatabaseContextFactory.createRequestContext(c.env.DB, c.req.raw); + try { + let body: any; + try { body = await c.req.json(); } catch { return dbContext.jsonResponse({ error: 'Invalid JSON body' }, { status: 400 }); } + const status = body?.status; + if (!['pending', 'handling', 'handled'].includes(status)) { + return dbContext.jsonResponse({ error: 'Invalid status' }, { status: 400 }); + } + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return dbContext.textResponse('Unauthorized', { status: 401 }); + const allowed = await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER); + if (!allowed) return dbContext.textResponse('Forbidden', { status: 403 }); + const contact = ServicePool.getContact(c.env); + const existing = await contact.getMessage(id); + if (!existing) return dbContext.textResponse('Not found', { status: 404 }); + const updated = await contact.updateStatus(id, status, user.vatsim_id); + return dbContext.jsonResponse({ message: updated }); + } finally { + dbContext.close(); + } +}); + +/** + * @openapi + * /contact/{id}: + * delete: + * summary: Delete a contact message + * x-hidden: true + * tags: + * - Contact + * - Staff + * description: Permanently deletes a contact message. Requires Product Manager or higher. + * security: + * - VatsimToken: [] + * parameters: + * - in: path + * name: id + * required: true + * schema: + * type: string + * responses: + * 204: + * description: Deleted + * 401: + * description: Unauthorized + * 403: + * description: Forbidden + * 404: + * description: Not found + */ +app.delete('/contact/:id', async (c) => { + const vatsimToken = c.req.header('X-Vatsim-Token'); + if (!vatsimToken) return c.text('Unauthorized', 401); + const id = c.req.param('id'); + const dbContext = DatabaseContextFactory.createRequestContext(c.env.DB, c.req.raw); + try { + const vatsim = ServicePool.getVatsim(c.env); + const auth = ServicePool.getAuth(c.env); + const roles = ServicePool.getRoles(c.env); + const vatsimUser = await vatsim.getUser(vatsimToken); + const user = await auth.getUserByVatsimId(vatsimUser.id); + if (!user) return dbContext.textResponse('Unauthorized', { status: 401 }); + const allowed = await roles.hasPermission(user.id, StaffRole.PRODUCT_MANAGER); + if (!allowed) return dbContext.textResponse('Forbidden', { status: 403 }); + const contact = ServicePool.getContact(c.env); + const existing = await contact.getMessage(id); + if (!existing) return dbContext.textResponse('Not found', { status: 404 }); + await contact.deleteMessage(id); + return dbContext.textResponse('', { status: 204 }); + } finally { + dbContext.close(); + } +}); + /** * @openapi * /connect: diff --git a/src/services/contact.ts b/src/services/contact.ts index aecfdbb..476df32 100644 --- a/src/services/contact.ts +++ b/src/services/contact.ts @@ -6,6 +6,9 @@ export interface ContactMessageRecord { topic: string; message: string; ip_address: string; + status: 'pending' | 'handling' | 'handled'; + handled_by: string | null; + handled_at: string | null; created_at: string; } @@ -18,7 +21,7 @@ export class ContactService { async createMessage(email: string, topic: string, message: string, ip: string): Promise { const id = crypto.randomUUID(); await this.dbSession.executeWrite( - `INSERT INTO contact_messages (id, email, topic, message, ip_address, created_at) VALUES (?, ?, ?, ?, ?, datetime('now'))`, + `INSERT INTO contact_messages (id, email, topic, message, ip_address, status, created_at) VALUES (?, ?, ?, ?, ?, 'pending', datetime('now'))`, [id, email, topic, message, ip], ); const created = await this.getMessage(id); @@ -28,7 +31,7 @@ export class ContactService { async getMessage(id: string): Promise { const res = await this.dbSession.executeRead( - `SELECT id, email, topic, message, ip_address, created_at FROM contact_messages WHERE id = ?`, + `SELECT id, email, topic, message, ip_address, status, handled_by, handled_at, created_at FROM contact_messages WHERE id = ?`, [id], ); return res.results[0] || null; @@ -36,12 +39,33 @@ export class ContactService { async listMessages(): Promise { const res = await this.dbSession.executeRead( - `SELECT id, email, topic, message, ip_address, created_at FROM contact_messages ORDER BY datetime(created_at) DESC`, + `SELECT id, email, topic, message, ip_address, status, handled_by, handled_at, created_at FROM contact_messages ORDER BY datetime(created_at) DESC`, [], ); return res.results; } + async updateStatus(id: string, status: 'pending' | 'handling' | 'handled', handlerVatsimId: string): Promise { + // handled_by/handled_at only set when moving to handled, if returning to pending/handling clear handled_at but keep who last handled + if (status === 'handled') { + await this.dbSession.executeWrite( + `UPDATE contact_messages SET status = ?, handled_by = ?, handled_at = datetime('now') WHERE id = ?`, + [status, handlerVatsimId, id], + ); + } else { + await this.dbSession.executeWrite( + `UPDATE contact_messages SET status = ?, handled_at = NULL WHERE id = ?`, + [status, id], + ); + } + return this.getMessage(id); + } + + async deleteMessage(id: string): Promise { + const res = await this.dbSession.executeWrite(`DELETE FROM contact_messages WHERE id = ?`, [id]); + return !!res.success; + } + async hasRecentSubmissionFromIp(ip: string, withinHours = 24): Promise { const res = await this.dbSession.executeRead<{ cnt: number }>( `SELECT COUNT(*) as cnt FROM contact_messages WHERE ip_address = ? AND datetime(created_at) >= datetime('now', ?)`, From 5f097e22e1862cad06ad382f3d761da19fda3f82 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Sun, 17 Aug 2025 11:13:12 +0800 Subject: [PATCH 15/17] Update CORS middleware to allow PATCH method for enhanced API flexibility --- src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 9a0742a..483308e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -120,7 +120,7 @@ app.use( cors({ origin: '*', allowHeaders: ['Content-Type', 'Authorization', 'X-Vatsim-Token', 'Upgrade', 'X-Client-Type'], - allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], }), ); From 7155ce4672db546596c73f2393fd7278f2d4a551 Mon Sep 17 00:00:00 2001 From: AussieScorcher Date: Sun, 17 Aug 2025 11:40:25 +0800 Subject: [PATCH 16/17] Enhance product support in API and database schema by adding 'Installer' and 'SimConnect.NET' options, and update related documentation and validation logic. --- openapi.json | 16 +++++-- schema.sql | 2 +- src/index.ts | 87 +++++++++++++++++++++++++++------------ src/services/releases.ts | 2 +- worker-configuration.d.ts | 6 +-- 5 files changed, 79 insertions(+), 34 deletions(-) diff --git a/openapi.json b/openapi.json index aa5d1e6..3fb731e 100644 --- a/openapi.json +++ b/openapi.json @@ -2150,7 +2150,9 @@ "enum": [ "Pilot-Client", "vatSys-Plugin", - "EuroScope-Plugin" + "EuroScope-Plugin", + "Installer", + "SimConnect.NET" ] } } @@ -2178,7 +2180,9 @@ "enum": [ "Pilot-Client", "vatSys-Plugin", - "EuroScope-Plugin" + "EuroScope-Plugin", + "Installer", + "SimConnect.NET" ] } } @@ -2226,7 +2230,9 @@ "enum": [ "Pilot-Client", "vatSys-Plugin", - "EuroScope-Plugin" + "EuroScope-Plugin", + "Installer", + "SimConnect.NET" ] }, "version": { @@ -2245,6 +2251,10 @@ } } }, + "x-notes": [ + "Product \"Installer\" requires an .exe file upload.", + "Product \"SimConnect.NET\" does not require a file upload (metadata + changelog only; version links to NuGet)." + ], "responses": { "201": { "description": "Release created" diff --git a/schema.sql b/schema.sql index a1b8281..9531d4d 100644 --- a/schema.sql +++ b/schema.sql @@ -174,7 +174,7 @@ CREATE INDEX IF NOT EXISTS idx_faqs_order ON faqs(order_position ASC); -- Installer releases table for distributable products CREATE TABLE IF NOT EXISTS installer_releases ( id INTEGER PRIMARY KEY AUTOINCREMENT, - product TEXT NOT NULL, -- Pilot-Client | vatSys-Plugin | EuroScope-Plugin + product TEXT NOT NULL, -- Pilot-Client | vatSys-Plugin | EuroScope-Plugin | Installer | SimConnect.NET (external NuGet, no binary stored) version TEXT NOT NULL, file_key TEXT NOT NULL, file_size INTEGER NOT NULL, diff --git a/src/index.ts b/src/index.ts index 483308e..187b721 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3509,7 +3509,7 @@ app.route('/euroscope', euroscopeApp); * parameters: * - in: query * name: product - * schema: { type: string, enum: [Pilot-Client, vatSys-Plugin, EuroScope-Plugin] } + * schema: { type: string, enum: [Pilot-Client, vatSys-Plugin, EuroScope-Plugin, Installer, SimConnect.NET] } * responses: * 200: * description: Releases listed @@ -3536,7 +3536,7 @@ app.get( * - in: query * name: product * required: true - * schema: { type: string, enum: [Pilot-Client, vatSys-Plugin, EuroScope-Plugin] } + * schema: { type: string, enum: [Pilot-Client, vatSys-Plugin, EuroScope-Plugin, Installer, SimConnect.NET] } * responses: * 200: * description: Latest release returned @@ -3549,7 +3549,9 @@ app.get('/releases/latest', withCache(CacheKeys.fromUrl, 120, 'installer'), asyn const releasesService = ServicePool.getReleases(c.env); const latest = await releasesService.getLatest(product); if (!latest) return c.text('Not found', 404); - const downloadUrl = new URL(`https://dev-cdn.stopbars.com/${latest.file_key}`, c.req.url).toString(); + const downloadUrl = product === 'SimConnect.NET' + ? `https://www.nuget.org/packages/SimConnect.NET/${latest.version}` + : new URL(`https://dev-cdn.stopbars.com/${latest.file_key}`, c.req.url).toString(); const imageUrl = latest.image_url ? new URL(latest.image_url, c.req.url).toString() : undefined; const { image_url: _omitImage, ...rest } = latest as any; return c.json({ ...rest, downloadUrl, imageUrl }); @@ -3578,7 +3580,7 @@ app.get('/releases/latest', withCache(CacheKeys.fromUrl, 120, 'installer'), asyn * format: binary * product: * type: string - * enum: [Pilot-Client, vatSys-Plugin, EuroScope-Plugin] + * enum: [Pilot-Client, vatSys-Plugin, EuroScope-Plugin, Installer, SimConnect.NET] * version: * type: string * changelog: @@ -3587,6 +3589,9 @@ app.get('/releases/latest', withCache(CacheKeys.fromUrl, 120, 'installer'), asyn * type: string * format: binary * description: Optional promotional image (PNG/JPEG, max 5MB) + * x-notes: + * - Product "Installer" requires an .exe file upload. + * - Product "SimConnect.NET" does not require a file upload (metadata + changelog only; version links to NuGet). * responses: * 201: * description: Release created @@ -3599,8 +3604,6 @@ app.post('/releases/upload', async (c) => { const vatsim = ServicePool.getVatsim(c.env); const auth = ServicePool.getAuth(c.env); const roles = ServicePool.getRoles(c.env); - - // Start remote VATSIM lookup early while we parse form data (minor latency win) const vatsimUserPromise = vatsim.getUser(vatsimToken); let formData: FormData; @@ -3615,8 +3618,6 @@ app.post('/releases/upload', async (c) => { const version = formData.get('version')?.toString(); const changelog = formData.get('changelog')?.toString(); const image = formData.get('image'); - - // Await user info only after fast local parsing work is done let vatsimUser; try { vatsimUser = await vatsimUserPromise; @@ -3628,21 +3629,49 @@ app.post('/releases/upload', async (c) => { const isLeadDev = await roles.hasPermission(user.id, StaffRole.LEAD_DEVELOPER); if (!isLeadDev) return c.text('Forbidden', 403); - if (!file || !(file instanceof File)) return c.json({ error: 'file required' }, 400); if (!product || !version) return c.json({ error: 'product & version required' }, 400); - const MAX = 90 * 1024 * 1024; - if (file.size > MAX) return c.json({ error: 'File too large (90MB max)' }, 400); + + const isSimConnect = product === 'SimConnect.NET'; + const isInstallerExe = product === 'Installer'; + + if (!isSimConnect) { + // For all products except SimConnect.NET a file is required + if (!file || !(file instanceof File)) return c.json({ error: 'file required' }, 400); + const MAX = 90 * 1024 * 1024; + if (file.size > MAX) return c.json({ error: 'File too large (90MB max)' }, 400); + if (isInstallerExe) { + // Enforce .exe extension for Installer product + const lower = file.name.toLowerCase(); + if (!lower.endsWith('.exe')) return c.json({ error: 'Installer product must be a .exe file' }, 400); + } + } + + if (isSimConnect && file && file instanceof File) { + return c.json({ error: 'SimConnect.NET releases do not accept file uploads' }, 400); + } try { const storage = ServicePool.getStorage(c.env); - const fileKey = `releases/${product}/${version}/${file.name}`; - const bytes = await file.arrayBuffer(); + let fileKey: string; + let bytes: ArrayBuffer | undefined; + if (!isSimConnect) { + // File upload path for normal products + const uploadFile = file as File; // already validated + fileKey = `releases/${product}/${version}/${uploadFile.name}`; + bytes = await uploadFile.arrayBuffer(); + } else { + // Sentinel key for external NuGet package (no bytes) + fileKey = `releases/${product}/${version}/EXTERNAL`; + } let imageBytesPromise: Promise | undefined; if (image && image instanceof File) { imageBytesPromise = image.arrayBuffer(); } - const digest = await crypto.subtle.digest('SHA-256', bytes); - const sha256 = Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join(''); + let sha256 = 'external'; + if (bytes) { + const digest = await crypto.subtle.digest('SHA-256', bytes); + sha256 = Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join(''); + } // Validate image (after its bytes read started) before uploads let imageUrl: string | undefined; @@ -3664,26 +3693,32 @@ app.post('/releases/upload', async (c) => { }); imageUrl = `https://dev-cdn.stopbars.com/${imageKey}`; } - const fileUploadPromise = storage.uploadFile(fileKey, bytes, file.type || 'application/zip', { - uploadedBy: user.vatsim_id, - product, - version, - size: file.size.toString(), - sha256 - }); - - await Promise.all([fileUploadPromise, imageUploadPromise].filter(Boolean)); + if (!isSimConnect) { + const uploadFile = file as File; + const fileUploadPromise = storage.uploadFile(fileKey, bytes!, uploadFile.type || 'application/octet-stream', { + uploadedBy: user.vatsim_id, + product, + version, + size: uploadFile.size.toString(), + sha256 + }); + await Promise.all([fileUploadPromise, imageUploadPromise].filter(Boolean)); + } else { + // Only image upload (if any) for external product + if (imageUploadPromise) await imageUploadPromise; + } const releasesService = ServicePool.getReleases(c.env); const release = await releasesService.createRelease({ product, version, fileKey, - fileSize: file.size, + fileSize: bytes ? (file as File).size : 0, fileHash: sha256, changelog, imageUrl }); - return c.json({ success: true, release, downloadUrl: `https://dev-cdn.stopbars.com/${fileKey}`, imageUrl }, 201); + const downloadUrl = isSimConnect ? `https://www.nuget.org/packages/SimConnect.NET/${version}` : `https://dev-cdn.stopbars.com/${fileKey}`; + return c.json({ success: true, release, downloadUrl, imageUrl }, 201); } catch (err) { console.error('Release upload error', err); return c.json({ error: err instanceof Error ? err.message : 'upload failed' }, 500); diff --git a/src/services/releases.ts b/src/services/releases.ts index 3654c81..db6fba5 100644 --- a/src/services/releases.ts +++ b/src/services/releases.ts @@ -1,7 +1,7 @@ import { DatabaseSessionService } from './database-session'; import { StorageService } from './storage'; -export type InstallerProduct = 'Pilot-Client' | 'vatSys-Plugin' | 'EuroScope-Plugin'; +export type InstallerProduct = 'Pilot-Client' | 'vatSys-Plugin' | 'EuroScope-Plugin' | 'Installer' | 'SimConnect.NET'; export interface ReleaseRecord { id: number; product: InstallerProduct; diff --git a/worker-configuration.d.ts b/worker-configuration.d.ts index 69ccb50..ae72318 100644 --- a/worker-configuration.d.ts +++ b/worker-configuration.d.ts @@ -3,11 +3,11 @@ // Runtime types generated with workerd@1.20250803.0 2024-12-18 nodejs_compat declare namespace Cloudflare { interface Env { - VATSIM_CLIENT_ID: '1562'; - POSTHOG_HOST: 'https://eu.i.posthog.com'; + VATSIM_CLIENT_ID: "1562"; + POSTHOG_HOST: "https://eu.i.posthog.com"; VATSIM_CLIENT_SECRET: string; AIRPORTDB_API_KEY: string; - BARS: DurableObjectNamespace; + BARS: DurableObjectNamespace; BARS_STORAGE: R2Bucket; DB: D1Database; } From 060b8768cdda69453a33b35d8dfe936a674d9fe3 Mon Sep 17 00:00:00 2001 From: openapi-bot Date: Tue, 19 Aug 2025 10:04:39 +0000 Subject: [PATCH 17/17] chore: update openapi spec --- openapi.json | 5438 ++++++++++++++++++++++++-------------------------- 1 file changed, 2574 insertions(+), 2864 deletions(-) diff --git a/openapi.json b/openapi.json index 3fb731e..1cba543 100644 --- a/openapi.json +++ b/openapi.json @@ -1,2865 +1,2575 @@ { - "openapi": "3.0.4", - "info": { - "title": "BARS Core API", - "version": "2.0.0", - "description": "API documentation for BARS Core", - "contact": { - "name": "BARS Support", - "email": "support@stopbars.com", - "url": "https://stopbars.com/support" - } - }, - "externalDocs": { - "description": "Find more info here", - "url": "https://docs.stopbars.com" - }, - "servers": [ - { - "url": "https://v2.stopbars.com", - "description": "Production" - }, - { - "url": "http://localhost:8787", - "description": "Local development (wrangler dev)" - } - ], - "tags": [ - { - "name": "RealTime", - "description": "WebSocket connection and real-time state interaction endpoints." - }, - { - "name": "State", - "description": "Endpoints for retrieving current system or airport lighting/network state." - }, - { - "name": "Auth", - "description": "Authentication, account management, and API key lifecycle." - }, - { - "name": "Airports", - "description": "Lookup and metadata endpoints for airports." - }, - { - "name": "Divisions", - "description": "Division management, membership, and associated airport access." - }, - { - "name": "Points", - "description": "Creation and management of lighting/navigation point data." - }, - { - "name": "Generation", - "description": "Utilities for generating light support / BARS XML artifacts." - }, - { - "name": "NOTAM", - "description": "Global NOTAM retrieval and (staff) updates." - }, - { - "name": "Contributions", - "description": "Community lighting package submission, review, and leaderboard." - }, - { - "name": "Staff", - "description": "Restricted staff-only operational and moderation endpoints (hidden from public docs)." - }, - { - "name": "CDN", - "description": "File storage, upload, listing, and deletion via CDN-backed storage." - }, - { - "name": "FAQ", - "description": "Frequently Asked Questions (FAQ) management and retrieval." - }, - { - "name": "EuroScope", - "description": "EuroScope sector file upload, listing, and permission checks by ICAO." - }, - { - "name": "Cache", - "description": "Administrative cache management operations." - }, - { - "name": "GitHub", - "description": "Repository contributor information." - }, - { - "name": "System", - "description": "System health and OpenAPI specification discovery." - } - ], - "paths": { - "/contact": { - "post": { - "summary": "Submit a contact form", - "tags": [ - "Contact" - ], - "description": "Public endpoint to submit a contact/support message. Limited to 1 submission per 24 hours per IP.", - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "email", - "topic", - "message" - ], - "properties": { - "email": { - "type": "string", - "format": "email" - }, - "topic": { - "type": "string" - }, - "message": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "201": { - "description": "Message stored" - }, - "400": { - "description": "Validation error" - }, - "429": { - "description": "Rate limited (already submitted within 24h)" - } - } - }, - "get": { - "summary": "List submitted contact messages", - "x-hidden": true, - "tags": [ - "Contact", - "Staff" - ], - "description": "Returns all contact messages (newest first). Requires Product Manager or higher.", - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Messages returned" - }, - "401": { - "description": "Unauthorized" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/contact/{id}/status": { - "patch": { - "summary": "Update contact message status", - "x-hidden": true, - "tags": [ - "Contact", - "Staff" - ], - "description": "Set status to pending, handling, or handled. Requires Product Manager or higher.", - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "status" - ], - "properties": { - "status": { - "type": "string", - "enum": [ - "pending", - "handling", - "handled" - ] - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Updated message returned" - }, - "400": { - "description": "Invalid status" - }, - "401": { - "description": "Unauthorized" - }, - "403": { - "description": "Forbidden" - }, - "404": { - "description": "Message not found" - } - } - } - }, - "/contact/{id}": { - "delete": { - "summary": "Delete a contact message", - "x-hidden": true, - "tags": [ - "Contact", - "Staff" - ], - "description": "Permanently deletes a contact message. Requires Product Manager or higher.", - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "204": { - "description": "Deleted" - }, - "401": { - "description": "Unauthorized" - }, - "403": { - "description": "Forbidden" - }, - "404": { - "description": "Not found" - } - } - } - }, - "/connect": { - "get": { - "summary": "Establish a WebSocket for an airport", - "tags": [ - "RealTime" - ], - "description": "Performs a WebSocket upgrade to stream real-time airport state. Requires:\n- GET with `Upgrade: websocket`\n- `airport` (ICAO, 4 chars) & `key` (API key) query params\nThe API key is forwarded as a Bearer token to the airport's Durable Object for auth.\n", - "parameters": [ - { - "in": "query", - "name": "airport", - "required": true, - "description": "Airport ICAO (4 alphanumeric characters)", - "schema": { - "type": "string", - "minLength": 4, - "maxLength": 4, - "pattern": "^[A-Z0-9]{4}$" - } - }, - { - "in": "query", - "name": "key", - "required": true, - "description": "User API key", - "schema": { - "type": "string" - } - } - ], - "responses": { - "101": { - "description": "WebSocket upgrade accepted" - }, - "400": { - "description": "Missing/invalid params or not a WebSocket upgrade" - }, - "401": { - "description": "API key rejected" - } - } - } - }, - "/state": { - "get": { - "summary": "Get current lighting/network state", - "tags": [ - "State" - ], - "description": "Retrieves real-time state for a specific airport or all active airports.", - "parameters": [ - { - "in": "query", - "name": "airport", - "required": true, - "description": "ICAO code of airport or 'all' for every active airport", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "State information returned" - }, - "400": { - "description": "Missing or invalid airport parameter" - } - } - } - }, - "/auth/vatsim/callback": { - "get": { - "summary": "VATSIM OAuth callback", - "tags": [ - "Auth" - ], - "description": "Exchanges authorization code for a VATSIM token and redirects to frontend with token.", - "parameters": [ - { - "in": "query", - "name": "code", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "302": { - "description": "Redirect to application with token or error" - }, - "400": { - "description": "Missing code parameter" - } - } - } - }, - "/auth/account": { - "get": { - "summary": "Get authenticated account information", - "tags": [ - "Auth" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Account found" - }, - "401": { - "description": "Missing or invalid token" - }, - "404": { - "description": "User not found" - } - } - } - }, - "/auth/display-mode": { - "put": { - "summary": "Update preferred display name mode", - "tags": [ - "Auth" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "mode" - ], - "properties": { - "mode": { - "type": "integer", - "enum": [ - 0, - 1, - 2 - ], - "description": "0=First,1=First LastInitial,2=CID" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Updated" - } - } - } - }, - "/auth/regenerate-api-key": { - "post": { - "summary": "Regenerate API key", - "tags": [ - "Auth" - ], - "description": "Generates a new API key for the authenticated user (24h cooldown).", - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Key regenerated" - }, - "401": { - "description": "Unauthorized" - }, - "404": { - "description": "User not found" - }, - "429": { - "description": "Rate limited (cooldown not elapsed)" - } - } - } - }, - "/auth/delete": { - "delete": { - "summary": "Delete current user account", - "tags": [ - "Auth" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "204": { - "description": "Account deleted" - }, - "401": { - "description": "Unauthorized" - }, - "404": { - "description": "User not found" - } - } - } - }, - "/auth/is-staff": { - "get": { - "x-hidden": true, - "summary": "Check staff status", - "tags": [ - "Staff" - ], - "security": [ - { - "ApiKeyAuth": [] - } - ], - "responses": { - "200": { - "description": "Staff status returned" - }, - "401": { - "description": "Unauthorized" - } - } - } - }, - "/airports": { - "get": { - "summary": "Get airport data", - "tags": [ - "Airports" - ], - "description": "Fetch airport(s) by ICAO(s) or by continent.", - "parameters": [ - { - "in": "query", - "name": "icao", - "required": false, - "description": "Single ICAO or comma-separated list", - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "continent", - "required": false, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Airport data returned" - }, - "400": { - "description": "Invalid parameters" - }, - "404": { - "description": "Airport not found" - } - } - } - }, - "/airports/nearest": { - "get": { - "summary": "Find nearest airport", - "tags": [ - "Airports" - ], - "description": "Returns the nearest airport to a given latitude/longitude. Results are cached in 5NM buckets for high performance.", - "parameters": [ - { - "in": "query", - "name": "lat", - "required": true, - "description": "Latitude in decimal degrees (-90 to 90)", - "schema": { - "type": "number" - } - }, - { - "in": "query", - "name": "lon", - "required": true, - "description": "Longitude in decimal degrees (-180 to 180)", - "schema": { - "type": "number" - } - } - ], - "responses": { - "200": { - "description": "Nearest airport returned" - }, - "400": { - "description": "Invalid coordinates" - }, - "404": { - "description": "No airport found" - } - } - } - }, - "/divisions": { - "get": { - "summary": "List all divisions", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Divisions returned" - }, - "401": { - "description": "Unauthorized" - } - } - }, - "post": { - "x-hidden": true, - "summary": "Create a new division", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "name", - "headVatsimId" - ], - "properties": { - "name": { - "type": "string" - }, - "headVatsimId": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Division created" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/divisions/{id}": { - "put": { - "x-hidden": true, - "summary": "Update division name", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Division updated" - }, - "403": { - "description": "Forbidden" - }, - "404": { - "description": "Division not found" - } - } - }, - "delete": { - "x-hidden": true, - "summary": "Delete a division", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "responses": { - "204": { - "description": "Division deleted" - }, - "403": { - "description": "Forbidden" - }, - "404": { - "description": "Division not found" - } - } - }, - "get": { - "summary": "Get division details", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "Division returned" - }, - "404": { - "description": "Division not found" - } - } - } - }, - "/divisions/user": { - "get": { - "summary": "Get divisions for current user", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "User divisions returned" - } - } - } - }, - "/divisions/{id}/members": { - "get": { - "summary": "List division members", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "Members listed" - }, - "404": { - "description": "Division not found" - } - } - }, - "post": { - "x-hidden": true, - "summary": "Add member to division", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "vatsimId", - "role" - ], - "properties": { - "vatsimId": { - "type": "string" - }, - "role": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Member added" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/divisions/{id}/members/{vatsimId}": { - "delete": { - "x-hidden": true, - "summary": "Remove member from division", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - }, - { - "in": "path", - "name": "vatsimId", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "204": { - "description": "Member removed" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/divisions/{id}/airports": { - "get": { - "summary": "List division airports", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "Airports listed" - }, - "404": { - "description": "Division not found" - } - } - }, - "post": { - "x-hidden": true, - "summary": "Request airport addition to division", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "icao" - ], - "properties": { - "icao": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Airport request created" - }, - "404": { - "description": "Division not found" - } - } - } - }, - "/divisions/{id}/airports/{airportId}/approve": { - "post": { - "x-hidden": true, - "summary": "Approve or reject airport request", - "tags": [ - "Divisions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - }, - { - "in": "path", - "name": "airportId", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "approved" - ], - "properties": { - "approved": { - "type": "boolean" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Airport approval processed" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/airports/{icao}/points": { - "get": { - "summary": "List lighting/navigation points for airport", - "tags": [ - "Points" - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string", - "minLength": 4, - "maxLength": 4 - } - } - ], - "responses": { - "200": { - "description": "Points returned" - }, - "400": { - "description": "Invalid ICAO" - } - } - }, - "post": { - "x-hidden": true, - "summary": "Create a single point", - "tags": [ - "Points" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PointData" - } - } - } - }, - "responses": { - "201": { - "description": "Point created" - }, - "401": { - "description": "Unauthorized" - } - } - } - }, - "/airports/{icao}/points/batch": { - "post": { - "x-hidden": true, - "summary": "Apply a batch point changeset", - "tags": [ - "Points" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PointChangeset" - } - } - } - }, - "responses": { - "201": { - "description": "Changeset applied" - } - } - } - }, - "/airports/{icao}/points/{id}": { - "put": { - "x-hidden": true, - "summary": "Update a point", - "tags": [ - "Points" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object" - } - } - } - }, - "responses": { - "200": { - "description": "Point updated" - } - } - }, - "delete": { - "x-hidden": true, - "summary": "Delete a point", - "tags": [ - "Points" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "204": { - "description": "Deleted" - } - } - } - }, - "/points/{id}": { - "get": { - "summary": "Get a single point by ID", - "tags": [ - "Points" - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Point found" - }, - "404": { - "description": "Not found" - } - } - } - }, - "/points": { - "get": { - "summary": "Get multiple points by IDs", - "tags": [ - "Points" - ], - "parameters": [ - { - "in": "query", - "name": "ids", - "required": true, - "description": "Comma-separated list of point IDs (max 100)", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Points returned" - }, - "400": { - "description": "Validation error" - } - } - } - }, - "/supports/generate": { - "post": { - "summary": "Generate Light Supports and BARS XML", - "tags": [ - "Generation" - ], - "description": "Upload raw XML and generate both light supports XML and processed BARS XML.", - "requestBody": { - "required": true, - "content": { - "multipart/form-data": { - "schema": { - "type": "object", - "required": [ - "xmlFile", - "icao" - ], - "properties": { - "xmlFile": { - "type": "string", - "format": "binary" - }, - "icao": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Generated XML returned" - }, - "400": { - "description": "Validation error" - } - } - } - }, - "/notam": { - "get": { - "summary": "Get global NOTAM", - "tags": [ - "NOTAM" - ], - "responses": { - "200": { - "description": "Current NOTAM returned" - } - } - }, - "put": { - "x-hidden": true, - "summary": "Update global NOTAM", - "tags": [ - "NOTAM" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "content" - ], - "properties": { - "content": { - "type": "string" - }, - "type": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "NOTAM updated" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/staff/users": { - "get": { - "x-hidden": true, - "summary": "List users (staff only)", - "tags": [ - "Staff" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Users returned" - }, - "401": { - "description": "Unauthorized" - } - } - } - }, - "/staff/users/search": { - "get": { - "x-hidden": true, - "summary": "Search users (staff only)", - "tags": [ - "Staff" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "query", - "name": "q", - "required": true, - "schema": { - "type": "string", - "minLength": 3 - } - } - ], - "responses": { - "200": { - "description": "Search results returned" - }, - "400": { - "description": "Invalid query" - } - } - } - }, - "/staff/users/refresh-api-token": { - "post": { - "x-hidden": true, - "summary": "Refresh a user's API token (staff only)", - "tags": [ - "Staff" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "vatsimId" - ], - "properties": { - "vatsimId": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Token refreshed" - } - } - } - }, - "/staff/users/{id}": { - "delete": { - "x-hidden": true, - "summary": "Delete a user (staff only)", - "tags": [ - "Staff" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "responses": { - "200": { - "description": "User deletion result" - } - } - } - }, - "/staff/manage": { - "get": { - "x-hidden": true, - "summary": "List staff members", - "tags": [ - "Staff" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "responses": { - "200": { - "description": "Staff listed" - }, - "403": { - "description": "Forbidden" - } - } - }, - "post": { - "x-hidden": true, - "summary": "Add or update a staff member", - "tags": [ - "Staff" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "vatsimId", - "role" - ], - "properties": { - "vatsimId": { - "type": "string" - }, - "role": { - "type": "string", - "enum": [ - "LEAD_DEVELOPER", - "PRODUCT_MANAGER" - ] - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Staff added/updated" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/staff/manage/{vatsimId}": { - "delete": { - "x-hidden": true, - "summary": "Remove staff member", - "tags": [ - "Staff" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "vatsimId", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Staff removed" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/contributions": { - "get": { - "summary": "List contributions", - "tags": [ - "Contributions" - ], - "parameters": [ - { - "in": "query", - "name": "status", - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "airport", - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "user", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Contributions listed" - } - } - }, - "post": { - "summary": "Submit a new contribution", - "tags": [ - "Contributions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "airportIcao", - "packageName", - "submittedXml" - ], - "properties": { - "airportIcao": { - "type": "string" - }, - "packageName": { - "type": "string" - }, - "submittedXml": { - "type": "string" - }, - "notes": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "201": { - "description": "Contribution created" - } - } - } - }, - "/contributions/leaderboard": { - "get": { - "summary": "Get top contributors", - "tags": [ - "Contributions" - ], - "responses": { - "200": { - "description": "Leaderboard returned" - } - } - } - }, - "/contributions/top-packages": { - "get": { - "summary": "Get most used packages", - "tags": [ - "Contributions" - ], - "responses": { - "200": { - "description": "Package stats returned" - } - } - } - }, - "/contributions/user": { - "get": { - "summary": "Get current user's contributions", - "tags": [ - "Contributions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "query", - "name": "status", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Contributions returned" - } - } - } - }, - "/contributions/{id}": { - "get": { - "summary": "Get a specific contribution", - "tags": [ - "Contributions" - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Contribution returned" - }, - "404": { - "description": "Not found" - } - } - }, - "delete": { - "x-hidden": true, - "summary": "Delete a contribution", - "tags": [ - "Contributions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Deletion result" - } - } - } - }, - "/contributions/{id}/decision": { - "post": { - "x-hidden": true, - "summary": "Approve or reject a contribution", - "tags": [ - "Contributions" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "approved" - ], - "properties": { - "approved": { - "type": "boolean" - }, - "rejectionReason": { - "type": "string" - }, - "newPackageName": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Decision processed" - }, - "403": { - "description": "Not authorized" - } - } - } - }, - "/maps/{icao}/packages/{package}/latest": { - "get": { - "summary": "Get latest approved BARS map XML (raw content) for an airport & package", - "tags": [ - "Generation" - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "path", - "name": "package", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "BARS XML document returned inline (application/xml)" - }, - "404": { - "description": "Not found" - } - } - } - }, - "/cdn/files/{fileKey}": { - "get": { - "summary": "Download a file from CDN", - "tags": [ - "CDN" - ], - "parameters": [ - { - "in": "path", - "name": "fileKey", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "File stream" - }, - "404": { - "description": "Not found" - } - } - }, - "delete": { - "x-hidden": true, - "summary": "Delete a file (staff only)", - "tags": [ - "CDN" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "fileKey", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Deletion result" - } - } - } - }, - "/cdn/upload": { - "post": { - "x-hidden": true, - "summary": "Upload a file to CDN (staff only)", - "tags": [ - "CDN" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "multipart/form-data": { - "schema": { - "type": "object", - "required": [ - "file" - ], - "properties": { - "file": { - "type": "string", - "format": "binary" - }, - "path": { - "type": "string" - }, - "key": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "201": { - "description": "File uploaded" - } - } - } - }, - "/cdn/files": { - "get": { - "x-hidden": true, - "summary": "List CDN files (staff only)", - "tags": [ - "CDN" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "query", - "name": "prefix", - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Files listed" - } - } - } - }, - "/euroscope/files/{icao}": { - "get": { - "summary": "List public EuroScope files for an airport", - "tags": [ - "EuroScope" - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Files listed" - }, - "400": { - "description": "Invalid ICAO" - } - } - } - }, - "/euroscope/upload": { - "post": { - "x-hidden": true, - "summary": "Upload EuroScope file for an airport", - "tags": [ - "EuroScope" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "multipart/form-data": { - "schema": { - "type": "object", - "required": [ - "file", - "icao" - ], - "properties": { - "file": { - "type": "string", - "format": "binary" - }, - "icao": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "201": { - "description": "File uploaded" - } - } - } - }, - "/euroscope/files/{icao}/{filename}": { - "delete": { - "x-hidden": true, - "summary": "Delete EuroScope file", - "tags": [ - "EuroScope" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "path", - "name": "filename", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Deletion result" - } - } - } - }, - "/euroscope/{icao}/editable": { - "get": { - "x-hidden": true, - "summary": "Check if EuroScope files are editable by user", - "tags": [ - "EuroScope" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "icao", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Permission status returned" - } - } - } - }, - "/releases": { - "get": { - "summary": "List all product releases (optionally filtered)", - "tags": [ - "Installer" - ], - "parameters": [ - { - "in": "query", - "name": "product", - "schema": { - "type": "string", - "enum": [ - "Pilot-Client", - "vatSys-Plugin", - "EuroScope-Plugin", - "Installer", - "SimConnect.NET" - ] - } - } - ], - "responses": { - "200": { - "description": "Releases listed" - } - } - } - }, - "/releases/latest": { - "get": { - "summary": "Get latest release for a product", - "tags": [ - "Installer" - ], - "parameters": [ - { - "in": "query", - "name": "product", - "required": true, - "schema": { - "type": "string", - "enum": [ - "Pilot-Client", - "vatSys-Plugin", - "EuroScope-Plugin", - "Installer", - "SimConnect.NET" - ] - } - } - ], - "responses": { - "200": { - "description": "Latest release returned" - }, - "404": { - "description": "Not found" - } - } - } - }, - "/releases/upload": { - "post": { - "x-hidden": true, - "summary": "Create a new product release (lead developer only)", - "tags": [ - "Installer" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "multipart/form-data": { - "schema": { - "type": "object", - "required": [ - "file", - "product", - "version" - ], - "properties": { - "file": { - "type": "string", - "format": "binary" - }, - "product": { - "type": "string", - "enum": [ - "Pilot-Client", - "vatSys-Plugin", - "EuroScope-Plugin", - "Installer", - "SimConnect.NET" - ] - }, - "version": { - "type": "string" - }, - "changelog": { - "type": "string" - }, - "image": { - "type": "string", - "format": "binary", - "description": "Optional promotional image (PNG/JPEG, max 5MB)" - } - } - } - } - } - }, - "x-notes": [ - "Product \"Installer\" requires an .exe file upload.", - "Product \"SimConnect.NET\" does not require a file upload (metadata + changelog only; version links to NuGet)." - ], - "responses": { - "201": { - "description": "Release created" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/releases/{id}/changelog": { - "put": { - "x-hidden": true, - "summary": "Update changelog content for a release", - "description": "Update only the changelog text of an existing release record.", - "tags": [ - "Installer" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "integer" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "changelog" - ], - "properties": { - "changelog": { - "type": "string", - "maxLength": 20000 - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Changelog updated" - }, - "400": { - "description": "Validation error" - }, - "401": { - "description": "Unauthorized" - }, - "403": { - "description": "Forbidden" - }, - "404": { - "description": "Release not found" - } - } - } - }, - "/purge-cache": { - "post": { - "x-hidden": true, - "summary": "Purge a cache key (lead developer only)", - "tags": [ - "Staff", - "Cache" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "key" - ], - "properties": { - "key": { - "type": "string" - }, - "namespace": { - "type": "string" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Cache purged" - }, - "403": { - "description": "Forbidden" - } - } - } - }, - "/contributors": { - "get": { - "summary": "List GitHub contributors", - "tags": [ - "GitHub" - ], - "responses": { - "200": { - "description": "Contributors returned" - } - } - } - }, - "/faqs": { - "get": { - "summary": "List public FAQs", - "tags": [ - "FAQ" - ], - "responses": { - "200": { - "description": "FAQs returned" - } - } - } - }, - "/staff/faqs": { - "post": { - "x-hidden": true, - "summary": "Create FAQ", - "tags": [ - "Staff", - "FAQ" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "question", - "answer", - "order_position" - ], - "properties": { - "question": { - "type": "string" - }, - "answer": { - "type": "string" - }, - "order_position": { - "type": "integer" - } - } - } - } - } - }, - "responses": { - "201": { - "description": "Created" - } - } - } - }, - "/staff/faqs/{id}": { - "put": { - "x-hidden": true, - "summary": "Update FAQ", - "tags": [ - "Staff", - "FAQ" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "question": { - "type": "string" - }, - "answer": { - "type": "string" - }, - "order_position": { - "type": "integer" - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Updated" - }, - "404": { - "description": "Not found" - } - } - }, - "delete": { - "x-hidden": true, - "summary": "Delete FAQ", - "tags": [ - "Staff", - "FAQ" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "parameters": [ - { - "in": "path", - "name": "id", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "Deletion result" - } - } - } - }, - "/staff/faqs/reorder": { - "post": { - "x-hidden": true, - "summary": "Bulk reorder FAQs", - "tags": [ - "Staff", - "FAQ" - ], - "security": [ - { - "VatsimToken": [] - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "updates" - ], - "properties": { - "updates": { - "type": "array", - "items": { - "type": "object", - "required": [ - "id", - "order_position" - ], - "properties": { - "id": { - "type": "string" - }, - "order_position": { - "type": "integer" - } - } - } - } - } - } - } - } - }, - "responses": { - "200": { - "description": "Reordered" - } - } - } - }, - "/health": { - "get": { - "summary": "System/service health check", - "tags": [ - "System" - ], - "parameters": [ - { - "in": "query", - "name": "service", - "required": false, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "All services healthy" - }, - "503": { - "description": "One or more services degraded" - } - } - } - }, - "/openapi.json": { - "get": { - "summary": "Get OpenAPI specification", - "tags": [ - "System" - ], - "description": "Returns the current OpenAPI 3.0 document for the BARS Core API.", - "responses": { - "200": { - "description": "OpenAPI document", - "content": { - "application/json": { - "schema": { - "type": "object" - } - } - } - } - } - } - } - }, - "components": { - "securitySchemes": { - "VatsimToken": { - "type": "apiKey", - "in": "header", - "name": "X-Vatsim-Token", - "description": "VATSIM authentication token obtained via OAuth callback." - }, - "ApiKeyAuth": { - "type": "http", - "scheme": "bearer", - "bearerFormat": "API Key", - "description": "User API key passed as Bearer token in Authorization header." - } - }, - "schemas": { - "Coordinates": { - "type": "object", - "required": [ - "lat", - "lng" - ], - "properties": { - "lat": { - "type": "number", - "description": "Latitude in decimal degrees." - }, - "lng": { - "type": "number", - "description": "Longitude in decimal degrees." - } - } - }, - "PointData": { - "type": "object", - "required": [ - "type", - "name", - "coordinates" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "stopbar", - "lead_on", - "taxiway", - "stand" - ], - "description": "Point category." - }, - "name": { - "type": "string", - "description": "Human readable point name / identifier." - }, - "coordinates": { - "$ref": "#/components/schemas/Coordinates" - }, - "directionality": { - "type": "string", - "enum": [ - "bi-directional", - "uni-directional" - ] - }, - "orientation": { - "type": "string", - "enum": [ - "left", - "right" - ] - }, - "color": { - "type": "string", - "enum": [ - "yellow", - "green", - "green-yellow", - "green-orange", - "green-blue" - ] - }, - "elevated": { - "type": "boolean" - }, - "ihp": { - "type": "boolean", - "description": "In pavement (false) vs elevated (true) for some systems." - } - }, - "description": "Point creation object. Server assigns id, airportId, created/updated timestamps & createdBy." - }, - "Point": { - "allOf": [ - { - "$ref": "#/components/schemas/PointData" - }, - { - "type": "object", - "required": [ - "id", - "airportId", - "createdAt", - "updatedAt", - "createdBy" - ], - "properties": { - "id": { - "type": "string" - }, - "airportId": { - "type": "string" - }, - "createdAt": { - "type": "string", - "format": "date-time" - }, - "updatedAt": { - "type": "string", - "format": "date-time" - }, - "createdBy": { - "type": "string", - "description": "VATSIM ID of creator" - } - }, - "description": "Persisted point including server-managed fields." - } - ] - }, - "PointDataPartial": { - "type": "object", - "description": "Partial PointData used for updates. All properties optional.", - "properties": { - "type": { - "type": "string", - "enum": [ - "stopbar", - "lead_on", - "taxiway", - "stand" - ] - }, - "name": { - "type": "string" - }, - "coordinates": { - "type": "object", - "properties": { - "lat": { - "type": "number" - }, - "lng": { - "type": "number" - } - } - }, - "directionality": { - "type": "string", - "enum": [ - "bi-directional", - "uni-directional" - ] - }, - "orientation": { - "type": "string", - "enum": [ - "left", - "right" - ] - }, - "color": { - "type": "string", - "enum": [ - "yellow", - "green", - "green-yellow", - "green-orange", - "green-blue" - ] - }, - "elevated": { - "type": "boolean" - }, - "ihp": { - "type": "boolean" - } - } - }, - "PointChangeset": { - "type": "object", - "description": "Transactional batch of point operations. Operations are applied atomically where possible.", - "properties": { - "create": { - "type": "array", - "items": { - "$ref": "#/components/schemas/PointData" - }, - "description": "List of new points to create." - }, - "modify": { - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/PointDataPartial" - }, - "description": "Map of point ID -> partial point data to update." - }, - "delete": { - "type": "array", - "items": { - "type": "string" - }, - "description": "List of point IDs to delete." - } - } - }, - "ErrorResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "message": { - "type": "string" - }, - "code": { - "type": "string", - "description": "Optional machine-readable error code" - } - }, - "required": [ - "error" - ], - "description": "Standard error envelope." - } - } - } -} \ No newline at end of file + "openapi": "3.0.4", + "info": { + "title": "BARS Core API", + "version": "2.0.0", + "description": "API documentation for BARS Core", + "contact": { + "name": "BARS Support", + "email": "support@stopbars.com", + "url": "https://stopbars.com/support" + } + }, + "externalDocs": { + "description": "Find more info here", + "url": "https://docs.stopbars.com" + }, + "servers": [ + { + "url": "https://v2.stopbars.com", + "description": "Production" + }, + { + "url": "http://localhost:8787", + "description": "Local development (wrangler dev)" + } + ], + "tags": [ + { + "name": "RealTime", + "description": "WebSocket connection and real-time state interaction endpoints." + }, + { + "name": "State", + "description": "Endpoints for retrieving current system or airport lighting/network state." + }, + { + "name": "Auth", + "description": "Authentication, account management, and API key lifecycle." + }, + { + "name": "Airports", + "description": "Lookup and metadata endpoints for airports." + }, + { + "name": "Divisions", + "description": "Division management, membership, and associated airport access." + }, + { + "name": "Points", + "description": "Creation and management of lighting/navigation point data." + }, + { + "name": "Generation", + "description": "Utilities for generating light support / BARS XML artifacts." + }, + { + "name": "NOTAM", + "description": "Global NOTAM retrieval and (staff) updates." + }, + { + "name": "Contributions", + "description": "Community lighting package submission, review, and leaderboard." + }, + { + "name": "Staff", + "description": "Restricted staff-only operational and moderation endpoints (hidden from public docs)." + }, + { + "name": "CDN", + "description": "File storage, upload, listing, and deletion via CDN-backed storage." + }, + { + "name": "FAQ", + "description": "Frequently Asked Questions (FAQ) management and retrieval." + }, + { + "name": "EuroScope", + "description": "EuroScope sector file upload, listing, and permission checks by ICAO." + }, + { + "name": "Cache", + "description": "Administrative cache management operations." + }, + { + "name": "GitHub", + "description": "Repository contributor information." + }, + { + "name": "System", + "description": "System health and OpenAPI specification discovery." + } + ], + "paths": { + "/contact": { + "post": { + "summary": "Submit a contact form", + "tags": ["Contact"], + "description": "Public endpoint to submit a contact/support message. Limited to 1 submission per 24 hours per IP.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["email", "topic", "message"], + "properties": { + "email": { + "type": "string", + "format": "email" + }, + "topic": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Message stored" + }, + "400": { + "description": "Validation error" + }, + "429": { + "description": "Rate limited (already submitted within 24h)" + } + } + }, + "get": { + "summary": "List submitted contact messages", + "x-hidden": true, + "tags": ["Contact", "Staff"], + "description": "Returns all contact messages (newest first). Requires Product Manager or higher.", + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Messages returned" + }, + "401": { + "description": "Unauthorized" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/contact/{id}/status": { + "patch": { + "summary": "Update contact message status", + "x-hidden": true, + "tags": ["Contact", "Staff"], + "description": "Set status to pending, handling, or handled. Requires Product Manager or higher.", + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["status"], + "properties": { + "status": { + "type": "string", + "enum": ["pending", "handling", "handled"] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Updated message returned" + }, + "400": { + "description": "Invalid status" + }, + "401": { + "description": "Unauthorized" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Message not found" + } + } + } + }, + "/contact/{id}": { + "delete": { + "summary": "Delete a contact message", + "x-hidden": true, + "tags": ["Contact", "Staff"], + "description": "Permanently deletes a contact message. Requires Product Manager or higher.", + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Deleted" + }, + "401": { + "description": "Unauthorized" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Not found" + } + } + } + }, + "/connect": { + "get": { + "summary": "Establish a WebSocket for an airport", + "tags": ["RealTime"], + "description": "Performs a WebSocket upgrade to stream real-time airport state. Requires:\n- GET with `Upgrade: websocket`\n- `airport` (ICAO, 4 chars) & `key` (API key) query params\nThe API key is forwarded as a Bearer token to the airport's Durable Object for auth.\n", + "parameters": [ + { + "in": "query", + "name": "airport", + "required": true, + "description": "Airport ICAO (4 alphanumeric characters)", + "schema": { + "type": "string", + "minLength": 4, + "maxLength": 4, + "pattern": "^[A-Z0-9]{4}$" + } + }, + { + "in": "query", + "name": "key", + "required": true, + "description": "User API key", + "schema": { + "type": "string" + } + } + ], + "responses": { + "101": { + "description": "WebSocket upgrade accepted" + }, + "400": { + "description": "Missing/invalid params or not a WebSocket upgrade" + }, + "401": { + "description": "API key rejected" + } + } + } + }, + "/state": { + "get": { + "summary": "Get current lighting/network state", + "tags": ["State"], + "description": "Retrieves real-time state for a specific airport or all active airports.", + "parameters": [ + { + "in": "query", + "name": "airport", + "required": true, + "description": "ICAO code of airport or 'all' for every active airport", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "State information returned" + }, + "400": { + "description": "Missing or invalid airport parameter" + } + } + } + }, + "/auth/vatsim/callback": { + "get": { + "summary": "VATSIM OAuth callback", + "tags": ["Auth"], + "description": "Exchanges authorization code for a VATSIM token and redirects to frontend with token.", + "parameters": [ + { + "in": "query", + "name": "code", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "302": { + "description": "Redirect to application with token or error" + }, + "400": { + "description": "Missing code parameter" + } + } + } + }, + "/auth/account": { + "get": { + "summary": "Get authenticated account information", + "tags": ["Auth"], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Account found" + }, + "401": { + "description": "Missing or invalid token" + }, + "404": { + "description": "User not found" + } + } + } + }, + "/auth/display-mode": { + "put": { + "summary": "Update preferred display name mode", + "tags": ["Auth"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["mode"], + "properties": { + "mode": { + "type": "integer", + "enum": [0, 1, 2], + "description": "0=First,1=First LastInitial,2=CID" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Updated" + } + } + } + }, + "/auth/regenerate-api-key": { + "post": { + "summary": "Regenerate API key", + "tags": ["Auth"], + "description": "Generates a new API key for the authenticated user (24h cooldown).", + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Key regenerated" + }, + "401": { + "description": "Unauthorized" + }, + "404": { + "description": "User not found" + }, + "429": { + "description": "Rate limited (cooldown not elapsed)" + } + } + } + }, + "/auth/delete": { + "delete": { + "summary": "Delete current user account", + "tags": ["Auth"], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "204": { + "description": "Account deleted" + }, + "401": { + "description": "Unauthorized" + }, + "404": { + "description": "User not found" + } + } + } + }, + "/auth/is-staff": { + "get": { + "x-hidden": true, + "summary": "Check staff status", + "tags": ["Staff"], + "security": [ + { + "ApiKeyAuth": [] + } + ], + "responses": { + "200": { + "description": "Staff status returned" + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/airports": { + "get": { + "summary": "Get airport data", + "tags": ["Airports"], + "description": "Fetch airport(s) by ICAO(s) or by continent.", + "parameters": [ + { + "in": "query", + "name": "icao", + "required": false, + "description": "Single ICAO or comma-separated list", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "continent", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Airport data returned" + }, + "400": { + "description": "Invalid parameters" + }, + "404": { + "description": "Airport not found" + } + } + } + }, + "/airports/nearest": { + "get": { + "summary": "Find nearest airport", + "tags": ["Airports"], + "description": "Returns the nearest airport to a given latitude/longitude. Results are cached in 5NM buckets for high performance.", + "parameters": [ + { + "in": "query", + "name": "lat", + "required": true, + "description": "Latitude in decimal degrees (-90 to 90)", + "schema": { + "type": "number" + } + }, + { + "in": "query", + "name": "lon", + "required": true, + "description": "Longitude in decimal degrees (-180 to 180)", + "schema": { + "type": "number" + } + } + ], + "responses": { + "200": { + "description": "Nearest airport returned" + }, + "400": { + "description": "Invalid coordinates" + }, + "404": { + "description": "No airport found" + } + } + } + }, + "/divisions": { + "get": { + "summary": "List all divisions", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Divisions returned" + }, + "401": { + "description": "Unauthorized" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Create a new division", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["name", "headVatsimId"], + "properties": { + "name": { + "type": "string" + }, + "headVatsimId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Division created" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/divisions/{id}": { + "put": { + "x-hidden": true, + "summary": "Update division name", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["name"], + "properties": { + "name": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Division updated" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Division not found" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete a division", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "204": { + "description": "Division deleted" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Division not found" + } + } + }, + "get": { + "summary": "Get division details", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Division returned" + }, + "404": { + "description": "Division not found" + } + } + } + }, + "/divisions/user": { + "get": { + "summary": "Get divisions for current user", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "User divisions returned" + } + } + } + }, + "/divisions/{id}/members": { + "get": { + "summary": "List division members", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Members listed" + }, + "404": { + "description": "Division not found" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Add member to division", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["vatsimId", "role"], + "properties": { + "vatsimId": { + "type": "string" + }, + "role": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Member added" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/divisions/{id}/members/{vatsimId}": { + "delete": { + "x-hidden": true, + "summary": "Remove member from division", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "in": "path", + "name": "vatsimId", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Member removed" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/divisions/{id}/airports": { + "get": { + "summary": "List division airports", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Airports listed" + }, + "404": { + "description": "Division not found" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Request airport addition to division", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["icao"], + "properties": { + "icao": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Airport request created" + }, + "404": { + "description": "Division not found" + } + } + } + }, + "/divisions/{id}/airports/{airportId}/approve": { + "post": { + "x-hidden": true, + "summary": "Approve or reject airport request", + "tags": ["Divisions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + }, + { + "in": "path", + "name": "airportId", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["approved"], + "properties": { + "approved": { + "type": "boolean" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Airport approval processed" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/airports/{icao}/points": { + "get": { + "summary": "List lighting/navigation points for airport", + "tags": ["Points"], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string", + "minLength": 4, + "maxLength": 4 + } + } + ], + "responses": { + "200": { + "description": "Points returned" + }, + "400": { + "description": "Invalid ICAO" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Create a single point", + "tags": ["Points"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PointData" + } + } + } + }, + "responses": { + "201": { + "description": "Point created" + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/airports/{icao}/points/batch": { + "post": { + "x-hidden": true, + "summary": "Apply a batch point changeset", + "tags": ["Points"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PointChangeset" + } + } + } + }, + "responses": { + "201": { + "description": "Changeset applied" + } + } + } + }, + "/airports/{icao}/points/{id}": { + "put": { + "x-hidden": true, + "summary": "Update a point", + "tags": ["Points"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "responses": { + "200": { + "description": "Point updated" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete a point", + "tags": ["Points"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "Deleted" + } + } + } + }, + "/points/{id}": { + "get": { + "summary": "Get a single point by ID", + "tags": ["Points"], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Point found" + }, + "404": { + "description": "Not found" + } + } + } + }, + "/points": { + "get": { + "summary": "Get multiple points by IDs", + "tags": ["Points"], + "parameters": [ + { + "in": "query", + "name": "ids", + "required": true, + "description": "Comma-separated list of point IDs (max 100)", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Points returned" + }, + "400": { + "description": "Validation error" + } + } + } + }, + "/supports/generate": { + "post": { + "summary": "Generate Light Supports and BARS XML", + "tags": ["Generation"], + "description": "Upload raw XML and generate both light supports XML and processed BARS XML.", + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "required": ["xmlFile", "icao"], + "properties": { + "xmlFile": { + "type": "string", + "format": "binary" + }, + "icao": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Generated XML returned" + }, + "400": { + "description": "Validation error" + } + } + } + }, + "/notam": { + "get": { + "summary": "Get global NOTAM", + "tags": ["NOTAM"], + "responses": { + "200": { + "description": "Current NOTAM returned" + } + } + }, + "put": { + "x-hidden": true, + "summary": "Update global NOTAM", + "tags": ["NOTAM"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["content"], + "properties": { + "content": { + "type": "string" + }, + "type": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "NOTAM updated" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/staff/users": { + "get": { + "x-hidden": true, + "summary": "List users (staff only)", + "tags": ["Staff"], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Users returned" + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/staff/users/search": { + "get": { + "x-hidden": true, + "summary": "Search users (staff only)", + "tags": ["Staff"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "query", + "name": "q", + "required": true, + "schema": { + "type": "string", + "minLength": 3 + } + } + ], + "responses": { + "200": { + "description": "Search results returned" + }, + "400": { + "description": "Invalid query" + } + } + } + }, + "/staff/users/refresh-api-token": { + "post": { + "x-hidden": true, + "summary": "Refresh a user's API token (staff only)", + "tags": ["Staff"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["vatsimId"], + "properties": { + "vatsimId": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Token refreshed" + } + } + } + }, + "/staff/users/{id}": { + "delete": { + "x-hidden": true, + "summary": "Delete a user (staff only)", + "tags": ["Staff"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "User deletion result" + } + } + } + }, + "/staff/manage": { + "get": { + "x-hidden": true, + "summary": "List staff members", + "tags": ["Staff"], + "security": [ + { + "VatsimToken": [] + } + ], + "responses": { + "200": { + "description": "Staff listed" + }, + "403": { + "description": "Forbidden" + } + } + }, + "post": { + "x-hidden": true, + "summary": "Add or update a staff member", + "tags": ["Staff"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["vatsimId", "role"], + "properties": { + "vatsimId": { + "type": "string" + }, + "role": { + "type": "string", + "enum": ["LEAD_DEVELOPER", "PRODUCT_MANAGER"] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Staff added/updated" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/staff/manage/{vatsimId}": { + "delete": { + "x-hidden": true, + "summary": "Remove staff member", + "tags": ["Staff"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "vatsimId", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Staff removed" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/contributions": { + "get": { + "summary": "List contributions", + "tags": ["Contributions"], + "parameters": [ + { + "in": "query", + "name": "status", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "airport", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "user", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Contributions listed" + } + } + }, + "post": { + "summary": "Submit a new contribution", + "tags": ["Contributions"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["airportIcao", "packageName", "submittedXml"], + "properties": { + "airportIcao": { + "type": "string" + }, + "packageName": { + "type": "string" + }, + "submittedXml": { + "type": "string" + }, + "notes": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Contribution created" + } + } + } + }, + "/contributions/leaderboard": { + "get": { + "summary": "Get top contributors", + "tags": ["Contributions"], + "responses": { + "200": { + "description": "Leaderboard returned" + } + } + } + }, + "/contributions/top-packages": { + "get": { + "summary": "Get most used packages", + "tags": ["Contributions"], + "responses": { + "200": { + "description": "Package stats returned" + } + } + } + }, + "/contributions/user": { + "get": { + "summary": "Get current user's contributions", + "tags": ["Contributions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "query", + "name": "status", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Contributions returned" + } + } + } + }, + "/contributions/{id}": { + "get": { + "summary": "Get a specific contribution", + "tags": ["Contributions"], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Contribution returned" + }, + "404": { + "description": "Not found" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete a contribution", + "tags": ["Contributions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Deletion result" + } + } + } + }, + "/contributions/{id}/decision": { + "post": { + "x-hidden": true, + "summary": "Approve or reject a contribution", + "tags": ["Contributions"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["approved"], + "properties": { + "approved": { + "type": "boolean" + }, + "rejectionReason": { + "type": "string" + }, + "newPackageName": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Decision processed" + }, + "403": { + "description": "Not authorized" + } + } + } + }, + "/maps/{icao}/packages/{package}/latest": { + "get": { + "summary": "Get latest approved BARS map XML (raw content) for an airport & package", + "tags": ["Generation"], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "package", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "BARS XML document returned inline (application/xml)" + }, + "404": { + "description": "Not found" + } + } + } + }, + "/cdn/files/{fileKey}": { + "get": { + "summary": "Download a file from CDN", + "tags": ["CDN"], + "parameters": [ + { + "in": "path", + "name": "fileKey", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "File stream" + }, + "404": { + "description": "Not found" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete a file (staff only)", + "tags": ["CDN"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "fileKey", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Deletion result" + } + } + } + }, + "/cdn/upload": { + "post": { + "x-hidden": true, + "summary": "Upload a file to CDN (staff only)", + "tags": ["CDN"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "required": ["file"], + "properties": { + "file": { + "type": "string", + "format": "binary" + }, + "path": { + "type": "string" + }, + "key": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "File uploaded" + } + } + } + }, + "/cdn/files": { + "get": { + "x-hidden": true, + "summary": "List CDN files (staff only)", + "tags": ["CDN"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "query", + "name": "prefix", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Files listed" + } + } + } + }, + "/euroscope/files/{icao}": { + "get": { + "summary": "List public EuroScope files for an airport", + "tags": ["EuroScope"], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Files listed" + }, + "400": { + "description": "Invalid ICAO" + } + } + } + }, + "/euroscope/upload": { + "post": { + "x-hidden": true, + "summary": "Upload EuroScope file for an airport", + "tags": ["EuroScope"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "required": ["file", "icao"], + "properties": { + "file": { + "type": "string", + "format": "binary" + }, + "icao": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "File uploaded" + } + } + } + }, + "/euroscope/files/{icao}/{filename}": { + "delete": { + "x-hidden": true, + "summary": "Delete EuroScope file", + "tags": ["EuroScope"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + }, + { + "in": "path", + "name": "filename", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Deletion result" + } + } + } + }, + "/euroscope/{icao}/editable": { + "get": { + "x-hidden": true, + "summary": "Check if EuroScope files are editable by user", + "tags": ["EuroScope"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "icao", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Permission status returned" + } + } + } + }, + "/releases": { + "get": { + "summary": "List all product releases (optionally filtered)", + "tags": ["Installer"], + "parameters": [ + { + "in": "query", + "name": "product", + "schema": { + "type": "string", + "enum": ["Pilot-Client", "vatSys-Plugin", "EuroScope-Plugin", "Installer", "SimConnect.NET"] + } + } + ], + "responses": { + "200": { + "description": "Releases listed" + } + } + } + }, + "/releases/latest": { + "get": { + "summary": "Get latest release for a product", + "tags": ["Installer"], + "parameters": [ + { + "in": "query", + "name": "product", + "required": true, + "schema": { + "type": "string", + "enum": ["Pilot-Client", "vatSys-Plugin", "EuroScope-Plugin", "Installer", "SimConnect.NET"] + } + } + ], + "responses": { + "200": { + "description": "Latest release returned" + }, + "404": { + "description": "Not found" + } + } + } + }, + "/releases/upload": { + "post": { + "x-hidden": true, + "summary": "Create a new product release (lead developer only)", + "tags": ["Installer"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "type": "object", + "required": ["file", "product", "version"], + "properties": { + "file": { + "type": "string", + "format": "binary" + }, + "product": { + "type": "string", + "enum": ["Pilot-Client", "vatSys-Plugin", "EuroScope-Plugin", "Installer", "SimConnect.NET"] + }, + "version": { + "type": "string" + }, + "changelog": { + "type": "string" + }, + "image": { + "type": "string", + "format": "binary", + "description": "Optional promotional image (PNG/JPEG, max 5MB)" + } + } + } + } + } + }, + "x-notes": [ + "Product \"Installer\" requires an .exe file upload.", + "Product \"SimConnect.NET\" does not require a file upload (metadata + changelog only; version links to NuGet)." + ], + "responses": { + "201": { + "description": "Release created" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/releases/{id}/changelog": { + "put": { + "x-hidden": true, + "summary": "Update changelog content for a release", + "description": "Update only the changelog text of an existing release record.", + "tags": ["Installer"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["changelog"], + "properties": { + "changelog": { + "type": "string", + "maxLength": 20000 + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Changelog updated" + }, + "400": { + "description": "Validation error" + }, + "401": { + "description": "Unauthorized" + }, + "403": { + "description": "Forbidden" + }, + "404": { + "description": "Release not found" + } + } + } + }, + "/purge-cache": { + "post": { + "x-hidden": true, + "summary": "Purge a cache key (lead developer only)", + "tags": ["Staff", "Cache"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["key"], + "properties": { + "key": { + "type": "string" + }, + "namespace": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Cache purged" + }, + "403": { + "description": "Forbidden" + } + } + } + }, + "/contributors": { + "get": { + "summary": "List GitHub contributors", + "tags": ["GitHub"], + "responses": { + "200": { + "description": "Contributors returned" + } + } + } + }, + "/faqs": { + "get": { + "summary": "List public FAQs", + "tags": ["FAQ"], + "responses": { + "200": { + "description": "FAQs returned" + } + } + } + }, + "/staff/faqs": { + "post": { + "x-hidden": true, + "summary": "Create FAQ", + "tags": ["Staff", "FAQ"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["question", "answer", "order_position"], + "properties": { + "question": { + "type": "string" + }, + "answer": { + "type": "string" + }, + "order_position": { + "type": "integer" + } + } + } + } + } + }, + "responses": { + "201": { + "description": "Created" + } + } + } + }, + "/staff/faqs/{id}": { + "put": { + "x-hidden": true, + "summary": "Update FAQ", + "tags": ["Staff", "FAQ"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "question": { + "type": "string" + }, + "answer": { + "type": "string" + }, + "order_position": { + "type": "integer" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Updated" + }, + "404": { + "description": "Not found" + } + } + }, + "delete": { + "x-hidden": true, + "summary": "Delete FAQ", + "tags": ["Staff", "FAQ"], + "security": [ + { + "VatsimToken": [] + } + ], + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Deletion result" + } + } + } + }, + "/staff/faqs/reorder": { + "post": { + "x-hidden": true, + "summary": "Bulk reorder FAQs", + "tags": ["Staff", "FAQ"], + "security": [ + { + "VatsimToken": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["updates"], + "properties": { + "updates": { + "type": "array", + "items": { + "type": "object", + "required": ["id", "order_position"], + "properties": { + "id": { + "type": "string" + }, + "order_position": { + "type": "integer" + } + } + } + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Reordered" + } + } + } + }, + "/health": { + "get": { + "summary": "System/service health check", + "tags": ["System"], + "parameters": [ + { + "in": "query", + "name": "service", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "All services healthy" + }, + "503": { + "description": "One or more services degraded" + } + } + } + }, + "/openapi.json": { + "get": { + "summary": "Get OpenAPI specification", + "tags": ["System"], + "description": "Returns the current OpenAPI 3.0 document for the BARS Core API.", + "responses": { + "200": { + "description": "OpenAPI document", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + } + } + }, + "components": { + "securitySchemes": { + "VatsimToken": { + "type": "apiKey", + "in": "header", + "name": "X-Vatsim-Token", + "description": "VATSIM authentication token obtained via OAuth callback." + }, + "ApiKeyAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "API Key", + "description": "User API key passed as Bearer token in Authorization header." + } + }, + "schemas": { + "Coordinates": { + "type": "object", + "required": ["lat", "lng"], + "properties": { + "lat": { + "type": "number", + "description": "Latitude in decimal degrees." + }, + "lng": { + "type": "number", + "description": "Longitude in decimal degrees." + } + } + }, + "PointData": { + "type": "object", + "required": ["type", "name", "coordinates"], + "properties": { + "type": { + "type": "string", + "enum": ["stopbar", "lead_on", "taxiway", "stand"], + "description": "Point category." + }, + "name": { + "type": "string", + "description": "Human readable point name / identifier." + }, + "coordinates": { + "$ref": "#/components/schemas/Coordinates" + }, + "directionality": { + "type": "string", + "enum": ["bi-directional", "uni-directional"] + }, + "orientation": { + "type": "string", + "enum": ["left", "right"] + }, + "color": { + "type": "string", + "enum": ["yellow", "green", "green-yellow", "green-orange", "green-blue"] + }, + "elevated": { + "type": "boolean" + }, + "ihp": { + "type": "boolean", + "description": "In pavement (false) vs elevated (true) for some systems." + } + }, + "description": "Point creation object. Server assigns id, airportId, created/updated timestamps & createdBy." + }, + "Point": { + "allOf": [ + { + "$ref": "#/components/schemas/PointData" + }, + { + "type": "object", + "required": ["id", "airportId", "createdAt", "updatedAt", "createdBy"], + "properties": { + "id": { + "type": "string" + }, + "airportId": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "createdBy": { + "type": "string", + "description": "VATSIM ID of creator" + } + }, + "description": "Persisted point including server-managed fields." + } + ] + }, + "PointDataPartial": { + "type": "object", + "description": "Partial PointData used for updates. All properties optional.", + "properties": { + "type": { + "type": "string", + "enum": ["stopbar", "lead_on", "taxiway", "stand"] + }, + "name": { + "type": "string" + }, + "coordinates": { + "type": "object", + "properties": { + "lat": { + "type": "number" + }, + "lng": { + "type": "number" + } + } + }, + "directionality": { + "type": "string", + "enum": ["bi-directional", "uni-directional"] + }, + "orientation": { + "type": "string", + "enum": ["left", "right"] + }, + "color": { + "type": "string", + "enum": ["yellow", "green", "green-yellow", "green-orange", "green-blue"] + }, + "elevated": { + "type": "boolean" + }, + "ihp": { + "type": "boolean" + } + } + }, + "PointChangeset": { + "type": "object", + "description": "Transactional batch of point operations. Operations are applied atomically where possible.", + "properties": { + "create": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PointData" + }, + "description": "List of new points to create." + }, + "modify": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/PointDataPartial" + }, + "description": "Map of point ID -> partial point data to update." + }, + "delete": { + "type": "array", + "items": { + "type": "string" + }, + "description": "List of point IDs to delete." + } + } + }, + "ErrorResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "message": { + "type": "string" + }, + "code": { + "type": "string", + "description": "Optional machine-readable error code" + } + }, + "required": ["error"], + "description": "Standard error envelope." + } + } + } +}