From c799b26fe01f2f51d3961b2a32fa57cb84619a81 Mon Sep 17 00:00:00 2001 From: Brett Beutell Date: Mon, 7 Oct 2024 14:41:01 +0200 Subject: [PATCH] Static analysis utilties to improve ai request generation (#291) * Proof of concept of static analysis to expand function context for ai req gen * Wire up tests for static analysis with an example repo * Move expand-function tests to their own test file * Use logger in the expand-function module and also fix directory traversal * Return undefined if no value was found for expanded defn * Factor out helper for getting out-of-scope identifiers and add utiltiies for creating workspace/executeCommand rpc calls * Also analzy function expressions jic * Update followImport with a docstring explaining why it was used (and hopefully should not be anymore) * Add failing test for filtering out web standard globals from identifiers returned by static analysis * Filter out web standard globals from the identifiers returned by static analysis * Add a type guard for definition responses from tsserver * Remove dead code and shuffle some files * Fix type error * Refactor forEach * Comment out some debug logs * Refactor getDefinitionText to provide info on whether it returned a function * Add TODO for tomorrow * Terminate language server when process exits * Add janky test for recursively expanding out of scope vars ((needs work)) * Add tests for identifier analyzer and update its behavior for property accesses on out of scope vars * Update workers-types in static analysis test repo * Implement a singleton pattern for the typescript server instance (child process) and fix up some tests * Add some tests for a drizzlified codebase and handle pnpm packages properly when extracing package names * Update comment * Move search-function into a folder * Write some tests for search-file and search-function * Update comments and logs * Move out of scope identifier analysis out of searchFunction * Tidy up search-function tests * Add README * Fix typecheck on studio * Add docstring to expandFunction * Start ts language server process if ai is enabled * Resolve path that is passed to getTSServer * Ignore directories more aggresively when searching for function * Remove srcPath argument as it is unneeded * Recursively expand context * Improve some logging and make test-static-analysis runnable * Add a nontrivial column to db schema * Expand logger with trace level and account for reponening changed files in lang server * Add trace logging * Format * Implement absolutely unhinged method for mapping back to source function but it works * Add option to skip source map searches * Remove type from prompt * Document search-compiled-function * Make search-source-function async * Fix tests for async search file, and remove .trace logging * Format * Add link to Ades work in the README * Also expand middleware context * Do not serialize 3rd party functions into context * Update identifier analyzer to have a scope stack (broke property access logic however) * Fix issues with property access. Now start tackling inner scope issues * Fix inner scope issues * Break out unit tests to be more granular * Split out identifier analyzer into smaller unit tests (again) * Continue with identifier-analyzer tests * Add hacky solution for middleware source function detection issue * Fix expand-function tests except for the one on Drizzle schema expansion (schema.stuff) * Improve type-narrowing for functions passed to analyzeOutOfScopeIdentifiers * Add a test for the source map reader to cover case where certain middleware could not be mapped back * Add some comments * Implement source hints from hits from the source map * Update blurb about eslint * Set up tests for full file context * Expand entirety of imported file if we are dealing with namespace imports * Add middleware context to the qa tester propmt * Turn off noisy logs bit by bit and try to speed up context builder * Start optimizing source map lookups * More comments * Start refactoring findSourceFunction to handle batch lookups * Modify tests to handle batch lookups * Update some comments * Add performance boost * Cleanup * Move inference router to its own folder * Factor out handler and middleware expansion utilties from the inference route * Fix expand-handler test route * Add docstrings and clean up some code for getting source map and compiled index.js * Log when we terminate tsserver * Start renaming things to make more sense * Add back prefiltering of bearerAuth middleware * Clean up some debug logs and implement an explicict debug logging switch on expandFunction * Factor out extractPackage * Do not throw errors in inference handler if context expansion fails * Add better docstrings to expand-function * Get definition text of type assignments * Extract out FunctionContextTypes * Remove unnecessary any * Update docstring in identifierAnalyzer * Update context-for-import to use module resolution helper * No need for xml escaping * Remove comment * Update expand function README * Update find-source-function * Clean up expand-handler use of buildAiContext * Remove TODO comments by unknown types * Add changelog entry * Add helper is-dependency * Update find-source-function tests after more fiddling with the test-static-analysis codebase * Comment out debug logs * Remove debug logs * Comment out one more debug log --- DEVELOPMENT.md | 2 +- api/package.json | 6 + api/src/app.ts | 2 +- api/src/constants.ts | 6 + api/src/index.node.ts | 19 +- api/src/lib/ai/anthropic.ts | 12 +- api/src/lib/ai/index.ts | 8 + api/src/lib/ai/openai.ts | 14 +- api/src/lib/ai/prompts.ts | 18 + api/src/lib/expand-function/README.md | 97 + .../ast-helpers/ast-helpers.ts | 152 + .../ast-helpers/identifier-analyzer.test.ts | 457 + .../ast-helpers/identifier-analyzer.ts | 276 + .../lib/expand-function/ast-helpers/index.ts | 2 + .../expand-function/ast-helpers/program.ts | 53 + .../lib/expand-function/expand-function.ts | 420 + .../imports/context-for-import.ts | 193 + .../imports/extract-package-name.ts | 44 + api/src/lib/expand-function/imports/index.ts | 4 + .../imports/is-dependency.test.ts | 43 + .../expand-function/imports/is-dependency.ts | 13 + .../imports/resolve-imports.ts | 72 + api/src/lib/expand-function/index.ts | 6 + .../expand-function/search-function/index.ts | 2 + .../search-compiled-function.ts | 122 + .../search-function/search-file.test.ts | 113 + .../search-function/search-file.ts | 153 + .../search-function/search-function.ts | 103 + .../search-source-function.test.ts | 290 + .../search-function/search-source-function.ts | 138 + .../tests/expand-function-smoke-test.ts | 80 + .../tests/expand-function.test.ts | 367 + .../lib/expand-function/tsserver/commands.ts | 176 + api/src/lib/expand-function/tsserver/index.ts | 8 + .../lib/expand-function/tsserver/server.ts | 175 + api/src/lib/expand-function/tsserver/types.ts | 74 + api/src/lib/expand-function/tsserver/utils.ts | 26 + api/src/lib/expand-function/types.ts | 8 + api/src/lib/find-source-function.ts | 173 - .../find-source-function.test.ts | 225 + .../find-source-function.ts | 297 + api/src/lib/find-source-function/index.ts | 4 + .../test-data/hono-js-tracker/index.js | 44188 ++++++++++++++++ .../test-data/hono-js-tracker/index.js.map | 8 + .../test-data/test-static-analysis/index.js | 15777 ++++++ .../test-static-analysis/index.js.map | 8 + api/src/logger.ts | 2 +- api/src/routes/inference/expand-handler.ts | 246 + api/src/routes/inference/index.ts | 3 + api/src/routes/{ => inference}/inference.ts | 41 +- api/src/routes/source.ts | 8 +- api/src/serve-frontend-build.ts | 13 +- biome.jsonc | 5 +- examples/goose-quotes/src/index.ts | 6 +- examples/goose-quotes/src/utils.ts | 6 + examples/goosify/README.md | 2 +- examples/goosify/package.json | 2 + examples/test-static-analysis/.gitignore | 33 + examples/test-static-analysis/README.md | 17 + examples/test-static-analysis/db-touch.sql | 0 .../test-static-analysis/drizzle.config.ts | 55 + .../migrations/0000_concerned_champions.sql | 6 + .../migrations/meta/0000_snapshot.json | 53 + .../drizzle/migrations/meta/_journal.json | 13 + examples/test-static-analysis/package.json | 19 + .../test-static-analysis/src/constants.ts | 1 + .../test-static-analysis/src/db/schema.ts | 9 + examples/test-static-analysis/src/index.ts | 45 + .../test-static-analysis/src/other-router.ts | 38 + examples/test-static-analysis/src/utils.ts | 10 + examples/test-static-analysis/tsconfig.json | 13 + examples/test-static-analysis/wrangler.toml | 23 + pnpm-lock.yaml | 129 +- .../RequestorPage/ai/generate-request-data.ts | 20 +- www/src/content/changelog/!canary.mdx | 2 + 75 files changed, 65041 insertions(+), 213 deletions(-) create mode 100644 api/src/lib/expand-function/README.md create mode 100644 api/src/lib/expand-function/ast-helpers/ast-helpers.ts create mode 100644 api/src/lib/expand-function/ast-helpers/identifier-analyzer.test.ts create mode 100644 api/src/lib/expand-function/ast-helpers/identifier-analyzer.ts create mode 100644 api/src/lib/expand-function/ast-helpers/index.ts create mode 100644 api/src/lib/expand-function/ast-helpers/program.ts create mode 100644 api/src/lib/expand-function/expand-function.ts create mode 100644 api/src/lib/expand-function/imports/context-for-import.ts create mode 100644 api/src/lib/expand-function/imports/extract-package-name.ts create mode 100644 api/src/lib/expand-function/imports/index.ts create mode 100644 api/src/lib/expand-function/imports/is-dependency.test.ts create mode 100644 api/src/lib/expand-function/imports/is-dependency.ts create mode 100644 api/src/lib/expand-function/imports/resolve-imports.ts create mode 100644 api/src/lib/expand-function/index.ts create mode 100644 api/src/lib/expand-function/search-function/index.ts create mode 100644 api/src/lib/expand-function/search-function/search-compiled-function.ts create mode 100644 api/src/lib/expand-function/search-function/search-file.test.ts create mode 100644 api/src/lib/expand-function/search-function/search-file.ts create mode 100644 api/src/lib/expand-function/search-function/search-function.ts create mode 100644 api/src/lib/expand-function/search-function/search-source-function.test.ts create mode 100644 api/src/lib/expand-function/search-function/search-source-function.ts create mode 100644 api/src/lib/expand-function/tests/expand-function-smoke-test.ts create mode 100644 api/src/lib/expand-function/tests/expand-function.test.ts create mode 100644 api/src/lib/expand-function/tsserver/commands.ts create mode 100644 api/src/lib/expand-function/tsserver/index.ts create mode 100644 api/src/lib/expand-function/tsserver/server.ts create mode 100644 api/src/lib/expand-function/tsserver/types.ts create mode 100644 api/src/lib/expand-function/tsserver/utils.ts create mode 100644 api/src/lib/expand-function/types.ts delete mode 100644 api/src/lib/find-source-function.ts create mode 100644 api/src/lib/find-source-function/find-source-function.test.ts create mode 100644 api/src/lib/find-source-function/find-source-function.ts create mode 100644 api/src/lib/find-source-function/index.ts create mode 100644 api/src/lib/find-source-function/test-data/hono-js-tracker/index.js create mode 100644 api/src/lib/find-source-function/test-data/hono-js-tracker/index.js.map create mode 100644 api/src/lib/find-source-function/test-data/test-static-analysis/index.js create mode 100644 api/src/lib/find-source-function/test-data/test-static-analysis/index.js.map create mode 100644 api/src/routes/inference/expand-handler.ts create mode 100644 api/src/routes/inference/index.ts rename api/src/routes/{ => inference}/inference.ts (66%) create mode 100644 examples/goose-quotes/src/utils.ts create mode 100644 examples/test-static-analysis/.gitignore create mode 100644 examples/test-static-analysis/README.md create mode 100644 examples/test-static-analysis/db-touch.sql create mode 100644 examples/test-static-analysis/drizzle.config.ts create mode 100644 examples/test-static-analysis/drizzle/migrations/0000_concerned_champions.sql create mode 100644 examples/test-static-analysis/drizzle/migrations/meta/0000_snapshot.json create mode 100644 examples/test-static-analysis/drizzle/migrations/meta/_journal.json create mode 100644 examples/test-static-analysis/package.json create mode 100644 examples/test-static-analysis/src/constants.ts create mode 100644 examples/test-static-analysis/src/db/schema.ts create mode 100644 examples/test-static-analysis/src/index.ts create mode 100644 examples/test-static-analysis/src/other-router.ts create mode 100644 examples/test-static-analysis/src/utils.ts create mode 100644 examples/test-static-analysis/tsconfig.json create mode 100644 examples/test-static-analysis/wrangler.toml diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 1a44f0f77..81409f801 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -45,7 +45,7 @@ Follow the instructions in the [`client-library-otel` README](./packages/client- ## Developing -This project uses typescript, biome and pnpm workspaces. The frontend package also uses eslint for linting purposes, all other packages use biome for linting (formatting is always done with biome). +This project uses typescript, biome and pnpm workspaces. Linting and formatting is handled with [biome](https://biomejs.dev/). In the project root you can format all typescript codebases with `pnpm run format`. diff --git a/api/package.json b/api/package.json index 445d271b8..506e35e1b 100644 --- a/api/package.json +++ b/api/package.json @@ -22,6 +22,8 @@ "db:drop": "drizzle-kit drop", "db:seed": "tsx scripts/seed.ts", "db:studio": "drizzle-kit studio", + "expand-function": "tsx src/lib/expand-function/tests/expand-function-smoke-test.ts", + "expand-function:debug": "node --inspect-brk -r tsx/cjs src/lib/expand-function/tests/expand-function-smoke-test.ts", "build": "pnpm run db:generate && tsc", "format": "biome check . --write", "lint": "biome lint .", @@ -56,6 +58,10 @@ "minimatch": "^10.0.1", "openai": "^4.47.1", "source-map": "^0.7.4", + "typescript": "^5.5.4", + "typescript-language-server": "^4.3.3", + "vscode-jsonrpc": "^8.2.1", + "vscode-uri": "^3.0.8", "ws": "^8.17.1", "zod": "^3.23.8" }, diff --git a/api/src/app.ts b/api/src/app.ts index a7f94d5a1..cf6a6c85e 100644 --- a/api/src/app.ts +++ b/api/src/app.ts @@ -9,7 +9,7 @@ import logger from "./logger.js"; import type * as webhoncType from "./lib/webhonc/index.js"; import appRoutes from "./routes/app-routes.js"; -import inference from "./routes/inference.js"; +import inference from "./routes/inference/index.js"; import settings from "./routes/settings.js"; import source from "./routes/source.js"; import traces from "./routes/traces.js"; diff --git a/api/src/constants.ts b/api/src/constants.ts index 72bcfd582..70b8a7ecc 100644 --- a/api/src/constants.ts +++ b/api/src/constants.ts @@ -1 +1,7 @@ +import path from "node:path"; + export const DEFAULT_DATABASE_URL = "file:fpx.db"; + +export const USER_PROJECT_ROOT_DIR = path.resolve( + process.env.FPX_WATCH_DIR ?? process.cwd(), +); diff --git a/api/src/index.node.ts b/api/src/index.node.ts index dae2063e1..ab416c1bc 100644 --- a/api/src/index.node.ts +++ b/api/src/index.node.ts @@ -7,8 +7,9 @@ import { drizzle } from "drizzle-orm/libsql"; import figlet from "figlet"; import type { WebSocket } from "ws"; import { createApp } from "./app.js"; -import { DEFAULT_DATABASE_URL } from "./constants.js"; +import { DEFAULT_DATABASE_URL, USER_PROJECT_ROOT_DIR } from "./constants.js"; import * as schema from "./db/schema.js"; +import { getTSServer } from "./lib/expand-function/tsserver/index.js"; import { setupRealtimeService } from "./lib/realtime/index.js"; import { getSetting } from "./lib/settings/index.js"; import { resolveWebhoncUrl } from "./lib/utils.js"; @@ -76,8 +77,7 @@ server.on("error", (err) => { // // Additionally, this will watch for changes to files in the project directory, // - If a file changes, send a new probe to the service -const watchDir = process.env.FPX_WATCH_DIR ?? process.cwd(); -startRouteProbeWatcher(watchDir); +startRouteProbeWatcher(USER_PROJECT_ROOT_DIR); // Set up websocket server setupRealtimeService({ server, path: "/ws", wsConnections }); @@ -92,3 +92,16 @@ if (proxyRequestsEnabled ?? false) { logger.debug("Proxy requests feature enabled."); await webhonc.start(); } + +// check settings if ai is enabled, and proactively start the typescript language server +const aiEnabled = await getSetting(db, "aiEnabled"); +if (aiEnabled ?? false) { + logger.debug( + "AI Request Generation enabled. Starting typescript language server", + ); + try { + await getTSServer(USER_PROJECT_ROOT_DIR); + } catch (error) { + logger.error("Error starting TSServer:", error); + } +} diff --git a/api/src/lib/ai/anthropic.ts b/api/src/lib/ai/anthropic.ts index c392034fe..24fdc6afb 100644 --- a/api/src/lib/ai/anthropic.ts +++ b/api/src/lib/ai/anthropic.ts @@ -19,12 +19,14 @@ type GenerateRequestOptions = { handler: string; baseUrl?: string; history?: Array; + handlerContext?: string; openApiSpec?: string; middleware?: { handler: string; method: string; path: string; }[]; + middlewareContext?: string; }; /** @@ -42,9 +44,11 @@ export async function generateRequestWithAnthropic({ method, path, handler, + handlerContext, history, openApiSpec, middleware, + middlewareContext, }: GenerateRequestOptions) { logger.debug( "Generating request data with Anthropic", @@ -54,8 +58,10 @@ export async function generateRequestWithAnthropic({ `method: ${method}`, `path: ${path}`, `handler: ${handler}`, - `openApiSpec: ${openApiSpec}`, - `middleware: ${middleware}`, + // `handlerContext: ${handlerContext}`, + // `openApiSpec: ${openApiSpec}`, + // `middleware: ${middleware}`, + // `middlewareContext: ${middlewareContext}`, ); const anthropicClient = new Anthropic({ apiKey, baseURL: baseUrl }); const userPrompt = await invokeRequestGenerationPrompt({ @@ -63,9 +69,11 @@ export async function generateRequestWithAnthropic({ method, path, handler, + handlerContext, history, openApiSpec, middleware, + middlewareContext, }); const toolChoice: Anthropic.Messages.MessageCreateParams.ToolChoiceTool = { diff --git a/api/src/lib/ai/index.ts b/api/src/lib/ai/index.ts index bb22b963b..04a4bfbc7 100644 --- a/api/src/lib/ai/index.ts +++ b/api/src/lib/ai/index.ts @@ -8,15 +8,18 @@ export async function generateRequestWithAiProvider({ method, path, handler, + handlerContext, history, openApiSpec, middleware, + middlewareContext, }: { inferenceConfig: Settings; persona: string; method: string; path: string; handler: string; + handlerContext?: string; history?: string[]; openApiSpec?: string; middleware?: { @@ -24,6 +27,7 @@ export async function generateRequestWithAiProvider({ method: string; path: string; }[]; + middlewareContext?: string; }) { const { openaiApiKey, @@ -43,9 +47,11 @@ export async function generateRequestWithAiProvider({ method, path, handler, + handlerContext, history, openApiSpec, middleware, + middlewareContext, }).then( (parsedArgs) => { return { data: parsedArgs, error: null }; @@ -67,9 +73,11 @@ export async function generateRequestWithAiProvider({ method, path, handler, + handlerContext, history, openApiSpec, middleware, + middlewareContext, }).then( (parsedArgs) => { return { data: parsedArgs, error: null }; diff --git a/api/src/lib/ai/openai.ts b/api/src/lib/ai/openai.ts index 007b84881..ddfca3bf4 100644 --- a/api/src/lib/ai/openai.ts +++ b/api/src/lib/ai/openai.ts @@ -11,6 +11,7 @@ type GenerateRequestOptions = { method: string; path: string; handler: string; + handlerContext?: string; history?: Array; openApiSpec?: string; middleware?: { @@ -18,6 +19,7 @@ type GenerateRequestOptions = { method: string; path: string; }[]; + middlewareContext?: string; }; /** @@ -35,9 +37,11 @@ export async function generateRequestWithOpenAI({ method, path, handler, + handlerContext, history, openApiSpec, middleware, + middlewareContext, }: GenerateRequestOptions) { logger.debug( "Generating request data with OpenAI", @@ -46,9 +50,11 @@ export async function generateRequestWithOpenAI({ `persona: ${persona}`, `method: ${method}`, `path: ${path}`, - `handler: ${handler}`, - `openApiSpec: ${openApiSpec}`, - `middleware: ${middleware}`, + // `handler: ${handler}`, + // `handlerContext: ${handlerContext}`, + // `openApiSpec: ${openApiSpec}`, + // `middleware: ${middleware}`, + // `middlewareContext: ${middlewareContext}`, ); const openaiClient = new OpenAI({ apiKey, baseURL: baseUrl }); const userPrompt = await invokeRequestGenerationPrompt({ @@ -56,9 +62,11 @@ export async function generateRequestWithOpenAI({ method, path, handler, + handlerContext, history, openApiSpec, middleware, + middlewareContext, }); const response = await openaiClient.chat.completions.create({ diff --git a/api/src/lib/ai/prompts.ts b/api/src/lib/ai/prompts.ts index e7de9caf0..2bd07c1e6 100644 --- a/api/src/lib/ai/prompts.ts +++ b/api/src/lib/ai/prompts.ts @@ -32,14 +32,17 @@ export const invokeRequestGenerationPrompt = async ({ method, path, handler, + handlerContext, history, openApiSpec, middleware, + middlewareContext, }: { persona: string; method: string; path: string; handler: string; + handlerContext?: string; history?: Array; openApiSpec?: string; middleware?: { @@ -47,6 +50,7 @@ export const invokeRequestGenerationPrompt = async ({ method: string; path: string; }[]; + middlewareContext?: string; }) => { const promptTemplate = persona === "QA" ? qaTesterPrompt : friendlyTesterPrompt; @@ -54,9 +58,11 @@ export const invokeRequestGenerationPrompt = async ({ method, path, handler, + handlerContext: handlerContext ?? "NO HANDLER CONTEXT", history: history?.join("\n") ?? "NO HISTORY", openApiSpec: openApiSpec ?? "NO OPENAPI SPEC", middleware: formatMiddleware(middleware), + middlewareContext: middlewareContext ?? "NO MIDDLEWARE CONTEXT", }); const userPrompt = userPromptInterface.value; return userPrompt; @@ -87,9 +93,15 @@ Here is the OpenAPI spec for the handler: Here is the middleware that will be applied to the request: {middleware} +Here is some additional context for the middleware that will be applied to the request: +{middlewareContext} + Here is the code for the handler: {handler} +Here is some additional context for the handler source code, if you need it: +{handlerContext} + `.trim(), ); @@ -113,9 +125,15 @@ Here is the OpenAPI spec for the handler: Here is the middleware that will be applied to the request: {middleware} +Here is some additional context for the middleware that will be applied to the request: +{middlewareContext} + Here is the code for the handler: {handler} +Here is some additional context for the handler source code, if you need it: +{handlerContext} + REMEMBER YOU ARE A QA. MISUSE THE API. BUT DO NOT MISUSE YOURSELF. Keep your responses short-ish. Including your random data. `.trim(), diff --git a/api/src/lib/expand-function/README.md b/api/src/lib/expand-function/README.md new file mode 100644 index 000000000..42060dcc8 --- /dev/null +++ b/api/src/lib/expand-function/README.md @@ -0,0 +1,97 @@ +# Static Analysis to Expand Functions + +> **NOTE** The original Pull Request for this functionality can be found [here](https://github.com/fiberplane/fpx/pull/291). + +## Overview + +The `expand-function` library provides functionality to look up and "expand" +functions in a user's codebase, providing more context to the LLM when generating +requests using AI. + +### The Problem + +Right now, when we need to generate a request with AI, all we have at our disposal are the stringified versions of compiled handler and middleware functions. + +If those functions rely on helper utilities to, say, validate certain headers or parameters, we end up in a pickle. The LLM doesn't have enough context to give a valid request back to us. It's effectively blind to certain critical logic. + +### The Solution + +So, our job is to locate the handler and middleware definitions in the code, and then statically analyze them, to find the definitions of any constants or utilities that they use to execute an incoming request. + +To achieve this, we have to do some terrible things. + +1. Map the compiled functions back to their locations in the source +2. Parse and analyze the abstract syntax tree of the source function +3. Apply heuristics to identify out-of-scope identifiers in the source function +4. Traverse the codebase to find the definitions of said out-of-scope identifiers +5. Repeat steps (3) and (4) recursively on any utility functions that are used in the functions we analyze + +The rest of the pr description will go through the decisions made to implement each of these steps. + +The 3rd party libraries/tools at our disposal are: + +- `acorn` and `source-map` - libraries for parsing source maps to go from compiled code back to the source +- `typescript` - the typescript compiler api, for parsing and traversing ASTs +- `typescript-language-server` - wrapper around `tsserver` (with which we communicate over stdio) +- `vscode-jsonrpc` - helpers for interfacing with the ts language server + +## Testing + +To play with this while developing locally, you need `FPX_WATCH_DIR` to be set +to the root of the example codebase you're testing against: + +```bash +FPX_WATCH_DIR=../examples/goose-quotes pnpm dev +``` + +Otherwise, you can just run the tests and develop from there. + +The most useful test is `expand-function.test.ts`, as it is effectively an +integration test for the library. + +```bash +pnpm test expand-function.test +``` + +Separately, there are unit tests for: + +- Source map resolution: `find-source-function.test.ts` (outside this lib, in the `lib/find-source-function` directory) +- Identifier analysis: `analyze-identifiers.test.ts` +- File search: `search-file.test.ts` +- Function search: `search-function.test.ts` + +If you find yourself wanting to use the node debugger, you can do so by adding +`debugger;` somewhere in the code, then modifying the smoke test located in +`expand-function-smoke-test.ts`. You can call this with: + +```bash +pnpm expand-function:debug +``` + +Then, launch the node debugger in Chrome (`chrome://inspect`) to attach to the +process and set additional breakpoints. + +## Usage + +The return result of `expandFunction` should be recursed in order to build up +the necessary context for the LLM to make an accurate assessment of the +function. Note that the return result contains a key, `context`, which is an +array of `ExpandedFunctionContext` objects. Each of those context objects may, +in turn, also contain a `context` key. + +Look in the `inference` routes in the Studio to see how this is ultimately done. + +## Improvements (TODOs) + +- Cache results of `searchForFunction` to reduce filesystem lookups +- Remove dependency on `typescript-language-server` + - Take inspiration from Ade's experiments with only using `createProgram` to + provide import resolution + (https://github.com/fiberplane/fpx/commit/c477a0986660497201c359afc7540970b6adada3) +- Re-introduce the `typescript-language-server`, and write a typescript plugin + to provide the same functionality via custom workspace commands (this will + allow us to use the typescript version of the user's project, rather than our + version in this repo) +- Look for other common source maps in the project to provide more context + (webpack, etc) -- **right now only works with Wrangler projects** + diff --git a/api/src/lib/expand-function/ast-helpers/ast-helpers.ts b/api/src/lib/expand-function/ast-helpers/ast-helpers.ts new file mode 100644 index 000000000..8fb517c01 --- /dev/null +++ b/api/src/lib/expand-function/ast-helpers/ast-helpers.ts @@ -0,0 +1,152 @@ +import fs from "node:fs"; +import * as ts from "typescript"; +import { URI } from "vscode-uri"; +import type { Definition as TSServerDefinition } from "../tsserver/index.js"; +import type { FunctionContextType } from "../types.js"; + +export function getParentImportDeclaration( + node: ts.Node, +): ts.ImportDeclaration | undefined { + let parent = node.parent; + while (parent && !ts.isSourceFile(parent)) { + if (ts.isImportDeclaration(parent)) { + return parent; + } + parent = parent.parent; + } + return undefined; +} + +type DefinitionText = { + type: FunctionContextType; + text: string; + definitionNode?: ts.Node; +}; + +export function getDefinitionText( + node: ts.Node, + sourceFile: ts.SourceFile, +): DefinitionText | undefined { + // Check: Variable declaration with initializer + // `const y = ...` + // `let x = ...` + if (ts.isVariableDeclaration(node) && node.initializer) { + return { + type: "variable", + text: node.initializer.getText(sourceFile), + }; + } + + // Function declaration, arrow function, or function expression + // Declaration: `function f() { ... }` + // Arrow: `(c) => { ... }` + // Expression: `const h = function () { ... }` (or e.g., a function passed inline as a callback) + if ( + ts.isFunctionDeclaration(node) || + ts.isArrowFunction(node) || + ts.isFunctionExpression(node) + ) { + return { + type: "function", + text: node.getText(sourceFile), + definitionNode: node, + }; + } + + // Check if the node is an identifier and if the parent node is a function declaration + if (ts.isIdentifier(node) && ts.isFunctionDeclaration(node.parent)) { + return { + type: "function", + text: node.parent.getText(sourceFile), + definitionNode: node.parent, + }; + } + + // Check if the node is an identifier and the parent node is a variable declaration with initializer + // `const myVariable = someValue;` + if ( + ts.isIdentifier(node) && + ts.isVariableDeclaration(node.parent) && + node.parent.initializer + ) { + return { + type: "variable", + text: node.parent.initializer.getText(sourceFile), + }; + } + + // Check for type alias declarations + // `type MyType = ...` + if (ts.isTypeAliasDeclaration(node)) { + return { + type: "type", + text: node.getText(sourceFile), + definitionNode: node, + }; + } + + // Check if the node is an identifier and the parent node is a type alias declaration + if (ts.isIdentifier(node) && ts.isTypeAliasDeclaration(node.parent)) { + return { + type: "type", + text: node.parent.getText(sourceFile), + definitionNode: node.parent, + }; + } + + return undefined; +} + +export function findNodeAtPosition( + sourceFile: ts.SourceFile, + position: { line: number; character: number }, +): ts.Node | undefined { + function find(node: ts.Node): ts.Node | undefined { + if (positionInNode(sourceFile, node, position)) { + return ts.forEachChild(node, find) || node; + } + } + return find(sourceFile); +} + +function positionInNode( + sourceFile: ts.SourceFile, + node: ts.Node, + position: { line: number; character: number }, +): boolean { + const { line, character } = position; + const start = sourceFile.getLineAndCharacterOfPosition(node.getStart()); + const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd()); + return ( + start.line <= line && + line <= end.line && + (start.line < line || start.character <= character) && + (line < end.line || character <= end.character) + ); +} + +/** + * Takes a definition from the TypeScript language server and returns the corresponding node and source file. + * + * @param definition - The definition object from the TypeScript language server + * @returns An object containing the node, source file, and definition file path + */ +export function definitionToNode(definition: TSServerDefinition) { + const definitionUri = URI.parse(definition.uri); + const definitionFilePath = definitionUri.fsPath; + + // Read the file content for the file that contains the definition + const fileContent = fs.readFileSync(definitionFilePath, "utf-8"); + + // Parse the file to do ast analysis + const sourceFile = ts.createSourceFile( + definitionFilePath, + fileContent, + ts.ScriptTarget.Latest, + true, + ); + + const node = findNodeAtPosition(sourceFile, definition.range.start); + + return { node, sourceFile, definitionFilePath }; +} diff --git a/api/src/lib/expand-function/ast-helpers/identifier-analyzer.test.ts b/api/src/lib/expand-function/ast-helpers/identifier-analyzer.test.ts new file mode 100644 index 000000000..ad41220a8 --- /dev/null +++ b/api/src/lib/expand-function/ast-helpers/identifier-analyzer.test.ts @@ -0,0 +1,457 @@ +import * as ts from "typescript"; +import { describe, expect, it } from "vitest"; +import { analyzeOutOfScopeIdentifiers } from "./identifier-analyzer.js"; + +function createSourceFile(content: string): ts.SourceFile { + return ts.createSourceFile("test.ts", content, ts.ScriptTarget.Latest, true); +} + +// NOTE - This helper does not parse out anonymous arrow functions +function getFunctionNode( + sourceFile: ts.SourceFile, +): ts.FunctionDeclaration | ts.ArrowFunction | ts.FunctionExpression { + let functionNode: + | ts.FunctionDeclaration + | ts.ArrowFunction + | ts.FunctionExpression + | undefined; + + ts.forEachChild(sourceFile, (node) => { + if (ts.isFunctionDeclaration(node)) { + functionNode = node; + } else if (ts.isVariableStatement(node)) { + ts.forEachChild(node.declarationList, (declaration) => { + if (ts.isVariableDeclaration(declaration) && declaration.initializer) { + if (ts.isArrowFunction(declaration.initializer)) { + functionNode = declaration.initializer; + } else if (ts.isFunctionExpression(declaration.initializer)) { + functionNode = declaration.initializer; + } + } + }); + } else if (ts.isExpressionStatement(node)) { + // Check for anonymous arrow functions + if (ts.isArrowFunction(node.expression)) { + functionNode = node.expression; + } + } + }); + + if (!functionNode) { + throw new Error("No function node found in the source file"); + } + + return functionNode; +} + +describe("analyzeOutOfScopeIdentifiers", () => { + it("should NOT return a function declaration's name as out of scope", () => { + const source = "function outer() {}"; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).not.toEqual( + expect.arrayContaining([expect.objectContaining({ name: "outer" })]), + ); + }); + it("should identify an out-of-scope variable", () => { + const source = ` + function test() { + console.log(outOfScope); + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: "outOfScope", + }), + ]), + ); + }); + + it("should NOT identify locally declared const as an out-of-scope identifier", () => { + const source = ` + function test() { + console.log(outOfScope); + const localConst = 1; + console.log(localConst); + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).not.toContainEqual( + expect.objectContaining({ name: "localConst" }), + ); + }); + + it("should NOT identify locally declared var as an out-of-scope identifier", () => { + const source = ` + function test() { + console.log(outOfScope); + var localVar = 2; + console.log(localVar); + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).not.toContainEqual( + expect.objectContaining({ name: "localVar" }), + ); + }); + + it("should NOT identify locally declared `let` as an out-of-scope identifier", () => { + const source = ` + function test() { + console.log(outOfScope); + let localLet = 3; + console.log(localLet); + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).not.toContainEqual( + expect.objectContaining({ name: "localLet" }), + ); + }); + + it("should consider Web Standard global like `console` (from `console.log`) as out-of-scope identifier", () => { + const source = ` + function test() { + console.log(outOfScope); + const localVar = 1; + console.log(localVar); + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).toEqual( + expect.arrayContaining([expect.objectContaining({ name: "console" })]), + ); + }); + + describe("arrow functions", () => { + it("should handle arrow functions assigned to variables", () => { + const source = ` + const test = () => { + console.log(outOfScope); + const localVar = 1; + console.log(localVar); + }; + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: "outOfScope" }), + expect.objectContaining({ name: "console" }), + ]), + ); + + const forbiddenNames = ["test", "localVar"]; + for (const name of forbiddenNames) { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + } + }); + it("should handle anonymous arrow functions", () => { + const source = ` + () => { + console.log(outOfScope); + const localVar = 1; + console.log(localVar); + }; + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: "outOfScope" }), + expect.objectContaining({ name: "console" }), + ]), + ); + + const forbiddenNames = ["localVar"]; + for (const name of forbiddenNames) { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + } + }); + }); + + it("should consider local variables derived from out of scope variables as in scope", () => { + const source = ` + function complex(param1) { + const local1 = outOfScope1; + let local2 = param1 + outOfScope2; + + function inner() { + const innerLocal = local1 + outOfScope3; + return innerLocal + local2 + outOfScope4; + } + + return inner() + obj.property + outOfScope5; + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: "outOfScope1" }), + expect.objectContaining({ name: "outOfScope2" }), + expect.objectContaining({ name: "outOfScope3" }), + expect.objectContaining({ name: "outOfScope4" }), + expect.objectContaining({ name: "outOfScope5" }), + expect.objectContaining({ name: "obj" }), + ]), + ); + + const forbiddenNames = ["inner", "local1", "local2", "param1"]; + // biome-ignore lint/complexity/noForEach: + forbiddenNames.forEach((name) => { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + }); + }); + + // NOTE - We may want to change some of this behavior going forward, but it makes things much simpler for now + // Right now we're just going to ignore any properties on a given out-of-scope object. + // Doing so could lead to us adding in LOTS of context, e.g., when someone imports an entire module file. + // `import * as schema from "./db";` + // + // However, that might be preferable to instead receiving a bunch of identifiers and having to do oodles of lookups. + // + describe("property access and destructuring", () => { + it("should not return identifiers that are used to access object properties", () => { + const source = ` + function test() { + console.log(obj.property); + globalObject.someMethod(); + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: "console" }), + expect.objectContaining({ name: "obj" }), + expect.objectContaining({ name: "globalObject" }), + ]), + ); + + const forbiddenNames = ["log", "property", "someMethod"]; + for (const name of forbiddenNames) { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + } + }); + + it("should consider property access expressions on function parameters as in-scope", () => { + const source = ` + function test(c) { + const { shouldHonk } = c.req.query(); + const honk = typeof shouldHonk !== "undefined" ? "Honk honk!" : ""; + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + const forbiddenNames = ["c", "req", "query"]; + for (const name of forbiddenNames) { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + } + }); + + it("should consider destructured variables from in-scope identifiers as local scope", () => { + const source = ` + function test(c) { + const { shouldHonk } = c.req.query(); + const honk = typeof shouldHonk !== "undefined" ? "Honk honk!" : ""; + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).not.toContainEqual( + expect.objectContaining({ name: "shouldHonk" }), + ); + }); + }); + + // Okay, this doesn't matter too much, since we'd expand OutOfScopeConstants anyhow + it.skip("should consider destructured variables from out-of-scope identifiers as out of scope", () => { + const source = ` + function test(_c) { + const { shouldHonk } = OutOfScopeConstants; + const honk = typeof shouldHonk !== "undefined" ? "Honk honk!" : ""; + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).toContainEqual( + expect.objectContaining({ name: "OutOfScopeConstants" }), + ); + expect(result).toContainEqual( + expect.objectContaining({ name: "shouldHonk" }), + ); + }); + + describe("function parameters", () => { + it("should NOT consider function declaration parameters as out-of-scope identifiers", () => { + const source = ` + function test(param1, param2) { + console.log(param1, param2, outOfScope); + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + const forbiddenNames = ["param1", "param2"]; + for (const name of forbiddenNames) { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + } + }); + + it("should NOT consider function expression parameters as out-of-scope identifiers", () => { + const source = ` + function(param1, param2) { + console.log(param1, param2, outOfScope); + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + const forbiddenNames = ["param1", "param2"]; + for (const name of forbiddenNames) { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + } + }); + + it("should NOT consider arrow function parameters as out-of-scope identifiers", () => { + const source = ` + const test = (param1, param2) => { + console.log(param1, param2, outOfScope); + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + const forbiddenNames = ["param1", "param2"]; + for (const name of forbiddenNames) { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + } + }); + }); + + describe("nested functions", () => { + it("should return out of scope identifiers from nested functions, but not the nested function's name", () => { + const source = ` + function outer() { + const outerVar = 1; + function inner() { + console.log(outerVar); + return meh; + } + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).toEqual( + expect.arrayContaining([expect.objectContaining({ name: "meh" })]), + ); + + const forbiddenNames = ["inner", "outer", "outerVar"]; + // biome-ignore lint/complexity/noForEach: + forbiddenNames.forEach((name) => { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + }); + }); + + it("should not consider parameters of functions defined within the function as out of scope", () => { + const source = ` + function test(userId, eventId) { + webhooks.on( + ["issues.opened", "star.created", "watch.started"], + async ({ payload, name }) => { + await db.insert(events).values({ + eventId, + eventAction: payload.action, + eventName: name, + repoId: payload.repository.id, + userId, + }); + } + } + `; + const sourceFile = createSourceFile(source); + const functionNode = getFunctionNode(sourceFile); + + const result = analyzeOutOfScopeIdentifiers(functionNode, sourceFile); + + expect(result).toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: "db" }), + expect.objectContaining({ name: "webhooks" }), + expect.objectContaining({ name: "events" }), + ]), + ); + + const forbiddenNames = [ + "test", + "userId", + "eventId", + "payload", + "action", + "repository", + "id", + "name", + ]; + // biome-ignore lint/complexity/noForEach: + forbiddenNames.forEach((name) => { + expect(result).not.toContainEqual(expect.objectContaining({ name })); + }); + }); + }); +}); diff --git a/api/src/lib/expand-function/ast-helpers/identifier-analyzer.ts b/api/src/lib/expand-function/ast-helpers/identifier-analyzer.ts new file mode 100644 index 000000000..3e36576a3 --- /dev/null +++ b/api/src/lib/expand-function/ast-helpers/identifier-analyzer.ts @@ -0,0 +1,276 @@ +import * as ts from "typescript"; +import logger from "../../../logger.js"; + +export interface OutOfScopeIdentifier { + /** The name of the identifier used but not declared within the function */ + name: string; + /** The position of the identifier in the code */ + position: ts.LineAndCharacter; +} + +/** + * Analyzes a function node to find out-of-scope identifiers. + * + * @param functionNode - The TypeScript AST node representing the function to analyze. + * @param sourceFile - The TypeScript SourceFile object containing the function. + * + * @returns An array of OutOfScopeIdentifier objects, each representing an identifier + * used within the function but not declared locally. + * + * @description + * This function performs a single-pass analysis on the given function node using a scope stack: + * 1. It tracks local declarations (variables and parameters) as it traverses the AST. + * 2. It identifies used identifiers that are not in the current scope stack. + * + * The function handles property access expressions specially: + * - It ignores property names in property access expressions. + * - It includes the base object of a property access if it's not locally declared. + * + * Note: This analysis does not consider closure variables or imported identifiers + * as "in scope". It only looks at declarations within the function itself and its + * nested scopes. + * + * The function also properly handles nested function declarations, function + * expressions, and arrow functions, creating new scopes as appropriate. + */ +export function analyzeOutOfScopeIdentifiers( + functionNode: + | ts.FunctionDeclaration + | ts.ArrowFunction + | ts.FunctionExpression, + sourceFile: ts.SourceFile, +): OutOfScopeIdentifier[] { + if (!functionNode) { + return []; + } + + // Type verification + if ( + !ts.isFunctionDeclaration(functionNode) && + !ts.isArrowFunction(functionNode) && + !ts.isFunctionExpression(functionNode) + ) { + logger.warn("Unexpected node type passed to analyzeOutOfScopeIdentifiers:"); + // @ts-ignore + logger.warn("Node kind:", ts.SyntaxKind[functionNode?.kind]); + // @ts-ignore + logger.warn("Node text:", functionNode?.getText?.(sourceFile)); + return []; + } + + const usedIdentifiers = new Map(); + + // Stack to keep track of scopes + const scopeStack: Set[] = []; + + function pushScope() { + scopeStack.push(new Set()); + } + + function popScope() { + scopeStack.pop(); + } + + function addDeclaration(name: string) { + if (scopeStack.length > 0) { + scopeStack[scopeStack.length - 1].add(name); + } + } + + function isDeclared(name: string): boolean { + for (let i = scopeStack.length - 1; i >= 0; i--) { + if (scopeStack[i].has(name)) { + return true; + } + } + return false; + } + + // Start traversing the function node + function traverse(node: ts.Node) { + if (ts.isFunctionDeclaration(node)) { + // Add function name to the outer scope + if (node.name && ts.isIdentifier(node.name)) { + addDeclaration(node.name.text); + } + + // Push a new scope for the function body + pushScope(); + + // Add parameters to the current scope + for (const param of node.parameters) { + collectBindings(param.name); + } + + if (node.body) { + traverse(node.body); + } + + popScope(); + return; + } + + if (ts.isFunctionExpression(node) || ts.isArrowFunction(node)) { + // Push a new scope for the function body + pushScope(); + + // Add parameters to the current scope + for (const param of node.parameters) { + collectBindings(param.name); + } + + // If it's a named function expression, add its name to the inner scope + if (node.name && ts.isIdentifier(node.name)) { + addDeclaration(node.name.text); + } + + if (node.body) { + traverse(node.body); + } + + popScope(); + return; + } + + if (ts.isBlock(node)) { + pushScope(); + + for (const statement of node.statements) { + traverse(statement); + } + + popScope(); + return; + } + + if (ts.isVariableStatement(node)) { + for (const decl of node.declarationList.declarations) { + collectBindings(decl.name); + if (decl.initializer) { + traverse(decl.initializer); + } + } + return; + } + + if (ts.isVariableDeclaration(node)) { + collectBindings(node.name); + if (node.initializer) { + traverse(node.initializer); + } + return; + } + + if (ts.isPropertyAccessExpression(node)) { + // Traverse the base expression + traverse(node.expression); + + // NOTE - The code below is commented out because we don't want to consider property names as out-of-scope identifiers + // It adds too much noise and complexity to the analysis. + // We will rely on traversing the parent object's definition to understand what the property is or represents. + // + // If you uncomment this code, the unfortunate thing that happens is that if `c` is in scope, then `c.req` will return `req` as out of scope + // + // *** + // + // Handle the property name + // + // if (!isDeclared(node.name.text)) { + // const pos = sourceFile.getLineAndCharacterOfPosition( + // node.name.getStart(), + // ); + // usedIdentifiers.set(node.name.text, pos); + // } + + return; + } + + if (ts.isElementAccessExpression(node)) { + // Traverse the object and the index expression + traverse(node.expression); + traverse(node.argumentExpression); + return; + } + + if (ts.isCallExpression(node)) { + // Traverse the function being called and its arguments + traverse(node.expression); + for (const arg of node.arguments) { + traverse(arg); + } + return; + } + + if (ts.isIdentifier(node)) { + const parent = node.parent; + const name = node.text; + + // Ignore property names in property assignments and declarations + const isIgnoredPropertyName = + (ts.isPropertyAssignment(parent) && parent.name === node) || + (ts.isShorthandPropertyAssignment(parent) && parent.name === node) || + (ts.isBindingElement(parent) && parent.propertyName === node) || + (ts.isPropertyDeclaration(parent) && parent.name === node) || + (ts.isMethodDeclaration(parent) && parent.name === node) || + (ts.isClassDeclaration(parent) && parent.name === node); + + if (isIgnoredPropertyName) { + // The identifier is a property name in an assignment or declaration; ignore it + return; + } + + if (!isDeclared(name)) { + const pos = sourceFile.getLineAndCharacterOfPosition(node.getStart()); + usedIdentifiers.set(name, pos); + } + return; + } + + // For all other nodes, continue traversal + node.forEachChild(traverse); + } + + function collectBindings(name: ts.BindingName) { + if (ts.isIdentifier(name)) { + addDeclaration(name.text); + } else if ( + ts.isObjectBindingPattern(name) || + ts.isArrayBindingPattern(name) + ) { + for (const element of name.elements) { + if (ts.isBindingElement(element)) { + collectBindings(element.name); + } + } + } + } + + // Initialize the scope with function parameters and the function name + pushScope(); + + // Add function parameters to the initial scope + for (const param of functionNode.parameters) { + collectBindings(param.name); + } + + // Add function name to the scope if it exists + if ( + ts.isFunctionDeclaration(functionNode) && + functionNode.name && + ts.isIdentifier(functionNode.name) + ) { + addDeclaration(functionNode.name.text); + } + + if (functionNode.body) { + traverse(functionNode.body); + } + + popScope(); + + // Convert the map to an array of OutOfScopeIdentifier objects + return Array.from(usedIdentifiers, ([name, position]) => ({ + name, + position, + })); +} diff --git a/api/src/lib/expand-function/ast-helpers/index.ts b/api/src/lib/expand-function/ast-helpers/index.ts new file mode 100644 index 000000000..d3f56d0e5 --- /dev/null +++ b/api/src/lib/expand-function/ast-helpers/index.ts @@ -0,0 +1,2 @@ +export * from "./ast-helpers.js"; +export * from "./identifier-analyzer.js"; diff --git a/api/src/lib/expand-function/ast-helpers/program.ts b/api/src/lib/expand-function/ast-helpers/program.ts new file mode 100644 index 000000000..49d62c28a --- /dev/null +++ b/api/src/lib/expand-function/ast-helpers/program.ts @@ -0,0 +1,53 @@ +/** + * NOTE - **NOT IN USE** currently, but this is a good starting point + * for creating a program from a typescript project in order to + * perform static analysis. + * + * ... + */ + +import * as path from "node:path"; +import * as ts from "typescript"; + +/** + * Create a program from a typescript project + * in order to perform static analysis. + * + const program = getProgram('/path/to/your/project'); + const checker = program.getTypeChecker(); + * + */ +export function getProgram(pathToProject: string): ts.Program { + const configPath = ts.findConfigFile( + pathToProject, + ts.sys.fileExists, + "tsconfig.json", + ); + if (!configPath) { + throw new Error("Could not find a valid 'tsconfig.json'."); + } + + const configFile = ts.readConfigFile(configPath, ts.sys.readFile); + if (configFile.error) { + throw new Error("Error reading 'tsconfig.json'."); + } + + const parsedCommandLine = ts.parseJsonConfigFileContent( + configFile.config, + ts.sys, + path.dirname(configPath), + ); + + if (parsedCommandLine.errors.length > 0) { + throw new Error("Error parsing 'tsconfig.json'."); + } + + return ts.createProgram({ + rootNames: parsedCommandLine.fileNames, + options: parsedCommandLine.options, + }); +} + +// Usage + +// Now you can perform various analyses using the TypeScript Compiler API diff --git a/api/src/lib/expand-function/expand-function.ts b/api/src/lib/expand-function/expand-function.ts new file mode 100644 index 000000000..216366294 --- /dev/null +++ b/api/src/lib/expand-function/expand-function.ts @@ -0,0 +1,420 @@ +import fs from "node:fs"; +import ts from "typescript"; +import logger from "../../logger.js"; +import { + type OutOfScopeIdentifier, + analyzeOutOfScopeIdentifiers, + definitionToNode, + getDefinitionText, + getParentImportDeclaration, +} from "./ast-helpers/index.js"; +import { + contextForImport, + extractPackageName, + isDependency, + resolveModulePath, +} from "./imports/index.js"; +import { searchFunction } from "./search-function/index.js"; +import { + getFileUri, + getTSServer, + getTextDocumentDefinition, + getTsSourceDefinition, + openFile, +} from "./tsserver/index.js"; +import type { FunctionContextType } from "./types.js"; + +type ExpandedFunctionContextEntry = { + /** The name of the constant or utility in the code */ + name: string; + /** + * The type of the constant or utility. + * This will be used to help determine whether or not to recursively comb + * helper utilities to expand context of their utilities, etc. + * + * For now, "unknown" is a placeholder for other ast nodes we do not want to want to expand. + */ + type: FunctionContextType; + /** The position of the constant or utility in the code */ + position: { line: number; character: number }; + definition?: { + uri: string; + range: { + start: { line: number; character: number }; + end: { line: number; character: number }; + }; + /** The text of the definition (utility function, constant value, etc.) */ + text: string | undefined; + }; + /** The package (in node_modules) that the constant or utility is defined in */ + package?: string; + /** + * Hurrah for recursive types! + * + * The child context of the constant or utility. + * That is, if the constant or utility is a function, + * this will contain definitions for any of the function's out-of-scope identifiers. + */ + context?: ExpandedFunctionContext; +}; + +export type ExpandedFunctionContext = Array; + +export type ExpandedFunctionResult = { + /** The file in which the function was found */ + file: string; + /** The line on which the function definition starts */ + startLine: number; + /** The column on which the function definition starts */ + startColumn: number; + /** The line on which the function definition ends */ + endLine: number; + /** The column on which the function definition ends */ + endColumn: number; + context: ExpandedFunctionContext; +}; + +type ExpandFunctionOptions = { + skipSourceMap?: boolean; + debug?: boolean; + hints?: { sourceFunction?: string | null; sourceFile?: string | null }; +}; + +/** + * Expands the context of a specified function within the codebase by analyzing its out-of-scope identifiers + * and recursively retrieving their definitions. This function searches for the target function, identifies + * all external references it makes, and gathers detailed information about each reference to build a comprehensive + * context. The result includes the location of the function and the expanded context of its dependencies. + * + * @param projectRoot - The root directory of the project. + * @param compiledFunction - The string representation of the function to expand (compiled JavaScript, not TypeScript). + * @param options - Optional parameters for the expansion process. + * @param options.skipSourceMap - If `true`, skips the source map search. Useful for testing scenarios. + * @param options.debug - If `true`, enables debug logging for detailed tracing. + * @param options.hints - Provides contextual hints for the search. + * @param options.hints.sourceFunction - The string representation of the source TypeScript function to expand. + * @param options.hints.sourceFile - The file path containing the source function to expand. + * @returns A promise that resolves to an `ExpandedFunctionResult` containing the expanded context of the function, + * or `null` if the function is not found within the project. + * + * @example + * ```typescript + * const result = await expandFunction('/path/to/project', 'function example2(t) { ... }', { + * debug: true, + * hints: { + * sourceFunction: 'function example(t: T) { ... }', + * sourceFile: 'src/example.ts', + * }, + * }); + * ``` + */ +export async function expandFunction( + projectRoot: string, + compiledFunction: string, + options: ExpandFunctionOptions = {}, +): Promise { + const searchResult = await searchFunction( + projectRoot, + compiledFunction, + options, + ); + if (!searchResult) { + const truncatedFunc = compiledFunction.slice(0, 100); + logger.warn( + `[expandFunction] No search result found for ${truncatedFunc}...`, + ); + return null; + } + + const identifiers = analyzeOutOfScopeIdentifiers( + searchResult.node, + searchResult.sourceFile, + ); + + const context = await extractContext( + projectRoot, + searchResult.file, + identifiers, + ); + + return { + ...searchResult, + context, + }; +} + +/** + * Extracts the expanded context of out-of-scope identifiers within a function by analyzing their definitions. + * This involves querying the TypeScript server to locate definitions, handling namespace imports, and recursively + * expanding the context for functions. The function aggregates detailed information about each identifier, + * including its type, position, definition details, and package information if applicable. + * + * @param projectRoot - The root directory of the project. + * @param filePath - The file path where the original function is located. + * @param identifiers - An array of `OutOfScopeIdentifier` representing identifiers that are not defined within the function's scope. + * @param options - Optional parameters to modify the extraction behavior. + * @param options.debug - If `true`, enables debug logging for detailed tracing during context extraction. + * @returns A promise that resolves to an `ExpandedFunctionContext`, detailing the context of each out-of-scope identifier. + * + * @example + * ```typescript + * const context = await extractContext('/path/to/project', 'src/example.ts', identifiers, { debug: true }); + * ``` + */ +async function extractContext( + projectRoot: string, + filePath: string, + identifiers: OutOfScopeIdentifier[], + options: { debug?: boolean } = { debug: false }, +): Promise { + const { debug } = options; + const context: ExpandedFunctionContext = []; + + if (!identifiers?.length) { + if (debug) { + logger.debug( + "[debug] No out of scope identifiers found in function, skipping context extraction", + ); + } + return context; + } + + try { + const { connection } = await getTSServer(projectRoot); + + // Open the document containing the function + // This makes the TSServer aware of the codebase, and allows us to execute requests + // We do this to get more information on the definitions of the function's out-of-scope identifiers + // + await openFile(connection, filePath); + + const funcFileUri = getFileUri(filePath); + + // Loop through each identifier in the function and find its definition + for (const identifier of identifiers) { + const [sourceDefinition, textDocumentDefinition] = await Promise.all([ + getTsSourceDefinition(connection, funcFileUri, identifier.position), + getTextDocumentDefinition(connection, funcFileUri, identifier.position), + ]); + + // Here we can filter out standard globals that are defined in the runtime + // (e.g., `console`, `URL`, `Number`, etc.) + // We can do this because the textDocumentDefinition will be a .d.ts file, while the sourceDefinition will not be present + // This is a bit of a hack, but it works for now + const isStandardGlobal = + !sourceDefinition && textDocumentDefinition?.uri?.endsWith(".d.ts"); + if (isStandardGlobal) { + if (debug) { + logger.debug( + `[debug] Skipping expansion of ${identifier.name} as it is likely a standard global in the runtime`, + ); + } + continue; + } + + if (sourceDefinition) { + // Find the node at the definition position + const { node, sourceFile, definitionFilePath } = + definitionToNode(sourceDefinition); + + // If there's a node, we can try to extract the value of the definition + if (node) { + // First, handle the case where it was imported from another file. + // As of writing, we will hit this case when you do `import * as schema from "./db"` + // + const parentImportDeclaration = getParentImportDeclaration(node); + if ( + parentImportDeclaration && + ts.isImportDeclaration(parentImportDeclaration) + ) { + const importClause = parentImportDeclaration.importClause; + + // Check if it's a namespace import (e.g., import * as schema from "./db") + if ( + importClause?.namedBindings && + ts.isNamespaceImport(importClause.namedBindings) + ) { + const namespaceName = importClause.namedBindings.name.text; + const moduleSpecifier = parentImportDeclaration.moduleSpecifier + .getText() + .replace(/['"]/g, ""); + + // Resolve the imported module's file path using a utility that can account for TypeScript path aliases + const importedFilePath = resolveModulePath( + moduleSpecifier, + filePath, + projectRoot, + ); + + if (!importedFilePath) { + logger.warn( + `[extractContext] Failed to resolve imported file path for ${identifier.name}`, + ); + continue; + } + + // Read the contents of the imported file + let importedFileContent: string; + try { + importedFileContent = await fs.promises.readFile( + importedFilePath, + "utf-8", + ); + } catch (readError) { + logger.warn( + `[extractContext] Failed to read imported file at ${importedFilePath} for namespace import ${namespaceName}`, + readError, + ); + continue; + } + + // Create a context entry with the entire file's contents + const contextEntry: ExpandedFunctionContextEntry = { + name: namespaceName, + type: "unknown", + position: identifier.position, + definition: { + uri: getFileUri(importedFilePath), + range: { + start: { line: 0, character: 0 }, + end: { + line: Number.MAX_SAFE_INTEGER, + character: Number.MAX_SAFE_INTEGER, + }, + }, + text: importedFileContent, + }, + // Optionally include package information if applicable + package: extractPackageName(sourceDefinition.uri) ?? undefined, + }; + + context.push(contextEntry); + continue; + } + + const contextEntry = await contextForImport( + connection, + projectRoot, + definitionFilePath, + parentImportDeclaration, + node, + identifier, + ); + + // TODO - Recurse definition from imported files (not implemented yet) + if (contextEntry) { + context.push(contextEntry); + continue; + } + + logger.warn( + `[extractContext] Failed to follow import for ${identifier.name}`, + ); + } + + // HACK - If we resolved the definition to node_modules, + // we can skip any recursive expansion and just add the import as context for now + if (isDependency(sourceDefinition?.uri)) { + if (debug) { + logger.debug( + `[debug] ${identifier.name} is likely an installed dependency`, + ); + } + + const contextEntry: ExpandedFunctionContextEntry = { + name: identifier.name, + // HACK - `unknown` just means "do not expand this" + type: "unknown", + position: identifier.position, + definition: { + uri: sourceDefinition.uri, + range: sourceDefinition.range, + // NOTE - We do not include definition text here, since it can be huge (since this is from a node_modules package) + text: "#third-party-library-code", + }, + package: extractPackageName(sourceDefinition.uri) ?? undefined, + }; + context.push(contextEntry); + continue; + } + + const valueText = getDefinitionText(node, sourceFile); + + const contextEntry: ExpandedFunctionContextEntry = { + name: identifier.name, + type: valueText?.type ?? "unknown", + position: identifier.position, + definition: { + uri: sourceDefinition.uri, + range: sourceDefinition.range, + text: valueText?.text, + }, + }; + + if (debug) { + logger.debug( + `[debug] [extractContext] Context entry for ${identifier.name}`, + contextEntry, + ); + } + + // Recursively expand context if the identifier is a function + if (contextEntry?.type === "function") { + const functionNode = valueText?.definitionNode ?? node; + if (!functionNode) { + logger.warn( + `[extractContext] No function body found for ${identifier.name}`, + ); + continue; + } + + // Do type narrowing on the result to appease the call to analyzeOutOfScopeIdentifiers + if ( + !ts.isFunctionDeclaration(functionNode) && + !ts.isArrowFunction(functionNode) && + !ts.isFunctionExpression(functionNode) + ) { + logger.warn( + `[extractContext] An unexpected node was returned for ${identifier.name}`, + ); + continue; + } + + const functionIdentifiers = analyzeOutOfScopeIdentifiers( + functionNode, + sourceFile, + ); + + if (debug) { + logger.debug( + `[debug] [extractContext] Analyzed NESTED out of scope identifiers for ${identifier.name}`, + functionIdentifiers, + ); + } + + const subContext = await extractContext( + projectRoot, + sourceDefinition.uri.replace(/^file:\/\//, ""), + functionIdentifiers, + ); + contextEntry.context = subContext; + } + + context.push(contextEntry); + } else { + logger.warn( + `[extractContext] AST parsing found no definition found for ${identifier.name} in ${definitionFilePath}`, + ); + } + } else { + logger.warn( + `[extractContext] TSServer found no definition found for ${identifier.name}`, + ); + } + } + } catch (error) { + logger.error("[extractContext] Error querying TSServer:", error); + } + + return context; +} diff --git a/api/src/lib/expand-function/imports/context-for-import.ts b/api/src/lib/expand-function/imports/context-for-import.ts new file mode 100644 index 000000000..7f0a01d57 --- /dev/null +++ b/api/src/lib/expand-function/imports/context-for-import.ts @@ -0,0 +1,193 @@ +import * as fs from "node:fs"; +import * as ts from "typescript"; +import type { MessageConnection } from "vscode-jsonrpc"; +import logger from "../../../logger.js"; +import { + type OutOfScopeIdentifier, + getDefinitionText, +} from "../ast-helpers/index.js"; +import { getFileUri, openFile } from "../tsserver/index.js"; +import { resolveModulePath } from "./resolve-imports.js"; + +export async function contextForImport( + tsserver: MessageConnection, + _projectRoot: string, // TODO - Use this to resolve node module imports + currentFilePath: string, + importNode: ts.ImportDeclaration, + identifierNode: ts.Node, + identifier: OutOfScopeIdentifier, +) { + logger.debug( + `[debug][contextForImport] Going to follow import for identifier: ${identifier.name}`, + ); + + // So. Sometimes, for `import * as thing from "./my-module"`, + // the "_typescript.goToSourceDefinition" will return the import declaration. + // In this case, we can try following the import with another goToSourceDefinition call + // but this time on the module specifier. + // + // For now, I'm okay with simply not expanding these imports, but this is something + // we will want to handle in the future. + // + // const doubleClickedImportDefinition = await getTsSourceDefinition( + // tsserver, + // currentFilePath, + // identifierNode.getSourceFile().getLineAndCharacterOfPosition(identifierNode.getStart()) + // ); + // + // console.log("doubleClickedImportDefinition", doubleClickedImportDefinition); + + const importedDefinition = await followImport( + tsserver, + _projectRoot, + currentFilePath, + importNode, + identifierNode, + ); + if (importedDefinition) { + return { + name: identifier.name, + type: importedDefinition.type ?? "unknown", + position: identifier.position, + definition: importedDefinition, + }; + } + + return null; +} + +/** + * Follows an import to the file it imports and returns the definition of the + * identifier it contains. + * + * I only wrote this helper because I couldn't get the language server to follow + * definitions to other files. (This has since been fixed.) + * + * I haven't thoroughly tested that it follows typescript aliases faithfully. + */ +async function followImport( + tsserver: MessageConnection, + projectRoot: string, + currentFilePath: string, + importNode: ts.ImportDeclaration, + identifierNode: ts.Node, +) { + const importPath = (importNode.moduleSpecifier as ts.StringLiteral).text; + const resolvedPath: string | null = resolveModulePath( + importPath, + currentFilePath, + projectRoot, + ); + + logger.debug(`[debug][followImport] Import path: ${importPath}`); + logger.debug(`[debug][followImport] Resolved import path: ${resolvedPath}`); + + if (!resolvedPath) { + return null; + } + + if (!fs.existsSync(resolvedPath)) { + logger.warn( + `[followImport] Resolved import path does not exist: ${resolvedPath}`, + ); + return null; + } + + await openFile(tsserver, resolvedPath); + + const importedFileContent = await fs.promises.readFile(resolvedPath, "utf-8"); + const importedSourceFile = ts.createSourceFile( + resolvedPath, + importedFileContent, + ts.ScriptTarget.Latest, + true, + ); + + // Find the definition in the imported file + const importClause = importNode.importClause; + if (importClause) { + let identifierToFind: string | undefined; + + if ( + importClause.name && + importClause.name.text === identifierNode.getText() + ) { + // Default import + identifierToFind = importClause.name.text; + } else if ( + importClause.namedBindings && + ts.isNamedImports(importClause.namedBindings) + ) { + // Named import + const namedImport = importClause.namedBindings.elements.find( + (element) => element.name.text === identifierNode.getText(), + ); + if (namedImport) { + identifierToFind = + namedImport.propertyName?.text || namedImport.name.text; + } + } + + if (identifierToFind) { + logger.debug( + `[debug][followImport] Identifier to find in file we're importing from: ${identifierToFind}`, + ); + const importedNode = findExportedDeclaration( + importedSourceFile, + identifierToFind, + ); + if (importedNode) { + const result = getDefinitionText(importedNode, importedSourceFile); + + const definitionText = result?.text; + const definitionType = result?.type; + + return { + uri: getFileUri(resolvedPath), + range: { + start: importedSourceFile.getLineAndCharacterOfPosition( + importedNode.getStart(), + ), + end: importedSourceFile.getLineAndCharacterOfPosition( + importedNode.getEnd(), + ), + }, + text: definitionText, + type: definitionType, + }; + } + } + } + + return null; +} + +function findExportedDeclaration( + sourceFile: ts.SourceFile, + identifierName: string, +): ts.Node | undefined { + return sourceFile.statements.find((statement) => { + if ( + ts.isExportAssignment(statement) && + ts.isIdentifier(statement.expression) + ) { + return statement.expression.text === identifierName; + } + if ( + ts.isFunctionDeclaration(statement) || + ts.isVariableStatement(statement) + ) { + const modifiers = ts.getModifiers(statement); + return ( + modifiers?.some( + (modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword, + ) && + (ts.isFunctionDeclaration(statement) + ? statement.name?.text === identifierName + : statement.declarationList.declarations[0].name.getText() === + identifierName) + ); + } + return false; + }); +} diff --git a/api/src/lib/expand-function/imports/extract-package-name.ts b/api/src/lib/expand-function/imports/extract-package-name.ts new file mode 100644 index 000000000..d263403ac --- /dev/null +++ b/api/src/lib/expand-function/imports/extract-package-name.ts @@ -0,0 +1,44 @@ +import logger from "../../../logger.js"; + +export function extractPackageName(uri: string): string | null { + try { + const url = new URL(uri); + const path = decodeURIComponent(url.pathname); // Decode URI components + + const nodeModulesIndex = path.indexOf("node_modules"); + + if (nodeModulesIndex === -1) { + return null; + } + + const packagePath = path.substring( + nodeModulesIndex + "node_modules/".length, + ); + + // Handle pnpm structure + const pnpmIndex = packagePath.indexOf(".pnpm/"); + if (pnpmIndex !== -1) { + const pnpmPath = packagePath.substring(pnpmIndex + ".pnpm/".length); + const parts = pnpmPath.split("/"); + + // Handle scoped packages + if (parts[0].startsWith("@") && parts.length > 1) { + return `${parts[0]}/${parts[1]}`; + } + + return parts[0]; + } + + const parts = packagePath.split("/"); + + // Handle scoped packages + if (parts[0].startsWith("@") && parts.length > 1) { + return `${parts[0]}/${parts[1]}`; + } + + return parts[0]; + } catch (error) { + logger.error("[extractPackageName] Error parsing URI:", uri, error); + return null; + } +} diff --git a/api/src/lib/expand-function/imports/index.ts b/api/src/lib/expand-function/imports/index.ts new file mode 100644 index 000000000..ea87f6efd --- /dev/null +++ b/api/src/lib/expand-function/imports/index.ts @@ -0,0 +1,4 @@ +export * from "./context-for-import.js"; +export { resolveModulePath } from "./resolve-imports.js"; +export { extractPackageName } from "./extract-package-name.js"; +export { isDependency } from "./is-dependency.js"; diff --git a/api/src/lib/expand-function/imports/is-dependency.test.ts b/api/src/lib/expand-function/imports/is-dependency.test.ts new file mode 100644 index 000000000..b74662288 --- /dev/null +++ b/api/src/lib/expand-function/imports/is-dependency.test.ts @@ -0,0 +1,43 @@ +import { isDependency } from "./is-dependency.js"; + +describe("isDependency", () => { + test("should return true for npm/yarn node_modules path", () => { + expect(isDependency("/project/node_modules/package/file.js")).toBe(true); + }); + + test("should return true for yarn zero-installs path", () => { + expect( + isDependency( + "/project/.yarn/cache/package-version-integrity/node_modules/package/file.js", + ), + ).toBe(true); + }); + + test("should return true for pnpm path", () => { + expect( + isDependency( + "/project/.pnpm/package@version/node_modules/package/file.js", + ), + ).toBe(true); + }); + + test("should return false for non-dependency path", () => { + expect(isDependency("/project/src/components/file.js")).toBe(false); + }); + + test("should return false for path with similar name but not a dependency", () => { + expect(isDependency("/project/my-node-modules-like-folder/file.js")).toBe( + false, + ); + }); + + test("should handle Windows-style paths", () => { + expect(isDependency("C:\\project\\node_modules\\package\\file.js")).toBe( + true, + ); + }); + + test("should return false for empty string", () => { + expect(isDependency("")).toBe(false); + }); +}); diff --git a/api/src/lib/expand-function/imports/is-dependency.ts b/api/src/lib/expand-function/imports/is-dependency.ts new file mode 100644 index 000000000..df0cc2689 --- /dev/null +++ b/api/src/lib/expand-function/imports/is-dependency.ts @@ -0,0 +1,13 @@ +const dependencyFolders = ["node_modules", ".yarn", ".pnpm"]; + +export function isDependency(filePath: string): boolean { + if (!filePath) { + return false; + } + + // Normalize the path to handle Windows + const normalizedPath = filePath.replace(/\\/g, "/"); + return dependencyFolders.some((folder) => + normalizedPath.includes(`/${folder}/`), + ); +} diff --git a/api/src/lib/expand-function/imports/resolve-imports.ts b/api/src/lib/expand-function/imports/resolve-imports.ts new file mode 100644 index 000000000..28f6c7742 --- /dev/null +++ b/api/src/lib/expand-function/imports/resolve-imports.ts @@ -0,0 +1,72 @@ +import path from "node:path"; +import ts from "typescript"; +import logger from "../../../logger.js"; + +/** + * Resolves a module specifier to an absolute file path considering TypeScript path aliases. + * + * @param {string} moduleSpecifier - The module specifier from the import statement. + * @param {string} containingFile - The absolute path of the file containing the import. + * @param {string} projectRoot - The root directory of the project. + * @returns {string | null} The resolved absolute file path or null if resolution fails. + */ +export function resolveModulePath( + moduleSpecifier: string, + containingFile: string, + projectRoot: string, +): string | null { + // Path to tsconfig.json + const tsconfigPath = ts.findConfigFile( + projectRoot, + ts.sys.fileExists, + "tsconfig.json", + ); + + if (!tsconfigPath) { + logger.warn( + `[resolveModulePath] tsconfig.json not found in project root: ${projectRoot}`, + ); + return null; + } + + // Parse tsconfig.json + const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile); + if (configFile.error) { + logger.warn( + "[resolveModulePath] Error reading tsconfig.json:", + configFile.error.messageText, + ); + return null; + } + + const parsedConfig = ts.parseJsonConfigFileContent( + configFile.config, + ts.sys, + path.dirname(tsconfigPath), + ); + + if (parsedConfig.errors.length > 0) { + logger.warn( + "[resolveModulePath] Error parsing tsconfig.json:", + parsedConfig.errors.map((e) => e.messageText).join(", "), + ); + return null; + } + + // Resolve the module name + const resolvedModule = ts.resolveModuleName( + moduleSpecifier, + containingFile, + parsedConfig.options, + ts.sys, + ); + + if (resolvedModule.resolvedModule?.resolvedFileName) { + return resolvedModule.resolvedModule.resolvedFileName; + } + + logger.warn( + `[resolveModulePath] Unable to resolve module: ${moduleSpecifier} from ${containingFile}`, + ); + return null; +} diff --git a/api/src/lib/expand-function/index.ts b/api/src/lib/expand-function/index.ts new file mode 100644 index 000000000..aecab04a7 --- /dev/null +++ b/api/src/lib/expand-function/index.ts @@ -0,0 +1,6 @@ +export { + expandFunction, + type ExpandedFunctionResult, + type ExpandedFunctionContext, +} from "./expand-function.js"; +export { findWranglerCompiledJavascriptDir } from "./search-function/index.js"; diff --git a/api/src/lib/expand-function/search-function/index.ts b/api/src/lib/expand-function/search-function/index.ts new file mode 100644 index 000000000..e501294a5 --- /dev/null +++ b/api/src/lib/expand-function/search-function/index.ts @@ -0,0 +1,2 @@ +export { searchFunction } from "./search-function.js"; +export { findWranglerCompiledJavascriptDir } from "./search-compiled-function.js"; diff --git a/api/src/lib/expand-function/search-function/search-compiled-function.ts b/api/src/lib/expand-function/search-function/search-compiled-function.ts new file mode 100644 index 000000000..a1bb7abd8 --- /dev/null +++ b/api/src/lib/expand-function/search-function/search-compiled-function.ts @@ -0,0 +1,122 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; +import logger from "../../../logger.js"; +import { findSourceFunctions } from "../../find-source-function/index.js"; + +/** + * Retrieves the source function text from the compiled JavaScript directory. + * + * On even a medium sized codebase, these lookups can take 600ms + * + * @param {string} projectPath - The path to the project directory. + * @param {string} functionString - The text of the function to retrieve. + * @returns {Promise} The source function text if found, otherwise null. + */ +export async function getSourceFunctionText( + projectPath: string, + functionString: string, +): Promise<{ text: string | null; sourceFile: string | null } | null> { + const compiledJavascriptPath = findWranglerCompiledJavascriptDir(projectPath); + if (!compiledJavascriptPath) { + return null; + } + + // NOTE - This is a bit of an optimization. We're reading the file contents into memory + // before passing them to findSourceFunction. This allows us to avoid a multiple reads + // of the files in findSourceFunction. + const jsFilePath = path.join(compiledJavascriptPath, "index.js"); + const mapFile = `${jsFilePath}.map`; + const sourceMapContent = JSON.parse( + await fs.promises.readFile(mapFile, { encoding: "utf8" }), + ); + const jsFileContents = await fs.promises.readFile(jsFilePath, { + encoding: "utf8", + }); + + // const truncatedFunctionString = functionString.slice(0, 100); + // console.time(`findSourceFunction: ${truncatedFunctionString}`); + const sourceFunction = await findSourceFunctions( + jsFilePath, + functionString, + true, + { + sourceMapContent, + jsFileContents, + }, + ); + // console.timeEnd(`findSourceFunction: ${truncatedFunctionString}`); + return { + text: sourceFunction?.[0]?.sourceFunction ?? null, + sourceFile: sourceFunction?.[0]?.sourceFile ?? null, + }; +} + +/** + * Finds the directory containing the compiled JavaScript files generated by Wrangler. + * + * @param {string} projectPath - The path to the project directory. + * @returns {string | null} The path to the compiled JavaScript directory if found, otherwise null. + */ +export function findWranglerCompiledJavascriptDir( + projectPath: string, +): string | null { + const wranglerTmpPath = findWranglerTmp(projectPath); + if (!wranglerTmpPath) { + return null; + } + + // Get all directories in tmp that start with 'dev' + const devDirs = fs + .readdirSync(wranglerTmpPath) + .filter( + (dir) => + dir.startsWith("dev") && + fs.statSync(path.join(wranglerTmpPath, dir)).isDirectory(), + ) + .map((dir) => path.join(wranglerTmpPath, dir)); + + // Sort directories by modification time (most recent first) + devDirs.sort( + (a, b) => fs.statSync(b).mtime.getTime() - fs.statSync(a).mtime.getTime(), + ); + + // Find the first directory that contains both 'index.js' and 'index.js.map' + for (const dir of devDirs) { + const indexJs = path.join(dir, "index.js"); + const indexJsMap = path.join(dir, "index.js.map"); + if (fs.existsSync(indexJs) && fs.existsSync(indexJsMap)) { + return dir; + } + } + + logger.debug( + "[findCompiledJavascript] No compiled JavaScript found in .wrangler/tmp/dev* directories", + ); + return null; +} + +/** + * Locates the `.wrangler/tmp` directory within the specified project path. + * + * @param {string} projectPath - The path to the project directory. + * @returns {string | null} The path to the `.wrangler/tmp` directory if found, otherwise null. + */ +function findWranglerTmp(projectPath: string): string | null { + const wranglerTmpPath = path.join(projectPath, ".wrangler", "tmp"); + + try { + const stats = fs.statSync(wranglerTmpPath); + if (stats.isDirectory()) { + return wranglerTmpPath; + } + } catch (_error) { + // Directory doesn't exist or is not accessible + logger.debug( + `[findWranglerTmp] .wrangler/tmp directory doesn't exist or is not accessible: ${wranglerTmpPath}`, + ); + return null; + } + + logger.debug(`.wrangler/tmp could not be found in ${projectPath}`); + return null; +} diff --git a/api/src/lib/expand-function/search-function/search-file.test.ts b/api/src/lib/expand-function/search-function/search-file.test.ts new file mode 100644 index 000000000..0b0563b60 --- /dev/null +++ b/api/src/lib/expand-function/search-function/search-file.test.ts @@ -0,0 +1,113 @@ +import * as fs from "node:fs"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { searchFile } from "./search-file.js"; + +// Mock fs, but not typescript +vi.mock("node:fs"); + +describe("searchFile", () => { + beforeEach(() => { + vi.resetAllMocks(); + }); + + it("should find a function in a file", () => { + const mockFileContent = `\nfunction testFunc() { + console.log('Hello, world!'); +}`; + vi.mocked(fs.readFileSync).mockReturnValue(mockFileContent); + + const result = searchFile( + "/path/to/file.ts", + "function testFunc() { console.log('Hello, world!'); }", + ); + + expect(result).toMatchObject({ + file: "/path/to/file.ts", + startLine: 2, + startColumn: 1, + endLine: 4, + endColumn: 2, + }); + + expect(fs.readFileSync).toHaveBeenCalledWith("/path/to/file.ts", "utf-8"); + }); + + it("should return null if function is not found", () => { + const mockFileContent = `function differentFunc() { + console.log('Not the function we\'re looking for'); +}`; + vi.mocked(fs.readFileSync).mockReturnValue(mockFileContent); + + const result = searchFile("/path/to/file.ts", "function testFunc() {}"); + + expect(result).toBeNull(); + + expect(fs.readFileSync).toHaveBeenCalledWith("/path/to/file.ts", "utf-8"); + }); + + it("should match async functions even if search string does not include 'async'", () => { + const mockFileContent = `async function testAsyncFunc() { + await someAsyncOperation(); +}`; + vi.mocked(fs.readFileSync).mockReturnValue(mockFileContent); + + const result = searchFile( + "/path/to/file.ts", + "function testAsyncFunc() { await someAsyncOperation(); }", + ); + + expect(result).toMatchObject({ + file: "/path/to/file.ts", + startLine: 1, + startColumn: 1, + endLine: 3, + endColumn: 2, + }); + + expect(fs.readFileSync).toHaveBeenCalledWith("/path/to/file.ts", "utf-8"); + }); + + it("should handle arrow functions", () => { + const mockFileContent = `const arrowFunc = () => { + return 'Arrow function'; +};`; + vi.mocked(fs.readFileSync).mockReturnValue(mockFileContent); + + const result = searchFile( + "/path/to/file.ts", + "() => { return 'Arrow function'; }", + ); + + expect(result).toMatchObject({ + file: "/path/to/file.ts", + startLine: 1, + startColumn: 19, + endLine: 3, + endColumn: 2, + }); + + expect(fs.readFileSync).toHaveBeenCalledWith("/path/to/file.ts", "utf-8"); + }); + + it("should handle async arrow functions", () => { + const mockFileContent = `const arrowFunc = async () => { + return 'Arrow function'; +};`; + vi.mocked(fs.readFileSync).mockReturnValue(mockFileContent); + + const result = searchFile( + "/path/to/file.ts", + "() => { return 'Arrow function'; }", + ); + + expect(result).toMatchObject({ + file: "/path/to/file.ts", + startLine: 1, + startColumn: 19, + endLine: 3, + endColumn: 2, + }); + + expect(fs.readFileSync).toHaveBeenCalledWith("/path/to/file.ts", "utf-8"); + }); +}); diff --git a/api/src/lib/expand-function/search-function/search-file.ts b/api/src/lib/expand-function/search-function/search-file.ts new file mode 100644 index 000000000..0f29a6971 --- /dev/null +++ b/api/src/lib/expand-function/search-function/search-file.ts @@ -0,0 +1,153 @@ +import * as fs from "node:fs"; +import * as ts from "typescript"; +import logger from "../../../logger.js"; +import type { FunctionNode } from "../types.js"; + +export type SearchFunctionResult = { + /** The file in which the function was found */ + file: string; + /** The line on which the function definition starts */ + startLine: number; + /** The column on which the function definition starts */ + startColumn: number; + /** The line on which the function definition ends */ + endLine: number; + /** The column on which the function definition ends */ + endColumn: number; + + /** The node that was found */ + node: FunctionNode; + /** The source file that was found */ + sourceFile: ts.SourceFile; +}; + +/** + * Searches for a specific function in a TypeScript file. + * + * @param filePath - The path to the TypeScript file to search. + * @param searchString - The function text to search for. + * @param debug - Optional. If true, enables debug logging. Default is false. This exists because always having debug logs on kinda pollutes the console in dev. + * @returns A SearchFunctionResult object if the function is found, null otherwise. + * + * @description + * This function reads the content of the specified TypeScript file and searches for a function + * that matches the provided searchString. It handles function declarations, arrow functions, + * and function expressions. The function also normalizes whitespace and handles async functions + * by optionally removing the 'async' keyword during comparison. + * + * If a match is found, it returns a SearchFunctionResult object containing file information, + * start and end positions of the function, and the TypeScript AST node and SourceFile. + */ +export function searchFile( + filePath: string, + searchString: string, + debug = false, +): SearchFunctionResult | null { + if (debug) { + logger.debug("[debug][searchFile] Searching file:", filePath); + } + const fileContent = fs.readFileSync(filePath, "utf-8"); + if (debug) { + logger.debug("[debug][searchFile] File content:", fileContent); + } + const sourceFile = ts.createSourceFile( + filePath, + fileContent, + ts.ScriptTarget.Latest, + true, + ); + + if (debug) { + logger.debug("[debug][searchFile] Source file:", sourceFile); + } + + let result: SearchFunctionResult | null = null; + + function visit(node: ts.Node) { + const isFunction = + ts.isFunctionDeclaration(node) || + ts.isArrowFunction(node) || + ts.isFunctionExpression(node); + + if (isFunction) { + const functionText = node.getText(sourceFile).trim(); + let functionTextWithoutAsync = functionText; + if (debug) { + logger.debug("[debug][searchFile] Found function:", functionText); + } + + // HACK - Remove the `async` keyword if it is at the beginning + if ( + node.modifiers?.some( + (modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword, + ) + ) { + functionTextWithoutAsync = functionTextWithoutAsync.replace( + /^\s*async\s*/, + "", + ); + if (debug) { + logger.debug( + "[debug][searchFile] Removed async keyword:", + functionText, + ); + } + } + + // Normalize whitespace in both the function text and search string + // TODO - Check that this doesn't break anything + const normalizedFunctionText = functionText.replace(/\s+/g, " "); + const normalizedFunctionTextWithoutAsync = + functionTextWithoutAsync.replace(/\s+/g, " "); + const normalizedSearchString = searchString.replace(/\s+/g, " "); + + if (debug) { + logger.debug( + "[debug][searchFile] Comparing:", + normalizedFunctionText, + "with:", + normalizedSearchString, + ); + } + + if ( + normalizedFunctionText === normalizedSearchString || + normalizedFunctionTextWithoutAsync === normalizedSearchString + ) { + if (debug) { + logger.debug("[debug][searchFile] Match found!"); + } + + const { line: startLine, character: startColumn } = + sourceFile.getLineAndCharacterOfPosition(node.getStart()); + const { line: endLine, character: endColumn } = + sourceFile.getLineAndCharacterOfPosition(node.getEnd()); + + // Replace the identifier analysis code with the new helper function + // const identifiers = analyzeOutOfScopeIdentifiers(node, sourceFile); + + result = { + file: filePath, + startLine: startLine + 1, + startColumn: startColumn + 1, + endLine: endLine + 1, + endColumn: endColumn + 1, + node, + sourceFile, + }; + } + } + + // Only continue traversing if we haven't found a match yet + if (!result) { + ts.forEachChild(node, visit); + } + } + + visit(sourceFile); + + if (debug) { + logger.debug("[debug][searchFile] Search result:", result); + } + return result; +} diff --git a/api/src/lib/expand-function/search-function/search-function.ts b/api/src/lib/expand-function/search-function/search-function.ts new file mode 100644 index 000000000..634fc7f1a --- /dev/null +++ b/api/src/lib/expand-function/search-function/search-function.ts @@ -0,0 +1,103 @@ +import logger from "../../../logger.js"; +import { getSourceFunctionText } from "./search-compiled-function.js"; +import type { SearchFunctionResult } from "./search-file.js"; +import { searchSourceFunction } from "./search-source-function.js"; + +type SearchFunctionOptions = { + skipSourceMap?: boolean; + debug?: boolean; + hints?: { sourceFunction?: string | null; sourceFile?: string | null }; +}; + +/** + * Searches for a function within the project source code. + * + * This function attempts to locate a specified function within the project's source files. + * It performs two main searches: + * + * 1. Directly searches for the function string in the source. + * 2. Retrieves the source function text via a source map and searches using the mapped text. + * + * This is ripe for optimization. + * + * @param projectPath - The path to the project directory. + * @param functionString - The string representation of the function to search for. + * @param options - Optional parameters for the search. + * @param options.skipSourceMap - If true, the source map search will be skipped. Useful for tests. + * @returns A promise that resolves to a {@link SearchFunctionResult} if found, or `null` otherwise. + */ +export async function searchFunction( + projectPath: string, + functionString: string, + options: SearchFunctionOptions = {}, +): Promise { + const debug = options.debug || false; + + // HACK - Allows us to run tests without source maps + if (options.skipSourceMap) { + // Attempt to search the function directly in the source. + const searchString = options.hints?.sourceFunction ?? functionString; + try { + const directResult = await searchSourceFunction( + projectPath, + searchString, + { + debug, + hints: { + sourceFile: options.hints?.sourceFile ?? undefined, + }, + }, + ); + if (directResult) { + return directResult; + } + } catch (error) { + logger.error(`Error searching for function directly in source: ${error}`); + } + return null; + } + + // Attempt to retrieve the source function text via a source map and search. + try { + const sourceFunction = await getSourceFunctionText( + projectPath, + functionString, + ); + if (sourceFunction?.text) { + if (debug) { + logger.debug( + `[searchFunction] Searching for function via source mapping: ${sourceFunction}`, + ); + } + try { + const mappedResult = await searchSourceFunction( + projectPath, + sourceFunction?.text, + { + hints: { + sourceFile: sourceFunction?.sourceFile ?? undefined, + }, + }, + ); + if (mappedResult) { + return mappedResult; + } + if (debug) { + logger.debug( + "no mapped result found for source function", + sourceFunction, + ); + } + } catch (error) { + logger.error( + `Error searching for function via source mapping: ${error}`, + ); + } + } + } catch (error) { + logger.error(`Error retrieving source function text: ${error}`); + } + + // If the function was not found in either search, return null. + return null; +} diff --git a/api/src/lib/expand-function/search-function/search-source-function.test.ts b/api/src/lib/expand-function/search-function/search-source-function.test.ts new file mode 100644 index 000000000..79ce170af --- /dev/null +++ b/api/src/lib/expand-function/search-function/search-source-function.test.ts @@ -0,0 +1,290 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { FunctionNode } from "../types.js"; + +// Mock the search-file module, as we test that separately +vi.mock("./search-file.js", () => ({ + searchFile: vi.fn(), +})); + +import type ts from "typescript"; +import { searchFile } from "./search-file.js"; +// Import after mocking +import { searchSourceFunction } from "./search-source-function.js"; + +// Mock the fs and path modules +vi.mock("node:fs"); +vi.mock("node:path"); +vi.mock("typescript"); + +// Add this import +import logger from "../../../logger.js"; + +// Mock the logger +vi.mock("../../../logger.js", () => ({ + default: { + trace: vi.fn(), + debug: vi.fn(), + error: vi.fn(), + }, +})); + +describe("searchSourceFunction", () => { + beforeEach(() => { + vi.resetAllMocks(); + }); + + it("should look for a function in TypeScript files in a directory", async () => { + // Mock the filesystem structure + vi.mocked(fs.promises.readdir).mockResolvedValue([ + "file1.ts" as unknown as fs.Dirent, + "file2.tsx" as unknown as fs.Dirent, + "file3.js" as unknown as fs.Dirent, + ]); + + vi.mocked(fs.promises.stat).mockImplementation( + async () => + ({ + isDirectory: () => false, + isFile: () => true, + }) as unknown as fs.Stats, + ); + + vi.mocked(path.join).mockImplementation((...args) => args.join("/")); + + // Mock the searchFile function to return a result for file1.ts + const mockResult = { + file: "/path/to/file1.ts", + startLine: 1, + startColumn: 1, + endLine: 5, + endColumn: 2, + node: {} as FunctionNode, + sourceFile: {} as ts.SourceFile, + }; + vi.mocked(searchFile).mockResolvedValueOnce(mockResult); + + const result = await searchSourceFunction( + "/path/to", + "function testFunc() {}", + ); + + expect(result).toEqual(mockResult); + expect(fs.promises.readdir).toHaveBeenCalledWith("/path/to"); + expect(searchFile).toHaveBeenCalledWith( + "/path/to/file1.ts", + "function testFunc() {}", + ); + }); + + it("should return null if function is not found", async () => { + vi.mocked(fs.promises.readdir).mockResolvedValue([ + "file1.ts" as unknown as fs.Dirent, + "file2.tsx" as unknown as fs.Dirent, + "file3.js" as unknown as fs.Dirent, + ]); + + vi.mocked(fs.promises.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + } as unknown as fs.Stats); + + vi.mocked(path.join).mockImplementation((...args) => args.join("/")); + + vi.mocked(searchFile).mockResolvedValue(null); + + const result = await searchSourceFunction( + "/path/to", + "function notFound() {}", + ); + + expect(result).toBeNull(); + expect(fs.promises.readdir).toHaveBeenCalledWith("/path/to"); + expect(searchFile).toHaveBeenCalledWith( + "/path/to/file1.ts", + "function notFound() {}", + ); + expect(searchFile).toHaveBeenCalledWith( + "/path/to/file2.tsx", + "function notFound() {}", + ); + expect(searchFile).not.toHaveBeenCalledWith( + "/path/to/file3.js", + "function notFound() {}", + ); + }); + + it("should recursively search in subdirectories", async () => { + // Mock the filesystem structure with a subdirectory + vi.mocked(fs.promises.readdir) + .mockResolvedValueOnce([ + "subdir" as unknown as fs.Dirent, + "file1.ts" as unknown as fs.Dirent, + ]) // First directory + .mockResolvedValueOnce(["file2.ts" as unknown as fs.Dirent]); // Subdirectory + + vi.mocked(fs.promises.stat).mockImplementation( + async (filePath) => + ({ + isDirectory: () => filePath.toString().endsWith("subdir"), + isFile: () => !filePath.toString().endsWith("subdir"), + }) as unknown as fs.Stats, + ); + + vi.mocked(path.join).mockImplementation((...args) => args.join("/")); + + vi.mocked(searchFile) + .mockResolvedValueOnce(null) // file1.ts does not contain the function + .mockResolvedValueOnce({ + file: "/path/to/subdir/file2.ts", + startLine: 10, + startColumn: 5, + endLine: 15, + endColumn: 10, + node: {} as FunctionNode, + sourceFile: {} as ts.SourceFile, + } as unknown as ReturnType); + + const result = await searchSourceFunction( + "/path/to", + "function recursiveFunc() {}", + ); + + expect(result).toEqual({ + file: "/path/to/subdir/file2.ts", + startLine: 10, + startColumn: 5, + endLine: 15, + endColumn: 10, + node: {} as FunctionNode, + sourceFile: {} as ts.SourceFile, + }); + expect(fs.promises.readdir).toHaveBeenCalledWith("/path/to"); + expect(fs.promises.readdir).toHaveBeenCalledWith("/path/to/subdir"); + expect(searchFile).toHaveBeenCalledWith( + "/path/to/file1.ts", + "function recursiveFunc() {}", + ); + expect(searchFile).toHaveBeenCalledWith( + "/path/to/subdir/file2.ts", + "function recursiveFunc() {}", + ); + }); + + it("should handle errors gracefully when reading directory", async () => { + vi.mocked(fs.promises.readdir).mockRejectedValueOnce( + new Error("Failed to read directory"), + ); + + const result = await searchSourceFunction( + "/path/to", + "function testFunc() {}", + ); + + expect(result).toBeNull(); + expect(fs.promises.readdir).toHaveBeenCalledWith("/path/to"); + expect(searchFile).not.toHaveBeenCalled(); + }); + + it("should handle errors gracefully when stat-ing a file", async () => { + vi.mocked(fs.promises.readdir).mockResolvedValue([ + "file1.ts" as unknown as fs.Dirent, + "file2.tsx" as unknown as fs.Dirent, + "file3.ts" as unknown as fs.Dirent, + ]); + + vi.mocked(fs.promises.stat).mockImplementation(async (filePath) => { + if (filePath.toString().endsWith("file2.tsx")) { + throw new Error("Failed to stat file"); + } + return { + isDirectory: () => false, + isFile: () => true, + } as unknown as fs.Stats; + }); + + vi.mocked(path.join).mockImplementation((...args) => args.join("/")); + + // Mock the searchFile function to return null for file1.ts and a result for file3.ts + const mockResult = { + file: "/path/to/file3.ts", + startLine: 1, + startColumn: 1, + endLine: 5, + endColumn: 2, + node: {} as FunctionNode, + sourceFile: {} as ts.SourceFile, + }; + vi.mocked(searchFile) + .mockResolvedValueOnce(null) // file1.ts returns null + .mockResolvedValueOnce(mockResult); // file3.js returns mockResult + + const result = await searchSourceFunction( + "/path/to", + "function testFunc() {}", + ); + + expect(result).toEqual(mockResult); + expect(fs.promises.readdir).toHaveBeenCalledWith("/path/to"); + expect(fs.promises.stat).toHaveBeenCalledWith("/path/to/file1.ts"); + expect(fs.promises.stat).toHaveBeenCalledWith("/path/to/file2.tsx"); + expect(fs.promises.stat).toHaveBeenCalledWith("/path/to/file3.ts"); + expect(searchFile).toHaveBeenCalledWith( + "/path/to/file1.ts", + "function testFunc() {}", + ); + expect(searchFile).not.toHaveBeenCalledWith( + "/path/to/file2.tsx", + "function testFunc() {}", + ); + expect(logger.error).toHaveBeenCalled(); + }); + + it("should ignore specified directories and files", async () => { + vi.mocked(fs.promises.readdir).mockResolvedValue([ + "file1.ts" as unknown as fs.Dirent, + "file2.tsx" as unknown as fs.Dirent, + "file3.js" as unknown as fs.Dirent, + "node_modules" as unknown as fs.Dirent, + ".git" as unknown as fs.Dirent, + "file1.ts" as unknown as fs.Dirent, + ".hidden" as unknown as fs.Dirent, + "README.md" as unknown as fs.Dirent, + ]); + + vi.mocked(fs.promises.stat).mockImplementation( + async (filePath) => + ({ + isDirectory: () => !filePath.toString().endsWith(".ts"), + isFile: () => filePath.toString().endsWith(".ts"), + }) as unknown as fs.Stats, + ); + + vi.mocked(path.join).mockImplementation((...args) => args.join("/")); + + // Mock the searchFile function to return a result for file1.ts + const mockResult = { + file: "/path/to/file1.ts", + startLine: 1, + startColumn: 1, + endLine: 5, + endColumn: 2, + node: {} as FunctionNode, + sourceFile: {} as ts.SourceFile, + }; + vi.mocked(searchFile).mockResolvedValueOnce(mockResult); + + const result = await searchSourceFunction( + "/path/to", + "function testFunc() {}", + ); + + expect(result).toEqual(mockResult); + expect(fs.promises.readdir).toHaveBeenCalledWith("/path/to"); + expect(searchFile).toHaveBeenCalledWith( + "/path/to/file1.ts", + "function testFunc() {}", + ); + }); +}); diff --git a/api/src/lib/expand-function/search-function/search-source-function.ts b/api/src/lib/expand-function/search-function/search-source-function.ts new file mode 100644 index 000000000..716744d46 --- /dev/null +++ b/api/src/lib/expand-function/search-function/search-source-function.ts @@ -0,0 +1,138 @@ +import { promises as fs } from "node:fs"; +import type { Stats } from "node:fs"; +import * as path from "node:path"; +import logger from "../../../logger.js"; +import { type SearchFunctionResult, searchFile } from "./search-file.js"; + +/** + * Recursively searches for a function in a directory and its subdirectories. + * + * - Ignores hidden directories and node_modules + * - Only looks in .ts and .tsx files + * + * @param dirPath - The directory to search in, typically the project root. + * @param searchString - The (stringified) function to search for. + * @param debug - Whether to log debug information - this is an explicit switch because otherwise the console gets too noisy + * @returns The result of the search, or null if the function is not found. + */ +export async function searchSourceFunction( + dirPath: string, + searchString: string, + options: { debug?: boolean; hints?: { sourceFile?: string } } = { + debug: false, + }, +): Promise { + const { debug, hints } = options; + // HACK - The sourceHint is a path to a file that contains the function we are trying to expand + // We will receive this as a hint if we did source map parsing to find the definition of the function + if (hints?.sourceFile) { + if (debug) { + logger.debug( + `[debug] [searchSourceFunction] Searching for function: ${searchString} in directory: ${dirPath} with source hint: ${hints.sourceFile}`, + ); + } + const result = await searchFile(hints.sourceFile, searchString); + if (result) { + return result; + } + } + let files: string[]; + try { + files = await fs.readdir(dirPath); + if (debug) { + logger.debug("[debug] [searchForFunction] Searching files:", files); + } + } catch (error) { + logger.error( + `[error] [searchForFunction] Failed to read directory: ${dirPath}`, + error, + ); + return null; + } + + for (const file of files) { + const filePath = path.join(dirPath, file); + let stats: Stats; + try { + stats = await fs.stat(filePath); + } catch (error) { + logger.error( + `[error] [searchForFunction] Failed to stat file: ${filePath}`, + error, + ); + continue; + } + + if (stats.isDirectory()) { + if (shouldIgnoreDirent(file)) { + continue; + } + // Recursively search directories + const result = await searchSourceFunction(filePath, searchString); + if (result) { + return result; + } + } else if ( + stats.isFile() && + (file.endsWith(".ts") || file.endsWith(".tsx")) + ) { + if (debug) { + logger.debug("[debug] [searchForFunction] Searching file:", file); + } + let result: SearchFunctionResult | null; + try { + result = await searchFile(filePath, searchString); + if (debug && result) { + logger.debug("[debug] [searchForFunction] Result:", result); + } + } catch (error) { + logger.error( + `[error] [searchForFunction] Failed to search file: ${filePath}`, + error, + ); + continue; + } + if (debug) { + logger.debug("[debug] [searchForFunction] Result:", result); + } + if (result) { + return result; + } + } + } + + return null; +} + +/** + * Returns true if the file should be ignored. + * Ignores hidden directories and node_modules, for example. + */ +function shouldIgnoreDirent(dirent: string): boolean { + const ignoredDirs = [ + "node_modules", + ".git", + ".vscode", + ".idea", + "dist", + "build", + "coverage", + "tmp", + "temp", + ".wrangler", + ".next", + ".cache", + ".husky", + ".yarn", + ".nx", + ]; + + const ignoredPrefixes = [".", "_"]; + + return ( + ignoredDirs.includes(dirent.toLowerCase()) || + ignoredPrefixes.some((prefix) => dirent.startsWith(prefix)) || + dirent.endsWith(".log") || + dirent.endsWith(".md") + ); +} diff --git a/api/src/lib/expand-function/tests/expand-function-smoke-test.ts b/api/src/lib/expand-function/tests/expand-function-smoke-test.ts new file mode 100644 index 000000000..2f4b8ea4c --- /dev/null +++ b/api/src/lib/expand-function/tests/expand-function-smoke-test.ts @@ -0,0 +1,80 @@ +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import util from "node:util"; +import { expandFunction } from "../expand-function.js"; +import { getTSServer } from "../tsserver/server.js"; + +// Shim __filename and __dirname since we're using esm +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const projectRoot = path.resolve( + __dirname, + "../../../../../examples/test-static-analysis", +); + +const _functionWithConstant = `(c) => { + const auth = c.req.header("Authorization"); + if (auth && PASSPHRASES.includes(auth)) { + return c.text("Hello Hono!"); + } + return c.text("Unauthorized", 401); +}`.trim(); + +const _functionWithHelper = `(c) => { + const shouldSayHello = helperFunction(c.req); + return c.text(shouldSayHello ? "Hello Helper Function!" : "Helper Function"); +}`.trim(); + +const functionWithHelperInAnotherFile = `(c) => { + const auth = getAuthHeader(c.req); + if (auth && PASSPHRASES.includes(auth)) { + return c.text("Hello Hono!"); + } + return c.text("Unauthorized", 401); +}`.trim(); + +async function main() { + try { + // await tsServerTest(); + const result = await expandFunction( + projectRoot, + functionWithHelperInAnotherFile, + ); + console.log(result); + } catch (error) { + console.error(error); + } +} + +main().catch((error) => { + console.error("An error occurred:", error); + process.exit(1); +}); + +export async function tsServerTest() { + const { connection } = await getTSServer(projectRoot); + // debugger; + const fileUri = `file://${path.resolve(projectRoot, "src/index.ts")}`; + console.log("fileUri", fileUri); + + const response = await connection.sendRequest("textDocument/definition", { + textDocument: { uri: fileUri }, + position: { line: 0, character: 10 }, + }); + + console.log("Definition response:", util.inspect(response, { depth: null })); + + const referencesResponse = await connection.sendRequest( + "textDocument/references", + { + textDocument: { uri: fileUri }, + position: { line: 6, character: 13 }, + }, + ); + + console.log( + "References response:", + util.inspect(referencesResponse, { depth: null }), + ); +} diff --git a/api/src/lib/expand-function/tests/expand-function.test.ts b/api/src/lib/expand-function/tests/expand-function.test.ts new file mode 100644 index 000000000..fc7b51675 --- /dev/null +++ b/api/src/lib/expand-function/tests/expand-function.test.ts @@ -0,0 +1,367 @@ +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; +import { expandFunction } from "../expand-function.js"; + +// Shim __filename and __dirname since we're using esm +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Resolve the path and analyze the 'src' directory +const projectRoot = path.resolve( + __dirname, + "../../../../../examples/test-static-analysis", +); + +const srcPath = path.resolve(projectRoot, "src"); + +// Skip source map search for tests +// Typically, we want to also look for a handler defintion in the source map of compiled ts code, +// but this adds unnecessary time to the test suite and could introduce flakiness. +const SKIP_SOURCE_MAP_SEARCH = { skipSourceMap: true }; + +// A function in `/app/src/index.ts` that has a constant identifier that is out of scope +const functionWithConstant = `(c) => { + const auth = c.req.header("Authorization"); + if (auth && PASSPHRASES.includes(auth)) { + return c.text("Hello Hono!"); + } + return c.text("Unauthorized", 401); +}`.trim(); + +// A function in `/app/src/index.ts` that has a helper function that is out of scope +const functionWithHelper = `(c) => { + const shouldSayHello = helperFunction(c.req); + return c.text(shouldSayHello ? "Hello Helper Function!" : "Helper Function"); +}`.trim(); + +// A function in `/app/src/index.ts` that has a helper function that is out of scope and in another file +const functionWithHelperInAnotherFile = `(c) => { + const auth = getAuthHeader(c.req); + if (auth && PASSPHRASES.includes(auth)) { + return c.text("Hello Hono!"); + } + return c.text("Unauthorized", 401); +}`.trim(); + +// A function in `/app/src/index.ts` that has a helper function that is out of scope and in another file, +// and the helper function itself has a constant that is out of scope and defined in another file +const functionWithHelperWithConstant = `(c) => { + const randomHeader = getRandomHeader(c.req); + if (randomHeader) { + return c.text("What a random header!"); + } + return c.text("No random header", 422); +}`.trim(); + +// A function in `/app/src/other-router.ts` that has a global web standard (like console) +// which we can use to test that we're not including global web standards as out of scope identifiers +const functionWithWebStandardGlobals = `(c) => { + console.log("Other Router"); + const url = new URL(c.req.url); + return c.text(\`Other Router: \${url}\`); +}`.trim(); + +// A function in `/app/src/other-router.ts` that has a drizzle identifier that is out of scope +// as well as accessing a table from the entire schema definition +const functionWithDrizzleSchemaStuff = `(c) => { + const db = drizzle(c.env.DB); + const stuff = await db.select().from(schema.stuff); + return c.json(stuff); +}`.trim(); + +// A function in `/app/src/other-router.ts` that has a drizzle identifier that is out of scope +// as well as a directly imported table definition +const functionWithDrizzleTableStuff = `async (c) => { + const body = await c.req.json(); + const db = drizzle(c.env.DB); + const stuff2 = await db.insert(stuff).values(body).returning(); + return c.json(stuff2); +}`.trim(); + +describe("expandFunction: testing on the test-static-analysis project", () => { + describe("single file - app/src/index.ts", () => { + it("should return the function location and definition of a constant identifier that is out of scope", async () => { + const result = await expandFunction( + projectRoot, + functionWithConstant, + SKIP_SOURCE_MAP_SEARCH, + ); + + expect(result).not.toBeNull(); + expect(result?.file).toBe(path.resolve(srcPath, "index.ts")); + expect(result?.startLine).toBe(10); + expect(result?.startColumn).toBe(19); + expect(result?.endLine).toBe(16); + expect(result?.endColumn).toBe(2); + + expect(result?.context?.[0]?.definition?.text).toBe( + '["I am a cat", "I am a dog", "I am a bird"]', + ); + }); + + it("should return the function location and definition of a function identifier that is out of scope", async () => { + const result = await expandFunction( + projectRoot, + functionWithHelper, + SKIP_SOURCE_MAP_SEARCH, + ); + + expect(result).not.toBeNull(); + expect(result?.file).toBe(path.resolve(srcPath, "index.ts")); + expect(result?.startLine).toBe(18); + expect(result?.startColumn).toBe(29); + expect(result?.endLine).toBe(21); + expect(result?.endColumn).toBe(2); + + expect(result?.context?.[0]?.definition?.text).toBe( + `function helperFunction(req: HonoRequest): boolean { + return req.query("shouldSayHello") === "true"; +}`.trim(), + ); + }); + }); + + describe("multiple files - app/src/index.ts, app/src/utils.ts, app/src/constants.ts", () => { + it("should return the function location and definition of a function identifier that is out of scope", async () => { + const result = await expandFunction( + projectRoot, + functionWithHelperInAnotherFile, + SKIP_SOURCE_MAP_SEARCH, + ); + + expect(result).not.toBeNull(); + expect(result?.file).toBe(path.resolve(srcPath, "index.ts")); + expect(result?.startLine).toBe(23); + expect(result?.startColumn).toBe(42); + expect(result?.endLine).toBe(29); + expect(result?.endColumn).toBe(2); + + expect(result?.context).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + definition: expect.objectContaining({ + text: `export function getAuthHeader(req: HonoRequest) { + return req.header("Authorization"); +}`.trim(), + }), + }), + ]), + ); + }); + + it("should recursively expand context for a function identifier that is out of scope", async () => { + const result = await expandFunction( + projectRoot, + functionWithHelperWithConstant, + SKIP_SOURCE_MAP_SEARCH, + ); + + expect(result).not.toBeNull(); + expect(result?.file).toBe(path.resolve(srcPath, "index.ts")); + + expect(result?.context).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + definition: expect.objectContaining({ + text: `export function getRandomHeader(req: HonoRequest) { + return req.header(RANDOM_HEADER); +}`.trim(), + }), + context: expect.arrayContaining([ + expect.objectContaining({ + name: "RANDOM_HEADER", + definition: expect.objectContaining({ + text: `"X-Random"`, + }), + }), + ]), + }), + ]), + ); + }); + }); + + describe("router file - app/src/other-router.ts", () => { + it("should not return global web standards like console as out of scope identifiers", async () => { + const result = await expandFunction( + projectRoot, + functionWithWebStandardGlobals, + SKIP_SOURCE_MAP_SEARCH, + ); + + expect(result).not.toBeNull(); + expect(result?.file).toBe(path.resolve(srcPath, "other-router.ts")); + expect(result?.startLine).toBe(12); + expect(result?.startColumn).toBe(14); + expect(result?.endLine).toBe(16); + expect(result?.endColumn).toBe(2); + + // NOTE - `console` maps back to `@cloudflare/workers-types`'s declaration file (.d.ts) + // so our `expandFunction` correctly identifies it as part of the runtime + expect(result?.context).not.toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: "console", + }), + ]), + ); + + // NOTE - `log` *SHOULD* map back to `@cloudflare/workers-types`'s declaration file (.d.ts) + // so our `expandFunction` *SHOULD* correctly identifies it as part of the runtime + // If this fails, though, you may need to uncomment the lines below, as depending on the workers-types, + // we might end up mapping `log` to an `index.ts` file. + expect(result?.context).not.toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: "log", + }), + ]), + ); + + // HACK - `log` maps back to workers-types (cloudflare pacakge), but not a `.d.ts` file... + // so it's really difficult to detect that it's actually part of the runtime + // so we just check that we correctly identify the package name and move on for now + // expect(result?.context).toEqual( + // expect.arrayContaining([ + // expect.objectContaining({ + // name: "log", + // package: expect.stringMatching(/^@cloudflare\/workers-types/), + // }), + // ]), + // ); + }); + }); + + describe("drizzle test (external packages)", () => { + it("should report drizzle as an out of scope identifier and show its package name", async () => { + const result = await expandFunction( + projectRoot, + functionWithDrizzleSchemaStuff, + SKIP_SOURCE_MAP_SEARCH, + ); + + expect(result).not.toBeNull(); + expect(result?.file).toBe(path.resolve(srcPath, "other-router.ts")); + expect(result?.startLine).toBe(18); + // Start column is 16 because of the `async` keyword at the beginning of the function + expect(result?.startColumn).toBe(16); + expect(result?.endLine).toBe(22); + expect(result?.endColumn).toBe(2); + + expect(result?.context).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: "drizzle", + package: expect.stringMatching(/^drizzle-orm/), + }), + ]), + ); + }); + + // TODO - Unskip this test when identifier analysis works well with property access expressions + it.skip("should handle expansion of schema definition (drizzle schema accessed as `schema.stuff`)", async () => { + const result = await expandFunction( + projectRoot, + functionWithDrizzleSchemaStuff, + SKIP_SOURCE_MAP_SEARCH, + ); + + expect(result).not.toBeNull(); + + expect(result?.context).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: "stuff", + definition: expect.objectContaining({ + text: `sqliteTable("stuff", { + id: integer("id", { mode: "number" }).primaryKey(), + foo: text(\"foo\").notNull(), + createdAt: text("created_at").notNull().default(sql\`(CURRENT_TIMESTAMP)\`), + updatedAt: text("updated_at").notNull().default(sql\`(CURRENT_TIMESTAMP)\`), +})`.trim(), + }), + // TODO - Follow definition of sqliteTable and sql + // context: expect.arrayContaining([ + // expect.objectContaining({ + // name: "sqliteTable", + // definition: expect.objectContaining({ + // text: "TODO", + // package: expect.stringMatching(/^drizzle-orm/), + // }), + // }), + // ]), + }), + ]), + ); + }); + + it("should handle expansion of schema definition (drizzle schema accessed as direct import of table `stuff`)", async () => { + const result = await expandFunction( + projectRoot, + functionWithDrizzleTableStuff, + SKIP_SOURCE_MAP_SEARCH, + ); + + expect(result).not.toBeNull(); + + expect(result?.context).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: "stuff", + definition: expect.objectContaining({ + text: `sqliteTable("stuff", { + id: integer("id", { mode: "number" }).primaryKey(), + foo: text(\"foo\").notNull(), + createdAt: text("created_at").notNull().default(sql\`(CURRENT_TIMESTAMP)\`), + updatedAt: text("updated_at").notNull().default(sql\`(CURRENT_TIMESTAMP)\`), +})`.trim(), + }), + // TODO - Follow definition of sqliteTable and sql + // context: expect.arrayContaining([ + // expect.objectContaining({ + // name: "sqliteTable", + // definition: expect.objectContaining({ + // text: "TODO", + // package: expect.stringMatching(/^drizzle-orm/), + // }), + // }), + // ]), + }), + ]), + ); + }); + + // TEMPORARY - I am having issues with only expanding properties accessed on the schema, + // So expected behavior for now is that when you use + // `import * as schema from "./db"` and + // `schema.stuff` in a function, we expand to the entire schema definition + it("TEMP should handle expansion of entire schema definition (drizzle schema) for `schema.stuff`", async () => { + const result = await expandFunction( + projectRoot, + functionWithDrizzleSchemaStuff, + SKIP_SOURCE_MAP_SEARCH, + ); + + expect(result).not.toBeNull(); + + expect(result?.context).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: "schema", + definition: expect.objectContaining({ + text: `import { sql } from "drizzle-orm"; +import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; + +export const stuff = sqliteTable("stuff", { + id: integer("id", { mode: "number" }).primaryKey(), + foo: text("foo").notNull(), + createdAt: text("created_at").notNull().default(sql\`(CURRENT_TIMESTAMP)\`), + updatedAt: text("updated_at").notNull().default(sql\`(CURRENT_TIMESTAMP)\`), +});\n`, + }), + }), + ]), + ); + }); + }); +}); diff --git a/api/src/lib/expand-function/tsserver/commands.ts b/api/src/lib/expand-function/tsserver/commands.ts new file mode 100644 index 000000000..6cf8cf28e --- /dev/null +++ b/api/src/lib/expand-function/tsserver/commands.ts @@ -0,0 +1,176 @@ +import fs from "node:fs"; +import type ts from "typescript"; +import type { MessageConnection } from "vscode-jsonrpc"; +import logger from "../../../logger.js"; +import { type Definition, isDefinitionsArray } from "./types.js"; +import { getFileUri } from "./utils.js"; + +// Modify the openedFiles Map to store the version number +const openedFiles = new Map(); + +export async function openFile( + connection: MessageConnection, + filePath: string, +) { + const fileUri = getFileUri(filePath); + const fileContent = fs.readFileSync(filePath, "utf-8"); + + const existingFile = openedFiles.get(filePath); + if (existingFile && existingFile.content === fileContent) { + // logger.debug("[debug] [openFile] File already opened:", filePath); + return; + } + + const version = (existingFile?.version ?? 0) + 1; + + await connection.sendNotification("textDocument/didOpen", { + textDocument: { + uri: fileUri, + languageId: "typescript", + version: version, + text: fileContent, + }, + }); + openedFiles.set(filePath, { content: fileContent, version }); +} + +export async function updateFile( + connection: MessageConnection, + filePath: string, +) { + const fileUri = getFileUri(filePath); + const newContent = fs.readFileSync(filePath, "utf-8"); + + const existingFile = openedFiles.get(filePath); + if (!existingFile) { + logger.warn( + "[warn] Attempting to update a file that wasn't opened:", + filePath, + ); + return await openFile(connection, filePath); + } + + if (existingFile.content === newContent) { + // logger.debug("[debug] [updateFile] File content unchanged:", filePath); + return; + } + + const newVersion = existingFile.version + 1; + + await connection.sendNotification("textDocument/didChange", { + textDocument: { + uri: fileUri, + version: newVersion, + }, + contentChanges: [{ text: newContent }], + }); + openedFiles.set(filePath, { content: newContent, version: newVersion }); + logger.debug("[debug] Updated document:", fileUri); +} + +/** + * Get the source definition of a TypeScript file at a given position by executing + * the Language Server Protocol (LSP) workspace/executeCommand command, specifically + * the _typescript.goToSourceDefinition command. + * + * This function differs from executing the LSP textDocument/definition command (see {@link getTextDocumentDefinition}) in that + * it retrieves the source definition, which is the original location where a symbol is defined, + * rather than just the location where it is referenced or declared. + * + * @param connection - The TypeScript server connection. + * @param filePath - The path to the TypeScript file. + * @param position - The position in the file to get the source definition for. + * @returns The source definition location or null if not found. + */ +export async function getTsSourceDefinition( + connection: MessageConnection, + filePath: string, + position: ts.LineAndCharacter, +): Promise { + const fileUri = getFileUri(filePath); + + const sourceDefinition = await executeCommand( + connection, + "_typescript.goToSourceDefinition", + [fileUri, position], + ); + + // INVESTIGATE - When is definitionResponse longer than 1? + if (isDefinitionsArray(sourceDefinition)) { + return sourceDefinition[0] ?? null; + } + + logger.warn( + `[warning] getTsSourceDefinition returned an unexpected, unparseable response: ${sourceDefinition}`, + ); + + return null; +} + +/** + * Execute a command on the TypeScript server. + * + * This is useful for non-standard LSP commands that the TypeScript server + * supports. (E.g., the _typescript.goToSourceDefinition command.) + * + * @param connection - The TypeScript server connection. + * @param command - The command to execute. + * @param args - The arguments to pass to the command. + * @returns The response from the server. + */ +export async function executeCommand( + connection: MessageConnection, + command: string, + args: unknown[], +) { + try { + const response = await connection.sendRequest("workspace/executeCommand", { + command: command, + arguments: args, + }); + return response; + } catch (error) { + logger.error( + `Error with 'workspace/executeCommand' for command: ${command} with args: ${JSON.stringify(args, null, 2)}`, + error, + ); + return null; + } +} + +/** + * Get the definition of a TypeScript file at a given position by executing + * the Language Server Protocol (LSP) textDocument/definition command. + * + * This function retrieves the location where a symbol is defined within the TypeScript file, + * which can be useful for navigating to the definition of a symbol from its usage. + * + * @param connection - The TypeScript server connection. + * @param fileUri - The URI of the TypeScript file. + * @param position - The position in the file to get the definition for. + * @returns The definition location or null if not found. + */ +export async function getTextDocumentDefinition( + connection: MessageConnection, + fileUri: string, + position: ts.LineAndCharacter, +): Promise { + const definitionResponse = await connection.sendRequest( + "textDocument/definition", + { + textDocument: { uri: fileUri }, + position: position, + }, + ); + + // INVESTIGATE - When is definitionResponse longer than 1? + if (isDefinitionsArray(definitionResponse)) { + return definitionResponse[0] ?? null; + } + + logger.warn( + `[warning] getTextDocumentDefinition returned an unexpected, unparseable response: ${definitionResponse}`, + ); + + return null; +} diff --git a/api/src/lib/expand-function/tsserver/index.ts b/api/src/lib/expand-function/tsserver/index.ts new file mode 100644 index 000000000..daa95017f --- /dev/null +++ b/api/src/lib/expand-function/tsserver/index.ts @@ -0,0 +1,8 @@ +export { getTSServer } from "./server.js"; +export { + openFile, + getTextDocumentDefinition, + getTsSourceDefinition, +} from "./commands.js"; +export type { Definition } from "./types.js"; +export { getFileUri } from "./utils.js"; diff --git a/api/src/lib/expand-function/tsserver/server.ts b/api/src/lib/expand-function/tsserver/server.ts new file mode 100644 index 000000000..c17cd2400 --- /dev/null +++ b/api/src/lib/expand-function/tsserver/server.ts @@ -0,0 +1,175 @@ +/** + * This file contains the TypeScript language server instance and related functions. + * It uses the `vscode-jsonrpc` library to create a connection to the language server + * and handles the initialization, notification registration, and cleanup. + * + * Note that the language server is initialized in the user's project directory by spawning a child process, + * and running `npx typescript-language-server --stdio`. + * We interface with that process via stdin/stdout. + */ + +import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; +import { resolve } from "node:path"; +import chalk from "chalk"; +import { + type MessageConnection, + StreamMessageReader, + StreamMessageWriter, + createMessageConnection, +} from "vscode-jsonrpc/node.js"; +import logger from "../../../logger.js"; +import { isPublishDiagnosticsParams } from "./types.js"; +import { getFileUri } from "./utils.js"; + +let tsServerInstance: { + connection: MessageConnection; + tsServer: ChildProcessWithoutNullStreams; +} | null = null; + +/** + * Retrieves the TypeScript language server instance for a given project path. + * If an instance already exists, it will be reused to avoid unnecessary initialization. + * + * @param {string} pathToProject - The path to the project directory. + * @returns {Promise<{ connection: MessageConnection; tsServer: ChildProcessWithoutNullStreams }>} The TypeScript language server instance. + */ +export async function getTSServer(pathToProject: string) { + const resolvedPath = resolve(pathToProject); + + if (tsServerInstance) { + // logger.debug( + // chalk.dim( + // `[debug] Reusing existing TS Server instance for project: ${resolvedPath}`, + // ), + // ); + return tsServerInstance; + } + + tsServerInstance = await initializeTSServer(resolvedPath); + return tsServerInstance; +} + +async function initializeTSServer(pathToProject: string) { + logger.debug( + chalk.dim(`[debug] Initializing TS Server for project: ${pathToProject}`), + ); + + const tsServer = spawn("npx", ["typescript-language-server", "--stdio"], { + // NOTE - This will add quite a bit of startup time if the user has not yet downloaded typescript-language-server dependency before via npx... + // And I haven't tested what that overhead is... + // NOTE - We *could* run the language server in the project root (via cwd switch), but I think we handle this by initializing the language server + // and pointing it to the project root below anyhow. + // cwd: pathToProject, + shell: true, + }); + + // Terminate the language server when the Node.js process exits + process.on("exit", () => { + logger.debug( + chalk.dim( + `[debug] Terminating TS Server instance for project: ${pathToProject}`, + ), + ); + tsServer.kill(); + }); + + // NOTE - Uncomment to debug raw output of ts-language-server + // + // tsServer.stdout.on("data", (data) => { + // console.log("") + // console.log(`tsServer stdout: ${data.toString()}`); + // console.log("") + // }); + + tsServer.stderr.on("data", (data) => { + logger.error(`tsserver stderr: ${data.toString()}`); + }); + + const connection = createMessageConnection( + new StreamMessageReader(tsServer.stdout), + new StreamMessageWriter(tsServer.stdin), + ); + + connection.listen(); + + tsServer.on("close", (code) => { + logger.debug(`typescript-language-server process exited with code ${code}`); + }); + + try { + const rootUri = getFileUri(pathToProject); + logger.debug( + chalk.dim( + `[debug] Initializing typescript language server with rootUri: ${rootUri}`, + ), + ); + + const _response = await connection.sendRequest("initialize", { + processId: process.pid, + rootUri: rootUri, + capabilities: {}, + workspaceFolders: [{ uri: rootUri, name: "app" }], + initializationOptions: { + preferences: { + allowIncompleteCompletions: true, + includeCompletionsForModuleExports: true, + includeCompletionsWithInsertText: true, + }, + }, + }); + + logger.debug(chalk.dim("[debug] Initialized typescript language server")); + // logger.debug('Initialization response:', JSON.stringify(_response, null, 2)); + + await connection.sendNotification("initialized"); + + registerNotificationHandlers(connection); + + return { connection, tsServer }; + } catch (error) { + logger.error(chalk.red("Error initializing TS Server:"), error); + throw error; + } +} + +/** + * Registers handlers for various notifications from the TypeScript language server. + * + * @param {MessageConnection} connection - The connection to the TypeScript language server. + */ +function registerNotificationHandlers(connection: MessageConnection) { + // Listen for diagnostics + connection.onNotification("textDocument/publishDiagnostics", (params) => { + if (!isPublishDiagnosticsParams(params)) { + logger.debug( + "[debug] Received unexpected params for `textDocument/publishDiagnostics`", + ); + return; + } + const { uri, diagnostics } = params; + if (diagnostics.length > 0) { + logger.info(`[textDocument/publishDiagnostics] Diagnostics for ${uri}:`); + for (const diag of diagnostics) { + logger.info( + `- [${diag.severity}] ${diag.message} at ${diag.range.start.line}:${diag.range.start.character}`, + ); + } + } else { + logger.debug( + `[textDocument/publishDiagnostics] No diagnostics for ${uri}.`, + ); + } + }); + + // Listen for log messages + connection.onNotification("window/logMessage", (params) => { + const { type, message } = params; + logger.info(`[window/logMessage] Log Message [${type}]: ${message}`); + }); + + // Listen for show messages + connection.onNotification("window/showMessage", (params) => { + const { type, message } = params; + logger.info(`[window/showMessage] Show Message [${type}]: ${message}`); + }); +} diff --git a/api/src/lib/expand-function/tsserver/types.ts b/api/src/lib/expand-function/tsserver/types.ts new file mode 100644 index 000000000..d06a2d151 --- /dev/null +++ b/api/src/lib/expand-function/tsserver/types.ts @@ -0,0 +1,74 @@ +import { z } from "zod"; + +const PositionSchema = z.object({ + line: z.number(), + character: z.number(), +}); + +const RangeSchema = z.object({ + start: PositionSchema, + end: PositionSchema, +}); + +const DefinitionSchema = z.object({ + uri: z.string().url(), + range: RangeSchema, +}); + +export const DefinitionsArraySchema = z.array(DefinitionSchema); + +/** + * Expected response from: + * - `textDocument/definition` + * - `workspace/executeCommand` of `_typescript.goToSourceDefinition` + */ +export type DefinitionsArray = z.infer; + +/** + * A definition description returned from tsserver + */ +export type Definition = z.infer; + +/** + * Type guard for DefinitionsArray (see `DefinitionsArraySchema`) + */ +export function isDefinitionsArray(data: unknown): data is DefinitionsArray { + return DefinitionsArraySchema.safeParse(data).success; +} + +// Define the Zod schema for the diagnostics response +const DiagnosticSchema = z.object({ + severity: z.number().optional(), + message: z.string(), + range: z.object({ + start: z.object({ + line: z.number(), + character: z.number(), + }), + end: z.object({ + line: z.number(), + character: z.number(), + }), + }), + source: z.string().optional(), + code: z.union([z.string(), z.number()]).optional(), +}); + +const PublishDiagnosticsParamsSchema = z.object({ + uri: z.string(), + diagnostics: z.array(DiagnosticSchema), +}); + +/** + * Expected response from: + * - `textDocument/publishDiagnostics` + */ +export type PublishDiagnosticsParams = z.infer< + typeof PublishDiagnosticsParamsSchema +>; + +export const isPublishDiagnosticsParams = ( + data: unknown, +): data is PublishDiagnosticsParams => { + return PublishDiagnosticsParamsSchema.safeParse(data).success; +}; diff --git a/api/src/lib/expand-function/tsserver/utils.ts b/api/src/lib/expand-function/tsserver/utils.ts new file mode 100644 index 000000000..6a2ded57b --- /dev/null +++ b/api/src/lib/expand-function/tsserver/utils.ts @@ -0,0 +1,26 @@ +/** + * Gets the file uri to be used in the typescript language server + * + * If the file path is already a file:// uri, it is returned as is. + * + * @param filePath - The file path to get the uri for + * @returns The file uri (file://) + */ +export function getFileUri(filePath: string) { + if (isFileUri(filePath)) { + return filePath; + } + return `file://${escapeFilePath(filePath)}`; +} + +/** + * Escapes the file path to be used in the typescript language server + * Necessary for Windows support + */ +function escapeFilePath(filePath: string) { + return filePath.replace(/\\/g, "/"); +} + +function isFileUri(uri: string) { + return uri.startsWith("file://"); +} diff --git a/api/src/lib/expand-function/types.ts b/api/src/lib/expand-function/types.ts new file mode 100644 index 000000000..22556bf3a --- /dev/null +++ b/api/src/lib/expand-function/types.ts @@ -0,0 +1,8 @@ +import type ts from "typescript"; + +export type FunctionNode = + | ts.FunctionDeclaration + | ts.ArrowFunction + | ts.FunctionExpression; + +export type FunctionContextType = "unknown" | "function" | "type" | "variable"; diff --git a/api/src/lib/find-source-function.ts b/api/src/lib/find-source-function.ts deleted file mode 100644 index a4cb99b15..000000000 --- a/api/src/lib/find-source-function.ts +++ /dev/null @@ -1,173 +0,0 @@ -import fs from "node:fs"; -import { promisify } from "node:util"; -import { parse } from "acorn"; -import { simple as walkSimple } from "acorn-walk"; -import { SourceMapConsumer } from "source-map"; - -const readFileAsync = promisify(fs.readFile); - -interface FunctionLocation { - startLine: number; - startColumn: number; - endLine: number; - endColumn: number; -} - -async function findFunctionByDefinition( - jsFilePath: string, - functionDefinition: string, -): Promise { - try { - const fileContent = await readFileAsync(jsFilePath, { encoding: "utf-8" }); - const ast = parse(fileContent, { - ecmaVersion: "latest", - locations: true, - sourceType: "module", - }); - - let foundLocation: FunctionLocation | null = null; - - walkSimple(ast, { - FunctionDeclaration(node) { - // Extract function source from original content based on node's location - const funcSource = fileContent.substring(node.start, node.end); - if ( - funcSource.replace(/\s+/g, " ").trim() === - functionDefinition.replace(/\s+/g, " ").trim() && - node.loc - ) { - foundLocation = { - startLine: node.loc.start.line, - startColumn: node.loc.start.column + 1, - endLine: node.loc.end.line, - endColumn: node.loc.end.column + 1, - }; - } - }, - FunctionExpression(node) { - // Repeat as FunctionDeclaration - const funcSource = fileContent.substring(node.start, node.end); - if ( - funcSource.replace(/\s+/g, " ").trim() === - functionDefinition.replace(/\s+/g, " ").trim() && - node.loc - ) { - foundLocation = { - startLine: node.loc.start.line, - startColumn: node.loc.start.column + 1, - endLine: node.loc.end.line, - endColumn: node.loc.end.column + 1, - }; - } - }, - ArrowFunctionExpression(node) { - // Repeat as FunctionDeclaration - const funcSource = fileContent.substring(node.start, node.end); - if ( - funcSource.replace(/\s+/g, " ").trim() === - functionDefinition.replace(/\s+/g, " ").trim() && - node.loc - ) { - foundLocation = { - startLine: node.loc.start.line, - startColumn: node.loc.start.column + 1, - endLine: node.loc.end.line, - endColumn: node.loc.end.column + 1, - }; - } - }, - }); - - return foundLocation; - } catch { - console.error("Error reading or parsing file:", jsFilePath); - return null; - } -} - -/** - * This function will throw an error if the - */ -async function findOriginalSource( - jsFile: string, - line: number, - column: number, -) { - const mapFile = `${jsFile}.map`; // Adjust if your source map is located elsewhere - const sourceMapContent = JSON.parse(fs.readFileSync(mapFile, "utf8")); - - return await SourceMapConsumer.with(sourceMapContent, null, (consumer) => { - const pos = consumer.originalPositionFor({ - line: line, // Line number from JS file - column: column, // Column number from JS file - }); - - consumer.destroy(); - // console.log('Original Source:', pos); - // Optional: Display the source code snippet if needed - const returnNullOnMissing = true; - const sourceContent = consumer.sourceContentFor( - pos.source ?? "", - returnNullOnMissing, - ); - // console.log('Source Content:\n', sourceContent); - return { ...pos, sourceContent }; - }); -} - -export async function findSourceFunction( - jsFilePath: string, - functionText: string, -) { - return findFunctionByDefinition(jsFilePath, functionText).then( - async (loc) => { - const functionStartLine = loc?.startLine ?? 0; - const functionStartColumn = loc?.startColumn ?? 0; - const functionEndLine = loc?.endLine ?? 0; - const functionEndColumn = loc?.endColumn ?? 0; - - const [sourceFunctionStart, sourceFunctionEnd] = await Promise.all([ - findOriginalSource(jsFilePath, functionStartLine, functionStartColumn), - findOriginalSource(jsFilePath, functionEndLine, functionEndColumn), - ]); - - // console.log('Function start:', sourceFunctionStart); - // console.log('Function end:', sourceFunctionEnd); - - const sourceContent = sourceFunctionStart.sourceContent ?? ""; - const startLine = sourceFunctionStart.line; - const endLine = sourceFunctionEnd.line; - // Check if the start/end line are null and otherwise just return sourceContent as is - if (startLine === null || endLine === null) { - // TODO decide what the proper behavior should be when - // we can't find the correct source content. - // For now: return the source content as is - return sourceContent; - } - - const sourceFunction = sourceContent - .split("\n") - .filter((_, i) => i >= startLine - 1 && i <= endLine - 1) - .join("\n"); - - // console.log('Function source:', sourceFunction) - return sourceFunction; - }, - ); -} -/** - * Example Usage - * - const functionText = `async (c) => { - const { id: idString } = c.req.param(); - const id = Number.parseInt(idString, 10); - const sql2 = zs(process.env.FPX_DATABASE_URL ?? ""); - const db = drizzle(sql2, { schema: schema_exports }); - const bug = await db.select().from(bugs).where(eq(bugs.id, id)); - return c.json(bug); - }`; - - const FILE_PATH = './test-content/function-loc-index.js'; - - * - */ diff --git a/api/src/lib/find-source-function/find-source-function.test.ts b/api/src/lib/find-source-function/find-source-function.test.ts new file mode 100644 index 000000000..f522eb5bc --- /dev/null +++ b/api/src/lib/find-source-function/find-source-function.test.ts @@ -0,0 +1,225 @@ +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; +import { findSourceFunctions } from "./find-source-function.js"; + +// Shim __filename and __dirname since we're using esm +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// NOTE - This covers an edge case I found when analyzing code from hono-github-tracker, +// where the source code mapping to the original function would cut off the final character, +// and I think the cause of the issue was a trailing comma after the function's closing brace, +// since it was being passed as an argument to another function. +describe("findSourceFunction", () => { + describe("test-static-analysis", () => { + // Resolve the path and analyze the source maps in our test-data directory + const testStaticAnalysisTestDir = path.resolve( + __dirname, + "./test-data/test-static-analysis", + ); + + it("should find non-async arrow function", async () => { + const { + NON_ASYNC_ARROW_FUNCTION_COMPILED_CODE, + NON_ASYNC_ARROW_FUNCTION_SOURCE_CODE, + } = getStaticAnalysisTestNonAsyncArrowFunctionCode(); + const jsFilePath = path.join(testStaticAnalysisTestDir, "index.js"); + const functionText = NON_ASYNC_ARROW_FUNCTION_COMPILED_CODE; + const result = await findSourceFunctions(jsFilePath, functionText); + + expect(result).toHaveLength(1); + expect(result[0]?.sourceFunction).toEqual( + NON_ASYNC_ARROW_FUNCTION_SOURCE_CODE, + ); + }); + }); + + describe("hono-github-tracker", () => { + // Resolve the path and analyze the source maps in our test-data directory + const honoGithubTrackerTestDir = path.resolve( + __dirname, + "./test-data/hono-js-tracker", + ); + + describe("handler", () => { + it("should find the source handler function", async () => { + const { HANDLER_COMPILED_CODE, HANDLE_SOURCE_CODE } = + getGithubTrackerHandlerCode(); + const jsFilePath = path.join(honoGithubTrackerTestDir, "index.js"); + const functionText = HANDLER_COMPILED_CODE; + const result = await findSourceFunctions(jsFilePath, functionText); + + expect(result).toHaveLength(1); + expect(result[0]?.sourceFunction).toEqual(HANDLE_SOURCE_CODE); + }); + }); + + describe("middleware", () => { + it("should find the source middleware function", async () => { + const { MIDDLEWARE_COMPILED_CODE, MIDDLEWARE_SOURCE_CODE } = + getGithubTrackerMiddlewareCode(); + const jsFilePath = path.join(honoGithubTrackerTestDir, "index.js"); + const functionText = MIDDLEWARE_COMPILED_CODE; + const result = await findSourceFunctions(jsFilePath, functionText); + + expect(result).toHaveLength(1); + expect(result[0]?.sourceFunction).toEqual(MIDDLEWARE_SOURCE_CODE); + }); + }); + + describe("batch input", () => { + it("should be able to do multiple lookups", async () => { + const { HANDLER_COMPILED_CODE, HANDLE_SOURCE_CODE } = + getGithubTrackerHandlerCode(); + const { MIDDLEWARE_COMPILED_CODE, MIDDLEWARE_SOURCE_CODE } = + getGithubTrackerMiddlewareCode(); + const jsFilePath = path.join(honoGithubTrackerTestDir, "index.js"); + const functionDefinitions = [ + HANDLER_COMPILED_CODE, + MIDDLEWARE_COMPILED_CODE, + ]; + const result = await findSourceFunctions( + jsFilePath, + functionDefinitions, + ); + + expect(result).toHaveLength(2); + expect(result[0]?.sourceFunction).toEqual(HANDLE_SOURCE_CODE); + expect(result[1]?.sourceFunction).toEqual(MIDDLEWARE_SOURCE_CODE); + }); + }); + }); +}); + +function getGithubTrackerHandlerCode() { + const HANDLER_COMPILED_CODE = + 'async (c) => {\n const db2 = c.var.db;\n const webhooks2 = c.var.webhooks;\n const fetchUserById = c.var.fetchUserById;\n webhooks2.on(\n ["issues.opened", "star.created", "watch.started"],\n async ({ payload, name }) => {\n const userId = payload.sender.id;\n try {\n await db2.insert(repositories).values({\n description: payload.repository.description,\n fullName: payload.repository.full_name,\n id: payload.repository.id,\n name: payload.repository.name,\n stargazersCount: payload.repository.stargazers_count,\n watchersCount: payload.repository.watchers_count\n }).onConflictDoUpdate({\n target: repositories.id,\n set: {\n stargazersCount: payload.repository.stargazers_count,\n watchersCount: payload.repository.watchers_count\n }\n });\n } catch (error) {\n return c.text(`Error fetching repository: ${error}`, 500);\n }\n try {\n const user = await fetchUserById(userId);\n await db2.insert(users).values({\n avatar: user.avatar_url,\n company: user.company,\n emailAddress: user.email,\n handle: user.login,\n id: user.id,\n location: user.location,\n name: user.name,\n twitterHandle: user.twitter_username\n }).onConflictDoNothing({ target: users.id });\n } catch (error) {\n return c.text(`Error inserting user: ${error}`, 500);\n }\n let eventId;\n if (name === "issues") {\n eventId = payload.issue.id;\n }\n try {\n await db2.insert(events).values({\n eventId,\n eventAction: payload.action,\n eventName: name,\n repoId: payload.repository.id,\n userId\n });\n } catch (error) {\n return c.text(`Error inserting event: ${error}`, 500);\n }\n }\n );\n}'; + const HANDLE_SOURCE_CODE = `async (c) => { + const db = c.var.db; + const webhooks = c.var.webhooks; + const fetchUserById = c.var.fetchUserById; + + webhooks.on( + ["issues.opened", "star.created", "watch.started"], + async ({ payload, name }) => { + const userId = payload.sender.id; + + try { + await db + .insert(repositories) + .values({ + description: payload.repository.description, + fullName: payload.repository.full_name, + id: payload.repository.id, + name: payload.repository.name, + stargazersCount: payload.repository.stargazers_count, + watchersCount: payload.repository.watchers_count, + }) + .onConflictDoUpdate({ + target: repositories.id, + set: { + stargazersCount: payload.repository.stargazers_count, + watchersCount: payload.repository.watchers_count, + }, + }); + } catch (error) { + return c.text(\`Error fetching repository: \${error}\`, 500); + } + + try { + const user = await fetchUserById(userId); + + await db + .insert(users) + .values({ + avatar: user.avatar_url, + company: user.company, + emailAddress: user.email, + handle: user.login, + id: user.id, + location: user.location, + name: user.name, + twitterHandle: user.twitter_username, + }) + .onConflictDoNothing({ target: users.id }); + } catch (error) { + return c.text(\`Error inserting user: \${error}\`, 500); + } + + // Only issues have an event ID + let eventId: number | undefined; + if (name === "issues") { + eventId = payload.issue.id; + } + + try { + await db.insert(events).values({ + eventId, + eventAction: payload.action, + eventName: name, + repoId: payload.repository.id, + userId, + }); + } catch (error) { + return c.text(\`Error inserting event: \${error}\`, 500); + } + }, + ); +}`; + + return { HANDLER_COMPILED_CODE, HANDLE_SOURCE_CODE }; +} + +function getGithubTrackerMiddlewareCode() { + const MIDDLEWARE_COMPILED_CODE = + 'async (c, next) => {\n const secret = c.env.GITHUB_WEBHOOK_SECRET;\n const webhooks2 = getWebhooksInstance(secret);\n c.set("webhooks", webhooks2);\n await next();\n const id = c.req.header("x-github-delivery");\n const signature = c.req.header("x-hub-signature-256");\n const name = c.req.header("x-github-event");\n if (!(id && name && signature)) {\n return c.text("Invalid webhook request", 403);\n }\n const payload = await c.req.text();\n try {\n await webhooks2.verifyAndReceive({\n id,\n name,\n signature,\n payload\n });\n return c.text("Webhook received & verified", 201);\n } catch (error) {\n return c.text(`Failed to verify Github Webhook request: ${error}`, 400);\n }\n }'; + const MIDDLEWARE_SOURCE_CODE = `async (c, next) => { + const secret = c.env.GITHUB_WEBHOOK_SECRET; + const webhooks = getWebhooksInstance(secret); + + c.set("webhooks", webhooks); + + await next(); + + const id = c.req.header("x-github-delivery"); + const signature = c.req.header("x-hub-signature-256"); + const name = c.req.header("x-github-event") as WebhookEventName; + + if (!(id && name && signature)) { + return c.text("Invalid webhook request", 403); + } + + const payload = await c.req.text(); + + try { + await webhooks.verifyAndReceive({ + id, + name, + signature, + payload, + }); + return c.text("Webhook received & verified", 201); + } catch (error) { + return c.text(\`Failed to verify Github Webhook request: \${error}\`, 400); + } + }`; + + return { MIDDLEWARE_COMPILED_CODE, MIDDLEWARE_SOURCE_CODE }; +} + +function getStaticAnalysisTestNonAsyncArrowFunctionCode() { + const NON_ASYNC_ARROW_FUNCTION_COMPILED_CODE = `(c) => { + const auth = c.req.header("Authorization"); + if (auth && PASSPHRASES.includes(auth)) { + return c.text("Hello Hono!"); + } + return c.text("Unauthorized", 401); +}`; + const NON_ASYNC_ARROW_FUNCTION_SOURCE_CODE = + NON_ASYNC_ARROW_FUNCTION_COMPILED_CODE; + + return { + NON_ASYNC_ARROW_FUNCTION_COMPILED_CODE, + NON_ASYNC_ARROW_FUNCTION_SOURCE_CODE, + }; +} diff --git a/api/src/lib/find-source-function/find-source-function.ts b/api/src/lib/find-source-function/find-source-function.ts new file mode 100644 index 000000000..308a9efce --- /dev/null +++ b/api/src/lib/find-source-function/find-source-function.ts @@ -0,0 +1,297 @@ +import fs from "node:fs"; +import { promisify } from "node:util"; +import { parse } from "acorn"; +import { simple as walkSimple } from "acorn-walk"; +import { + type RawIndexMap, + type RawSourceMap, + SourceMapConsumer, +} from "source-map"; +import logger from "../../logger.js"; + +const readFileAsync = promisify(fs.readFile); + +type FunctionLocation = { + startLine: number; + startColumn: number; + endLine: number; + endColumn: number; +}; + +/** + * Finds the locations of specified function definitions within the provided JavaScript file contents. + * + * @param {string} jsFileContents - The contents of the JavaScript file to search. + * @param {Array} functionDefinitions - An array of function definition strings to locate. + * @returns {Promise>} + * A promise that resolves to a record mapping each function definition to its normalized form and location. + */ +async function findFunctionsByDefinition( + jsFileContents: string, + functionDefinitions: Array, +): Promise< + Record +> { + try { + // Create a map of function definitions to their normalized form and foundLocation + const functionMap = functionDefinitions.reduce( + (acc, def) => { + acc[def] = { + normalized: def.replace(/\s+/g, " ").trim(), + foundLocation: null, + }; + return acc; + }, + {} as Record< + string, + { normalized: string; foundLocation: FunctionLocation | null } + >, + ); + + const ast = parse(jsFileContents, { + ecmaVersion: "latest", + locations: true, + sourceType: "module", + }); + + walkSimple(ast, { + FunctionDeclaration(node) { + for (const key in functionMap) { + if (functionMap[key].foundLocation) { + continue; + } + const funcSource = jsFileContents.substring(node.start, node.end); + if ( + node.loc && + funcSource.replace(/\s+/g, " ").trim() === + functionMap[key].normalized + ) { + functionMap[key].foundLocation = { + startLine: node.loc.start.line, + startColumn: node.loc.start.column + 1, + endLine: node.loc.end.line, + endColumn: node.loc.end.column + 1, + }; + } + } + }, + FunctionExpression(node) { + for (const key in functionMap) { + if (functionMap[key].foundLocation) { + continue; + } + const funcSource = jsFileContents.substring(node.start, node.end); + if ( + node.loc && + funcSource.replace(/\s+/g, " ").trim() === + functionMap[key].normalized + ) { + functionMap[key].foundLocation = { + startLine: node.loc.start.line, + startColumn: node.loc.start.column + 1, + endLine: node.loc.end.line, + endColumn: node.loc.end.column + 1, + }; + } + } + }, + ArrowFunctionExpression(node) { + for (const key in functionMap) { + if (functionMap[key].foundLocation) { + continue; + } + const funcSource = jsFileContents.substring(node.start, node.end); + if ( + node.loc && + funcSource.replace(/\s+/g, " ").trim() === + functionMap[key].normalized + ) { + functionMap[key].foundLocation = { + startLine: node.loc.start.line, + startColumn: node.loc.start.column, + endLine: node.loc.end.line, + endColumn: node.loc.end.column, + }; + } + } + }, + }); + + return functionMap; + } catch { + logger.error("[findFunctionByDefinition] Error parsing js file contents"); + return {}; + } +} + +/** + * Finds the original source position for a given position in the compiled JavaScript using a source map. + * + * @param {RawSourceMap | RawIndexMap} sourceMapContent - The source map content. + * @param {number} line - The line number in the compiled JavaScript file. + * @param {number} column - The column number in the compiled JavaScript file. + * @returns {Promise<{ source: string | null; sourceContent: string | null; line: number | null; column: number | null }>} + * A promise that resolves to the original source position and content. + * @throws Will throw an error if the source map is not valid JSON. + */ +async function findOriginalSource( + sourceMapContent: RawSourceMap | RawIndexMap, + line: number, + column: number, +) { + return await SourceMapConsumer.with(sourceMapContent, null, (consumer) => { + const pos = consumer.originalPositionFor({ + line, // Line number from JS file + column, // Column number from JS file + }); + + consumer.destroy(); + + // Optional: Display the source code snippet if needed + const returnNullOnMissing = true; + const sourceContent = consumer.sourceContentFor( + pos.source ?? "", + returnNullOnMissing, + ); + + return { ...pos, sourceContent }; + }); +} + +export type SourceFunctionResult = { + /** The (compiled) function text that was used to find the source */ + functionText: string; + /** The source file */ + sourceFile: string | null; + /** The source code of the function */ + sourceFunction: string | null; +}; + +/** + * Finds the original source functions corresponding to compiled function texts using source maps. + * + * @param {string} jsFilePath - The path to the compiled JavaScript file. + * @param {string | Array} compiledFunctionText - The compiled function text(s) to locate in the source. + * @param {boolean} [returnNullOnMissing=false] - Whether to return null when a source function is missing. + * @param {Object} [hints={}] - Optional hints to provide preloaded source map content or JavaScript file contents. + * @param {RawSourceMap | RawIndexMap} [hints.sourceMapContent] - Preloaded source map content. + * @param {string} [hints.jsFileContents] - Preloaded JavaScript file contents. + * @returns {Promise>} A promise that resolves to an array of results mapping compiled functions to their sources. + */ +export async function findSourceFunctions( + jsFilePath: string, + compiledFunctionText: string | Array, + returnNullOnMissing = false, + hints: { + sourceMapContent?: RawSourceMap | RawIndexMap; + jsFileContents?: string; + } = {}, +): Promise> { + const mapFile = `${jsFilePath}.map`; + // OPTIMIZE - This is a hot path, so we should cache the source map content + // Each parse takes about 10ms even on a medium sized codebase + const sourceMapContent = + hints.sourceMapContent ?? + JSON.parse(await readFileAsync(mapFile, { encoding: "utf8" })); + const jsFileContents = + hints.jsFileContents ?? + (await readFileAsync(jsFilePath, { encoding: "utf8" })); + + const functionDefinitions = Array.isArray(compiledFunctionText) + ? compiledFunctionText + : [compiledFunctionText]; + + const locations = await findFunctionsByDefinition( + jsFileContents, + functionDefinitions, + ); + + const results = await Promise.all( + Object.entries(locations).map( + async ([compiledFunctionText, { foundLocation }]) => { + if (!foundLocation) { + return { + functionText: compiledFunctionText, + sourceFile: null, + sourceFunction: null, + }; + } + const lookupResult = await lookUpLocation(foundLocation); + return { + functionText: compiledFunctionText, + sourceFile: lookupResult?.sourceFile ?? null, + sourceFunction: lookupResult?.sourceFunction ?? null, + }; + }, + ), + ); + + return results; + + /** + * Looks up the original source function based on a function's location in the compiled code. + * + * @param {FunctionLocation} loc - The location of the function in the compiled JavaScript file. + * @returns {Promise<{ sourceFunction: string | null; source: string | null } | null>} + * A promise that resolves to the original source function and its source file, or null if not found. + */ + async function lookUpLocation(loc: FunctionLocation) { + const functionStartLine = loc?.startLine ?? 0; + const functionStartColumn = loc?.startColumn ?? 0; + const functionEndLine = loc?.endLine ?? 0; + const functionEndColumn = loc?.endColumn ?? 0; + + // NOTE - We want to execute these in parallel, time is of the essence + const [sourceFunctionStart, sourceFunctionEnd] = await Promise.all([ + findOriginalSource( + sourceMapContent, + functionStartLine, + functionStartColumn, + ), + findOriginalSource(sourceMapContent, functionEndLine, functionEndColumn), + ]); + + const sourceFile = sourceFunctionStart.source; + const sourceContent = sourceFunctionStart.sourceContent ?? ""; + const startLine = sourceFunctionStart.line; + const startColumn = sourceFunctionStart.column; + const endLine = sourceFunctionEnd.line; + const endColumn = sourceFunctionEnd.column; + // Check if the start/end line are null and otherwise just return sourceContent as is + if (startLine === null || endLine === null) { + // TODO decide what the proper behavior should be when + // we can't find the correct source content. + // For now: return the source content as is + return returnNullOnMissing + ? null + : { sourceContent, sourceFile, sourceFunction: null }; + } + + const lines = sourceContent.split("\n").slice(startLine - 1, endLine); + + const sourceFunction = lines + .map((line, index) => { + if (index === 0 && startLine === endLine) { + return line.slice(startColumn ?? 0, endColumn ?? 0); + } + if (index === 0) { + const sliceFrom = startColumn ?? 0; + return line.slice(sliceFrom); + } + if (index === endLine - startLine) { + // MEGA HACK - Add 1 to the end column only if it ends in a comma + // I don't know what was causing this issue, but when we parse the source code, + // we need to account for the fact that the original source code might have + // trailing commas in functions that are passed as arguments to other functions. + // In that case, we need to add 1 to the end column to account for something that gets odd when receiving the location back. + const endsInComma = line.endsWith(","); + const sliceTo = (endColumn ?? 0) + (endsInComma ? 1 : 0); + return line.slice(0, sliceTo); + } + return line; + }) + .join("\n"); + + return { sourceFunction, sourceFile }; + } +} diff --git a/api/src/lib/find-source-function/index.ts b/api/src/lib/find-source-function/index.ts new file mode 100644 index 000000000..5a9ccab28 --- /dev/null +++ b/api/src/lib/find-source-function/index.ts @@ -0,0 +1,4 @@ +export { + findSourceFunctions, + type SourceFunctionResult, +} from "./find-source-function.js"; diff --git a/api/src/lib/find-source-function/test-data/hono-js-tracker/index.js b/api/src/lib/find-source-function/test-data/hono-js-tracker/index.js new file mode 100644 index 000000000..e2dde4289 --- /dev/null +++ b/api/src/lib/find-source-function/test-data/hono-js-tracker/index.js @@ -0,0 +1,44188 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to2, from, except2, desc2) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to2, key) && key !== except2) + __defProp(to2, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable }); + } + return to2; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// .wrangler/tmp/bundle-m4kIpi/checked-fetch.js +function checkURL(request2, init) { + const url = request2 instanceof URL ? request2 : new URL( + (typeof request2 === "string" ? new Request(request2, init) : request2).url + ); + if (url.port && url.port !== "443" && url.protocol === "https:") { + if (!urls.has(url.toString())) { + urls.add(url.toString()); + console.warn( + `WARNING: known issue with \`fetch()\` requests to custom HTTPS ports in published Workers: + - ${url.toString()} - the custom port will be ignored when the Worker is published using the \`wrangler deploy\` command. +` + ); + } + } +} +var urls; +var init_checked_fetch = __esm({ + ".wrangler/tmp/bundle-m4kIpi/checked-fetch.js"() { + "use strict"; + urls = /* @__PURE__ */ new Set(); + globalThis.fetch = new Proxy(globalThis.fetch, { + apply(target, thisArg, argArray) { + const [request2, init] = argArray; + checkURL(request2, init); + return Reflect.apply(target, thisArg, argArray); + } + }); + } +}); + +// wrangler-modules-watch:wrangler:modules-watch +var init_wrangler_modules_watch = __esm({ + "wrangler-modules-watch:wrangler:modules-watch"() { + init_checked_fetch(); + init_modules_watch_stub(); + } +}); + +// node_modules/.pnpm/wrangler@3.79.0_@cloudflare+workers-types@4.20240925.0/node_modules/wrangler/templates/modules-watch-stub.js +var init_modules_watch_stub = __esm({ + "node_modules/.pnpm/wrangler@3.79.0_@cloudflare+workers-types@4.20240925.0/node_modules/wrangler/templates/modules-watch-stub.js"() { + init_wrangler_modules_watch(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js +var require_globalThis = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/platform/browser/globalThis.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports._globalThis = void 0; + exports._globalThis = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {}; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/platform/browser/index.js +var require_browser = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/platform/browser/index.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m2[k]; + } }); + } : function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + o[k2] = m2[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p2 in m2) + if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) + __createBinding(exports2, m2, p2); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_globalThis(), exports); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/version.js +var require_version = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/version.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = void 0; + exports.VERSION = "1.9.0"; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/internal/semver.js +var require_semver = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/internal/semver.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isCompatible = exports._makeCompatibilityCheck = void 0; + var version_1 = require_version(); + var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; + function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); + const rejectedVersions = /* @__PURE__ */ new Set(); + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + return () => false; + } + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4] + }; + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject(v2) { + rejectedVersions.add(v2); + return false; + } + function _accept(v2) { + acceptedVersions.add(v2); + return true; + } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + return _reject(globalVersion); + } + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4] + }; + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; + } + exports._makeCompatibilityCheck = _makeCompatibilityCheck; + exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/internal/global-utils.js +var require_global_utils = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/internal/global-utils.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; + var platform_1 = require_browser(); + var version_1 = require_version(); + var semver_1 = require_semver(); + var major = version_1.VERSION.split(".")[0]; + var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); + var _global = platform_1._globalThis; + function registerGlobal(type, instance, diag14, allowOverride = false) { + var _a95; + const api3 = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a95 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a95 !== void 0 ? _a95 : { + version: version_1.VERSION + }; + if (!allowOverride && api3[type]) { + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag14.error(err.stack || err.message); + return false; + } + if (api3.version !== version_1.VERSION) { + const err = new Error(`@opentelemetry/api: Registration of version v${api3.version} for ${type} does not match previously registered API v${version_1.VERSION}`); + diag14.error(err.stack || err.message); + return false; + } + api3[type] = instance; + diag14.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); + return true; + } + exports.registerGlobal = registerGlobal; + function getGlobal(type) { + var _a95, _b; + const globalVersion = (_a95 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a95 === void 0 ? void 0 : _a95.version; + if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { + return; + } + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; + } + exports.getGlobal = getGlobal; + function unregisterGlobal(type, diag14) { + diag14.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); + const api3 = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api3) { + delete api3[type]; + } + } + exports.unregisterGlobal = unregisterGlobal; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js +var require_ComponentLogger = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiagComponentLogger = void 0; + var global_utils_1 = require_global_utils(); + var DiagComponentLogger = class { + constructor(props) { + this._namespace = props.namespace || "DiagComponentLogger"; + } + debug(...args) { + return logProxy("debug", this._namespace, args); + } + error(...args) { + return logProxy("error", this._namespace, args); + } + info(...args) { + return logProxy("info", this._namespace, args); + } + warn(...args) { + return logProxy("warn", this._namespace, args); + } + verbose(...args) { + return logProxy("verbose", this._namespace, args); + } + }; + exports.DiagComponentLogger = DiagComponentLogger; + function logProxy(funcName, namespace, args) { + const logger = (0, global_utils_1.getGlobal)("diag"); + if (!logger) { + return; + } + args.unshift(namespace); + return logger[funcName](...args); + } + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag/types.js +var require_types = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag/types.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiagLogLevel = void 0; + var DiagLogLevel3; + (function(DiagLogLevel4) { + DiagLogLevel4[DiagLogLevel4["NONE"] = 0] = "NONE"; + DiagLogLevel4[DiagLogLevel4["ERROR"] = 30] = "ERROR"; + DiagLogLevel4[DiagLogLevel4["WARN"] = 50] = "WARN"; + DiagLogLevel4[DiagLogLevel4["INFO"] = 60] = "INFO"; + DiagLogLevel4[DiagLogLevel4["DEBUG"] = 70] = "DEBUG"; + DiagLogLevel4[DiagLogLevel4["VERBOSE"] = 80] = "VERBOSE"; + DiagLogLevel4[DiagLogLevel4["ALL"] = 9999] = "ALL"; + })(DiagLogLevel3 = exports.DiagLogLevel || (exports.DiagLogLevel = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js +var require_logLevelLogger = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createLogLevelDiagLogger = void 0; + var types_1 = require_types(); + function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < types_1.DiagLogLevel.NONE) { + maxLevel = types_1.DiagLogLevel.NONE; + } else if (maxLevel > types_1.DiagLogLevel.ALL) { + maxLevel = types_1.DiagLogLevel.ALL; + } + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger[funcName]; + if (typeof theFunc === "function" && maxLevel >= theLevel) { + return theFunc.bind(logger); + } + return function() { + }; + } + return { + error: _filterFunc("error", types_1.DiagLogLevel.ERROR), + warn: _filterFunc("warn", types_1.DiagLogLevel.WARN), + info: _filterFunc("info", types_1.DiagLogLevel.INFO), + debug: _filterFunc("debug", types_1.DiagLogLevel.DEBUG), + verbose: _filterFunc("verbose", types_1.DiagLogLevel.VERBOSE) + }; + } + exports.createLogLevelDiagLogger = createLogLevelDiagLogger; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/diag.js +var require_diag = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/diag.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiagAPI = void 0; + var ComponentLogger_1 = require_ComponentLogger(); + var logLevelLogger_1 = require_logLevelLogger(); + var types_1 = require_types(); + var global_utils_1 = require_global_utils(); + var API_NAME = "diag"; + var DiagAPI = class { + /** + * Private internal constructor + * @private + */ + constructor() { + function _logProxy(funcName) { + return function(...args) { + const logger = (0, global_utils_1.getGlobal)("diag"); + if (!logger) + return; + return logger[funcName](...args); + }; + } + const self2 = this; + const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { + var _a95, _b, _c; + if (logger === self2) { + const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); + self2.error((_a95 = err.stack) !== null && _a95 !== void 0 ? _a95 : err.message); + return false; + } + if (typeof optionsOrLogLevel === "number") { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel + }; + } + const oldLogger = (0, global_utils_1.getGlobal)("diag"); + const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return (0, global_utils_1.registerGlobal)("diag", newLogger, self2, true); + }; + self2.setLogger = setLogger; + self2.disable = () => { + (0, global_utils_1.unregisterGlobal)(API_NAME, self2); + }; + self2.createComponentLogger = (options) => { + return new ComponentLogger_1.DiagComponentLogger(options); + }; + self2.verbose = _logProxy("verbose"); + self2.debug = _logProxy("debug"); + self2.info = _logProxy("info"); + self2.warn = _logProxy("warn"); + self2.error = _logProxy("error"); + } + /** Get the singleton instance of the DiagAPI API */ + static instance() { + if (!this._instance) { + this._instance = new DiagAPI(); + } + return this._instance; + } + }; + exports.DiagAPI = DiagAPI; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js +var require_baggage_impl = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BaggageImpl = void 0; + var BaggageImpl = class { + constructor(entries) { + this._entries = entries ? new Map(entries) : /* @__PURE__ */ new Map(); + } + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) { + return void 0; + } + return Object.assign({}, entry); + } + getAllEntries() { + return Array.from(this._entries.entries()).map(([k, v2]) => [k, v2]); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + } + removeEntries(...keys2) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys2) { + newBaggage._entries.delete(key); + } + return newBaggage; + } + clear() { + return new BaggageImpl(); + } + }; + exports.BaggageImpl = BaggageImpl; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js +var require_symbol = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.baggageEntryMetadataSymbol = void 0; + exports.baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata"); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/baggage/utils.js +var require_utils = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/baggage/utils.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; + var diag_1 = require_diag(); + var baggage_impl_1 = require_baggage_impl(); + var symbol_1 = require_symbol(); + var diag14 = diag_1.DiagAPI.instance(); + function createBaggage(entries = {}) { + return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); + } + exports.createBaggage = createBaggage; + function baggageEntryMetadataFromString3(str) { + if (typeof str !== "string") { + diag14.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ""; + } + return { + __TYPE__: symbol_1.baggageEntryMetadataSymbol, + toString() { + return str; + } + }; + } + exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString3; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/context/context.js +var require_context = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/context/context.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ROOT_CONTEXT = exports.createContextKey = void 0; + function createContextKey2(description) { + return Symbol.for(description); + } + exports.createContextKey = createContextKey2; + var BaseContext = class { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + constructor(parentContext) { + const self2 = this; + self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); + self2.getValue = (key) => self2._currentContext.get(key); + self2.setValue = (key, value) => { + const context7 = new BaseContext(self2._currentContext); + context7._currentContext.set(key, value); + return context7; + }; + self2.deleteValue = (key) => { + const context7 = new BaseContext(self2._currentContext); + context7._currentContext.delete(key); + return context7; + }; + } + }; + exports.ROOT_CONTEXT = new BaseContext(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js +var require_consoleLogger = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiagConsoleLogger = void 0; + var consoleMap = [ + { n: "error", c: "error" }, + { n: "warn", c: "warn" }, + { n: "info", c: "info" }, + { n: "debug", c: "debug" }, + { n: "verbose", c: "trace" } + ]; + var DiagConsoleLogger = class { + constructor() { + function _consoleFunc(funcName) { + return function(...args) { + if (console) { + let theFunc = console[funcName]; + if (typeof theFunc !== "function") { + theFunc = console.log; + } + if (typeof theFunc === "function") { + return theFunc.apply(console, args); + } + } + }; + } + for (let i = 0; i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } + }; + exports.DiagConsoleLogger = DiagConsoleLogger; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js +var require_NoopMeter = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; + var NoopMeter = class { + constructor() { + } + /** + * @see {@link Meter.createGauge} + */ + createGauge(_name, _options) { + return exports.NOOP_GAUGE_METRIC; + } + /** + * @see {@link Meter.createHistogram} + */ + createHistogram(_name, _options) { + return exports.NOOP_HISTOGRAM_METRIC; + } + /** + * @see {@link Meter.createCounter} + */ + createCounter(_name, _options) { + return exports.NOOP_COUNTER_METRIC; + } + /** + * @see {@link Meter.createUpDownCounter} + */ + createUpDownCounter(_name, _options) { + return exports.NOOP_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableGauge} + */ + createObservableGauge(_name, _options) { + return exports.NOOP_OBSERVABLE_GAUGE_METRIC; + } + /** + * @see {@link Meter.createObservableCounter} + */ + createObservableCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_COUNTER_METRIC; + } + /** + * @see {@link Meter.createObservableUpDownCounter} + */ + createObservableUpDownCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + /** + * @see {@link Meter.addBatchObservableCallback} + */ + addBatchObservableCallback(_callback, _observables) { + } + /** + * @see {@link Meter.removeBatchObservableCallback} + */ + removeBatchObservableCallback(_callback) { + } + }; + exports.NoopMeter = NoopMeter; + var NoopMetric = class { + }; + exports.NoopMetric = NoopMetric; + var NoopCounterMetric = class extends NoopMetric { + add(_value, _attributes) { + } + }; + exports.NoopCounterMetric = NoopCounterMetric; + var NoopUpDownCounterMetric = class extends NoopMetric { + add(_value, _attributes) { + } + }; + exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; + var NoopGaugeMetric = class extends NoopMetric { + record(_value, _attributes) { + } + }; + exports.NoopGaugeMetric = NoopGaugeMetric; + var NoopHistogramMetric = class extends NoopMetric { + record(_value, _attributes) { + } + }; + exports.NoopHistogramMetric = NoopHistogramMetric; + var NoopObservableMetric = class { + addCallback(_callback) { + } + removeCallback(_callback) { + } + }; + exports.NoopObservableMetric = NoopObservableMetric; + var NoopObservableCounterMetric = class extends NoopObservableMetric { + }; + exports.NoopObservableCounterMetric = NoopObservableCounterMetric; + var NoopObservableGaugeMetric = class extends NoopObservableMetric { + }; + exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; + var NoopObservableUpDownCounterMetric = class extends NoopObservableMetric { + }; + exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; + exports.NOOP_METER = new NoopMeter(); + exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); + exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric(); + exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); + exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); + exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); + exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); + exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); + function createNoopMeter() { + return exports.NOOP_METER; + } + exports.createNoopMeter = createNoopMeter; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/metrics/Metric.js +var require_Metric = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/metrics/Metric.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueType = void 0; + var ValueType; + (function(ValueType2) { + ValueType2[ValueType2["INT"] = 0] = "INT"; + ValueType2[ValueType2["DOUBLE"] = 1] = "DOUBLE"; + })(ValueType = exports.ValueType || (exports.ValueType = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js +var require_TextMapPropagator = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; + exports.defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) { + return void 0; + } + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) { + return []; + } + return Object.keys(carrier); + } + }; + exports.defaultTextMapSetter = { + set(carrier, key, value) { + if (carrier == null) { + return; + } + carrier[key] = value; + } + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js +var require_NoopContextManager = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopContextManager = void 0; + var context_1 = require_context(); + var NoopContextManager = class { + active() { + return context_1.ROOT_CONTEXT; + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } + }; + exports.NoopContextManager = NoopContextManager; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/context.js +var require_context2 = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/context.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ContextAPI = void 0; + var NoopContextManager_1 = require_NoopContextManager(); + var global_utils_1 = require_global_utils(); + var diag_1 = require_diag(); + var API_NAME = "context"; + var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); + var ContextAPI = class { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + } + /** Get the singleton instance of the Context API */ + static getInstance() { + if (!this._instance) { + this._instance = new ContextAPI(); + } + return this._instance; + } + /** + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false + */ + setGlobalContextManager(contextManager) { + return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); + } + /** + * Get the currently active context + */ + active() { + return this._getContextManager().active(); + } + /** + * Execute a function with an active context + * + * @param context context to be active during function execution + * @param fn function to execute in a context + * @param thisArg optional receiver to be used for calling fn + * @param args optional arguments forwarded to fn + */ + with(context7, fn, thisArg, ...args) { + return this._getContextManager().with(context7, fn, thisArg, ...args); + } + /** + * Bind a context to a target function or event emitter + * + * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind + */ + bind(context7, target) { + return this._getContextManager().bind(context7, target); + } + _getContextManager() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; + } + /** Disable and remove the global context manager */ + disable() { + this._getContextManager().disable(); + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + }; + exports.ContextAPI = ContextAPI; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js +var require_trace_flags = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceFlags = void 0; + var TraceFlags6; + (function(TraceFlags7) { + TraceFlags7[TraceFlags7["NONE"] = 0] = "NONE"; + TraceFlags7[TraceFlags7["SAMPLED"] = 1] = "SAMPLED"; + })(TraceFlags6 = exports.TraceFlags || (exports.TraceFlags = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js +var require_invalid_span_constants = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; + var trace_flags_1 = require_trace_flags(); + exports.INVALID_SPANID = "0000000000000000"; + exports.INVALID_TRACEID = "00000000000000000000000000000000"; + exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js +var require_NonRecordingSpan = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NonRecordingSpan = void 0; + var invalid_span_constants_1 = require_invalid_span_constants(); + var NonRecordingSpan = class { + constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { + this._spanContext = _spanContext; + } + // Returns a SpanContext. + spanContext() { + return this._spanContext; + } + // By default does nothing + setAttribute(_key, _value) { + return this; + } + // By default does nothing + setAttributes(_attributes) { + return this; + } + // By default does nothing + addEvent(_name, _attributes) { + return this; + } + addLink(_link) { + return this; + } + addLinks(_links) { + return this; + } + // By default does nothing + setStatus(_status) { + return this; + } + // By default does nothing + updateName(_name) { + return this; + } + // By default does nothing + end(_endTime) { + } + // isRecording always returns false for NonRecordingSpan. + isRecording() { + return false; + } + // By default does nothing + recordException(_exception, _time) { + } + }; + exports.NonRecordingSpan = NonRecordingSpan; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/context-utils.js +var require_context_utils = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/context-utils.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; + var context_1 = require_context(); + var NonRecordingSpan_1 = require_NonRecordingSpan(); + var context_2 = require_context2(); + var SPAN_KEY = (0, context_1.createContextKey)("OpenTelemetry Context Key SPAN"); + function getSpan(context7) { + return context7.getValue(SPAN_KEY) || void 0; + } + exports.getSpan = getSpan; + function getActiveSpan() { + return getSpan(context_2.ContextAPI.getInstance().active()); + } + exports.getActiveSpan = getActiveSpan; + function setSpan(context7, span) { + return context7.setValue(SPAN_KEY, span); + } + exports.setSpan = setSpan; + function deleteSpan(context7) { + return context7.deleteValue(SPAN_KEY); + } + exports.deleteSpan = deleteSpan; + function setSpanContext(context7, spanContext) { + return setSpan(context7, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); + } + exports.setSpanContext = setSpanContext; + function getSpanContext(context7) { + var _a95; + return (_a95 = getSpan(context7)) === null || _a95 === void 0 ? void 0 : _a95.spanContext(); + } + exports.getSpanContext = getSpanContext; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js +var require_spancontext_utils = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0; + var invalid_span_constants_1 = require_invalid_span_constants(); + var NonRecordingSpan_1 = require_NonRecordingSpan(); + var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; + var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; + function isValidTraceId2(traceId) { + return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; + } + exports.isValidTraceId = isValidTraceId2; + function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; + } + exports.isValidSpanId = isValidSpanId; + function isSpanContextValid3(spanContext) { + return isValidTraceId2(spanContext.traceId) && isValidSpanId(spanContext.spanId); + } + exports.isSpanContextValid = isSpanContextValid3; + function wrapSpanContext(spanContext) { + return new NonRecordingSpan_1.NonRecordingSpan(spanContext); + } + exports.wrapSpanContext = wrapSpanContext; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js +var require_NoopTracer = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopTracer = void 0; + var context_1 = require_context2(); + var context_utils_1 = require_context_utils(); + var NonRecordingSpan_1 = require_NonRecordingSpan(); + var spancontext_utils_1 = require_spancontext_utils(); + var contextApi = context_1.ContextAPI.getInstance(); + var NoopTracer = class { + // startSpan starts a noop span. + startSpan(name, options, context7 = contextApi.active()) { + const root = Boolean(options === null || options === void 0 ? void 0 : options.root); + if (root) { + return new NonRecordingSpan_1.NonRecordingSpan(); + } + const parentFromContext = context7 && (0, context_utils_1.getSpanContext)(context7); + if (isSpanContext(parentFromContext) && (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { + return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); + } else { + return new NonRecordingSpan_1.NonRecordingSpan(); + } + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } else if (arguments.length === 2) { + fn = arg2; + } else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, void 0, span); + } + }; + exports.NoopTracer = NoopTracer; + function isSpanContext(spanContext) { + return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number"; + } + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js +var require_ProxyTracer = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProxyTracer = void 0; + var NoopTracer_1 = require_NoopTracer(); + var NOOP_TRACER = new NoopTracer_1.NoopTracer(); + var ProxyTracer = class { + constructor(_provider, name, version2, options) { + this._provider = _provider; + this.name = name; + this.version = version2; + this.options = options; + } + startSpan(name, options, context7) { + return this._getTracer().startSpan(name, options, context7); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer2 = this._getTracer(); + return Reflect.apply(tracer2.startActiveSpan, tracer2, arguments); + } + /** + * Try to get a tracer from the proxy tracer provider. + * If the proxy tracer provider has no delegate, return a noop tracer. + */ + _getTracer() { + if (this._delegate) { + return this._delegate; + } + const tracer2 = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer2) { + return NOOP_TRACER; + } + this._delegate = tracer2; + return this._delegate; + } + }; + exports.ProxyTracer = ProxyTracer; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js +var require_NoopTracerProvider = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopTracerProvider = void 0; + var NoopTracer_1 = require_NoopTracer(); + var NoopTracerProvider = class { + getTracer(_name, _version, _options) { + return new NoopTracer_1.NoopTracer(); + } + }; + exports.NoopTracerProvider = NoopTracerProvider; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js +var require_ProxyTracerProvider = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProxyTracerProvider = void 0; + var ProxyTracer_1 = require_ProxyTracer(); + var NoopTracerProvider_1 = require_NoopTracerProvider(); + var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); + var ProxyTracerProvider = class { + /** + * Get a {@link ProxyTracer} + */ + getTracer(name, version2, options) { + var _a95; + return (_a95 = this.getDelegateTracer(name, version2, options)) !== null && _a95 !== void 0 ? _a95 : new ProxyTracer_1.ProxyTracer(this, name, version2, options); + } + getDelegate() { + var _a95; + return (_a95 = this._delegate) !== null && _a95 !== void 0 ? _a95 : NOOP_TRACER_PROVIDER; + } + /** + * Set the delegate tracer provider + */ + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version2, options) { + var _a95; + return (_a95 = this._delegate) === null || _a95 === void 0 ? void 0 : _a95.getTracer(name, version2, options); + } + }; + exports.ProxyTracerProvider = ProxyTracerProvider; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js +var require_SamplingResult = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SamplingDecision = void 0; + var SamplingDecision3; + (function(SamplingDecision4) { + SamplingDecision4[SamplingDecision4["NOT_RECORD"] = 0] = "NOT_RECORD"; + SamplingDecision4[SamplingDecision4["RECORD"] = 1] = "RECORD"; + SamplingDecision4[SamplingDecision4["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; + })(SamplingDecision3 = exports.SamplingDecision || (exports.SamplingDecision = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/span_kind.js +var require_span_kind = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/span_kind.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SpanKind = void 0; + var SpanKind4; + (function(SpanKind5) { + SpanKind5[SpanKind5["INTERNAL"] = 0] = "INTERNAL"; + SpanKind5[SpanKind5["SERVER"] = 1] = "SERVER"; + SpanKind5[SpanKind5["CLIENT"] = 2] = "CLIENT"; + SpanKind5[SpanKind5["PRODUCER"] = 3] = "PRODUCER"; + SpanKind5[SpanKind5["CONSUMER"] = 4] = "CONSUMER"; + })(SpanKind4 = exports.SpanKind || (exports.SpanKind = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/status.js +var require_status = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/status.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SpanStatusCode = void 0; + var SpanStatusCode3; + (function(SpanStatusCode4) { + SpanStatusCode4[SpanStatusCode4["UNSET"] = 0] = "UNSET"; + SpanStatusCode4[SpanStatusCode4["OK"] = 1] = "OK"; + SpanStatusCode4[SpanStatusCode4["ERROR"] = 2] = "ERROR"; + })(SpanStatusCode3 = exports.SpanStatusCode || (exports.SpanStatusCode = {})); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js +var require_tracestate_validators = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateValue = exports.validateKey = void 0; + var VALID_KEY_CHAR_RANGE2 = "[_0-9a-z-*/]"; + var VALID_KEY2 = `[a-z]${VALID_KEY_CHAR_RANGE2}{0,255}`; + var VALID_VENDOR_KEY2 = `[a-z0-9]${VALID_KEY_CHAR_RANGE2}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE2}{0,13}`; + var VALID_KEY_REGEX2 = new RegExp(`^(?:${VALID_KEY2}|${VALID_VENDOR_KEY2})$`); + var VALID_VALUE_BASE_REGEX2 = /^[ -~]{0,255}[!-~]$/; + var INVALID_VALUE_COMMA_EQUAL_REGEX2 = /,|=/; + function validateKey2(key) { + return VALID_KEY_REGEX2.test(key); + } + exports.validateKey = validateKey2; + function validateValue2(value) { + return VALID_VALUE_BASE_REGEX2.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX2.test(value); + } + exports.validateValue = validateValue2; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js +var require_tracestate_impl = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceStateImpl = void 0; + var tracestate_validators_1 = require_tracestate_validators(); + var MAX_TRACE_STATE_ITEMS2 = 32; + var MAX_TRACE_STATE_LEN2 = 512; + var LIST_MEMBERS_SEPARATOR2 = ","; + var LIST_MEMBER_KEY_VALUE_SPLITTER2 = "="; + var TraceStateImpl = class { + constructor(rawTraceState) { + this._internalState = /* @__PURE__ */ new Map(); + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return this._keys().reduce((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER2 + this.get(key)); + return agg; + }, []).join(LIST_MEMBERS_SEPARATOR2); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN2) + return; + this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR2).reverse().reduce((agg, part) => { + const listMember = part.trim(); + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER2); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { + agg.set(key, value); + } else { + } + } + return agg; + }, /* @__PURE__ */ new Map()); + if (this._internalState.size > MAX_TRACE_STATE_ITEMS2) { + this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS2)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl(); + traceState._internalState = new Map(this._internalState); + return traceState; + } + }; + exports.TraceStateImpl = TraceStateImpl; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js +var require_utils2 = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createTraceState = void 0; + var tracestate_impl_1 = require_tracestate_impl(); + function createTraceState(rawTraceState) { + return new tracestate_impl_1.TraceStateImpl(rawTraceState); + } + exports.createTraceState = createTraceState; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/context-api.js +var require_context_api = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/context-api.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.context = void 0; + var context_1 = require_context2(); + exports.context = context_1.ContextAPI.getInstance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag-api.js +var require_diag_api = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/diag-api.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.diag = void 0; + var diag_1 = require_diag(); + exports.diag = diag_1.DiagAPI.instance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js +var require_NoopMeterProvider = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; + var NoopMeter_1 = require_NoopMeter(); + var NoopMeterProvider = class { + getMeter(_name, _version, _options) { + return NoopMeter_1.NOOP_METER; + } + }; + exports.NoopMeterProvider = NoopMeterProvider; + exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/metrics.js +var require_metrics = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/metrics.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricsAPI = void 0; + var NoopMeterProvider_1 = require_NoopMeterProvider(); + var global_utils_1 = require_global_utils(); + var diag_1 = require_diag(); + var API_NAME = "metrics"; + var MetricsAPI = class { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + } + /** Get the singleton instance of the Metrics API */ + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI(); + } + return this._instance; + } + /** + * Set the current global meter provider. + * Returns true if the meter provider was successfully registered, else false. + */ + setGlobalMeterProvider(provider) { + return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); + } + /** + * Returns the global meter provider. + */ + getMeterProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; + } + /** + * Returns a meter from the global meter provider. + */ + getMeter(name, version2, options) { + return this.getMeterProvider().getMeter(name, version2, options); + } + /** Remove the global meter provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + }; + exports.MetricsAPI = MetricsAPI; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/metrics-api.js +var require_metrics_api = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/metrics-api.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.metrics = void 0; + var metrics_1 = require_metrics(); + exports.metrics = metrics_1.MetricsAPI.getInstance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js +var require_NoopTextMapPropagator = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopTextMapPropagator = void 0; + var NoopTextMapPropagator = class { + /** Noop inject function does nothing */ + inject(_context, _carrier) { + } + /** Noop extract function does nothing and returns the input context */ + extract(context7, _carrier) { + return context7; + } + fields() { + return []; + } + }; + exports.NoopTextMapPropagator = NoopTextMapPropagator; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js +var require_context_helpers = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; + var context_1 = require_context2(); + var context_2 = require_context(); + var BAGGAGE_KEY = (0, context_2.createContextKey)("OpenTelemetry Baggage Key"); + function getBaggage(context7) { + return context7.getValue(BAGGAGE_KEY) || void 0; + } + exports.getBaggage = getBaggage; + function getActiveBaggage() { + return getBaggage(context_1.ContextAPI.getInstance().active()); + } + exports.getActiveBaggage = getActiveBaggage; + function setBaggage(context7, baggage) { + return context7.setValue(BAGGAGE_KEY, baggage); + } + exports.setBaggage = setBaggage; + function deleteBaggage(context7) { + return context7.deleteValue(BAGGAGE_KEY); + } + exports.deleteBaggage = deleteBaggage; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/propagation.js +var require_propagation = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/propagation.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PropagationAPI = void 0; + var global_utils_1 = require_global_utils(); + var NoopTextMapPropagator_1 = require_NoopTextMapPropagator(); + var TextMapPropagator_1 = require_TextMapPropagator(); + var context_helpers_1 = require_context_helpers(); + var utils_1 = require_utils(); + var diag_1 = require_diag(); + var API_NAME = "propagation"; + var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); + var PropagationAPI = class { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this.createBaggage = utils_1.createBaggage; + this.getBaggage = context_helpers_1.getBaggage; + this.getActiveBaggage = context_helpers_1.getActiveBaggage; + this.setBaggage = context_helpers_1.setBaggage; + this.deleteBaggage = context_helpers_1.deleteBaggage; + } + /** Get the singleton instance of the Propagator API */ + static getInstance() { + if (!this._instance) { + this._instance = new PropagationAPI(); + } + return this._instance; + } + /** + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false + */ + setGlobalPropagator(propagator) { + return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); + } + /** + * Inject context into a carrier to be propagated inter-process + * + * @param context Context carrying tracing data to inject + * @param carrier carrier to inject context into + * @param setter Function used to set values on the carrier + */ + inject(context7, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context7, carrier, setter); + } + /** + * Extract context from a carrier + * + * @param context Context which the newly created context will inherit from + * @param carrier Carrier to extract context from + * @param getter Function used to extract keys from a carrier + */ + extract(context7, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context7, carrier, getter); + } + /** + * Return a list of all fields which may be used by the propagator. + */ + fields() { + return this._getGlobalPropagator().fields(); + } + /** Remove the global propagator */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + _getGlobalPropagator() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + } + }; + exports.PropagationAPI = PropagationAPI; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/propagation-api.js +var require_propagation_api = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/propagation-api.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.propagation = void 0; + var propagation_1 = require_propagation(); + exports.propagation = propagation_1.PropagationAPI.getInstance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/trace.js +var require_trace = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/api/trace.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceAPI = void 0; + var global_utils_1 = require_global_utils(); + var ProxyTracerProvider_1 = require_ProxyTracerProvider(); + var spancontext_utils_1 = require_spancontext_utils(); + var context_utils_1 = require_context_utils(); + var diag_1 = require_diag(); + var API_NAME = "trace"; + var TraceAPI = class { + /** Empty private constructor prevents end users from constructing a new instance of the API */ + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; + this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; + this.deleteSpan = context_utils_1.deleteSpan; + this.getSpan = context_utils_1.getSpan; + this.getActiveSpan = context_utils_1.getActiveSpan; + this.getSpanContext = context_utils_1.getSpanContext; + this.setSpan = context_utils_1.setSpan; + this.setSpanContext = context_utils_1.setSpanContext; + } + /** Get the singleton instance of the Trace API */ + static getInstance() { + if (!this._instance) { + this._instance = new TraceAPI(); + } + return this._instance; + } + /** + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false + */ + setGlobalTracerProvider(provider) { + const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; + } + /** + * Returns the global tracer provider. + */ + getTracerProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; + } + /** + * Returns a tracer from the global tracer provider. + */ + getTracer(name, version2) { + return this.getTracerProvider().getTracer(name, version2); + } + /** Remove the global tracer provider */ + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + } + }; + exports.TraceAPI = TraceAPI; + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace-api.js +var require_trace_api = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/trace-api.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.trace = void 0; + var trace_1 = require_trace(); + exports.trace = trace_1.TraceAPI.getInstance(); + } +}); + +// node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/index.js +var require_src = __commonJS({ + "node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/src/index.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; + var utils_1 = require_utils(); + Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function() { + return utils_1.baggageEntryMetadataFromString; + } }); + var context_1 = require_context(); + Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function() { + return context_1.createContextKey; + } }); + Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function() { + return context_1.ROOT_CONTEXT; + } }); + var consoleLogger_1 = require_consoleLogger(); + Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function() { + return consoleLogger_1.DiagConsoleLogger; + } }); + var types_1 = require_types(); + Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function() { + return types_1.DiagLogLevel; + } }); + var NoopMeter_1 = require_NoopMeter(); + Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function() { + return NoopMeter_1.createNoopMeter; + } }); + var Metric_1 = require_Metric(); + Object.defineProperty(exports, "ValueType", { enumerable: true, get: function() { + return Metric_1.ValueType; + } }); + var TextMapPropagator_1 = require_TextMapPropagator(); + Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function() { + return TextMapPropagator_1.defaultTextMapGetter; + } }); + Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function() { + return TextMapPropagator_1.defaultTextMapSetter; + } }); + var ProxyTracer_1 = require_ProxyTracer(); + Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function() { + return ProxyTracer_1.ProxyTracer; + } }); + var ProxyTracerProvider_1 = require_ProxyTracerProvider(); + Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function() { + return ProxyTracerProvider_1.ProxyTracerProvider; + } }); + var SamplingResult_1 = require_SamplingResult(); + Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function() { + return SamplingResult_1.SamplingDecision; + } }); + var span_kind_1 = require_span_kind(); + Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function() { + return span_kind_1.SpanKind; + } }); + var status_1 = require_status(); + Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function() { + return status_1.SpanStatusCode; + } }); + var trace_flags_1 = require_trace_flags(); + Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function() { + return trace_flags_1.TraceFlags; + } }); + var utils_2 = require_utils2(); + Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function() { + return utils_2.createTraceState; + } }); + var spancontext_utils_1 = require_spancontext_utils(); + Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function() { + return spancontext_utils_1.isSpanContextValid; + } }); + Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function() { + return spancontext_utils_1.isValidTraceId; + } }); + Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function() { + return spancontext_utils_1.isValidSpanId; + } }); + var invalid_span_constants_1 = require_invalid_span_constants(); + Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function() { + return invalid_span_constants_1.INVALID_SPANID; + } }); + Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function() { + return invalid_span_constants_1.INVALID_TRACEID; + } }); + Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function() { + return invalid_span_constants_1.INVALID_SPAN_CONTEXT; + } }); + var context_api_1 = require_context_api(); + Object.defineProperty(exports, "context", { enumerable: true, get: function() { + return context_api_1.context; + } }); + var diag_api_1 = require_diag_api(); + Object.defineProperty(exports, "diag", { enumerable: true, get: function() { + return diag_api_1.diag; + } }); + var metrics_api_1 = require_metrics_api(); + Object.defineProperty(exports, "metrics", { enumerable: true, get: function() { + return metrics_api_1.metrics; + } }); + var propagation_api_1 = require_propagation_api(); + Object.defineProperty(exports, "propagation", { enumerable: true, get: function() { + return propagation_api_1.propagation; + } }); + var trace_api_1 = require_trace_api(); + Object.defineProperty(exports, "trace", { enumerable: true, get: function() { + return trace_api_1.trace; + } }); + exports.default = { + context: context_api_1.context, + diag: diag_api_1.diag, + metrics: metrics_api_1.metrics, + propagation: propagation_api_1.propagation, + trace: trace_api_1.trace + }; + } +}); + +// node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js +var require_utils3 = __commonJS({ + "node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createConstMap = void 0; + function createConstMap(values2) { + let res = {}; + const len = values2.length; + for (let lp = 0; lp < len; lp++) { + const val = values2[lp]; + if (val) { + res[String(val).toUpperCase().replace(/[-.]/g, "_")] = val; + } + } + return res; + } + exports.createConstMap = createConstMap; + } +}); + +// node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js +var require_SemanticAttributes = __commonJS({ + "node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SEMATTRS_NET_HOST_CARRIER_ICC = exports.SEMATTRS_NET_HOST_CARRIER_MNC = exports.SEMATTRS_NET_HOST_CARRIER_MCC = exports.SEMATTRS_NET_HOST_CARRIER_NAME = exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = exports.SEMATTRS_NET_HOST_NAME = exports.SEMATTRS_NET_HOST_PORT = exports.SEMATTRS_NET_HOST_IP = exports.SEMATTRS_NET_PEER_NAME = exports.SEMATTRS_NET_PEER_PORT = exports.SEMATTRS_NET_PEER_IP = exports.SEMATTRS_NET_TRANSPORT = exports.SEMATTRS_FAAS_INVOKED_REGION = exports.SEMATTRS_FAAS_INVOKED_PROVIDER = exports.SEMATTRS_FAAS_INVOKED_NAME = exports.SEMATTRS_FAAS_COLDSTART = exports.SEMATTRS_FAAS_CRON = exports.SEMATTRS_FAAS_TIME = exports.SEMATTRS_FAAS_DOCUMENT_NAME = exports.SEMATTRS_FAAS_DOCUMENT_TIME = exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = exports.SEMATTRS_FAAS_EXECUTION = exports.SEMATTRS_FAAS_TRIGGER = exports.SEMATTRS_EXCEPTION_ESCAPED = exports.SEMATTRS_EXCEPTION_STACKTRACE = exports.SEMATTRS_EXCEPTION_MESSAGE = exports.SEMATTRS_EXCEPTION_TYPE = exports.SEMATTRS_DB_SQL_TABLE = exports.SEMATTRS_DB_MONGODB_COLLECTION = exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = exports.SEMATTRS_DB_HBASE_NAMESPACE = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = exports.SEMATTRS_DB_CASSANDRA_TABLE = exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = exports.SEMATTRS_DB_OPERATION = exports.SEMATTRS_DB_STATEMENT = exports.SEMATTRS_DB_NAME = exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = exports.SEMATTRS_DB_USER = exports.SEMATTRS_DB_CONNECTION_STRING = exports.SEMATTRS_DB_SYSTEM = exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = void 0; + exports.SEMATTRS_MESSAGING_DESTINATION_KIND = exports.SEMATTRS_MESSAGING_DESTINATION = exports.SEMATTRS_MESSAGING_SYSTEM = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = exports.SEMATTRS_AWS_DYNAMODB_COUNT = exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_SELECT = exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = exports.SEMATTRS_AWS_DYNAMODB_LIMIT = exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = exports.SEMATTRS_HTTP_CLIENT_IP = exports.SEMATTRS_HTTP_ROUTE = exports.SEMATTRS_HTTP_SERVER_NAME = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = exports.SEMATTRS_HTTP_USER_AGENT = exports.SEMATTRS_HTTP_FLAVOR = exports.SEMATTRS_HTTP_STATUS_CODE = exports.SEMATTRS_HTTP_SCHEME = exports.SEMATTRS_HTTP_HOST = exports.SEMATTRS_HTTP_TARGET = exports.SEMATTRS_HTTP_URL = exports.SEMATTRS_HTTP_METHOD = exports.SEMATTRS_CODE_LINENO = exports.SEMATTRS_CODE_FILEPATH = exports.SEMATTRS_CODE_NAMESPACE = exports.SEMATTRS_CODE_FUNCTION = exports.SEMATTRS_THREAD_NAME = exports.SEMATTRS_THREAD_ID = exports.SEMATTRS_ENDUSER_SCOPE = exports.SEMATTRS_ENDUSER_ROLE = exports.SEMATTRS_ENDUSER_ID = exports.SEMATTRS_PEER_SERVICE = void 0; + exports.DBSYSTEMVALUES_FILEMAKER = exports.DBSYSTEMVALUES_DERBY = exports.DBSYSTEMVALUES_FIREBIRD = exports.DBSYSTEMVALUES_ADABAS = exports.DBSYSTEMVALUES_CACHE = exports.DBSYSTEMVALUES_EDB = exports.DBSYSTEMVALUES_FIRSTSQL = exports.DBSYSTEMVALUES_INGRES = exports.DBSYSTEMVALUES_HANADB = exports.DBSYSTEMVALUES_MAXDB = exports.DBSYSTEMVALUES_PROGRESS = exports.DBSYSTEMVALUES_HSQLDB = exports.DBSYSTEMVALUES_CLOUDSCAPE = exports.DBSYSTEMVALUES_HIVE = exports.DBSYSTEMVALUES_REDSHIFT = exports.DBSYSTEMVALUES_POSTGRESQL = exports.DBSYSTEMVALUES_DB2 = exports.DBSYSTEMVALUES_ORACLE = exports.DBSYSTEMVALUES_MYSQL = exports.DBSYSTEMVALUES_MSSQL = exports.DBSYSTEMVALUES_OTHER_SQL = exports.SemanticAttributes = exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_ID = exports.SEMATTRS_MESSAGE_TYPE = exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = exports.SEMATTRS_RPC_JSONRPC_VERSION = exports.SEMATTRS_RPC_GRPC_STATUS_CODE = exports.SEMATTRS_RPC_METHOD = exports.SEMATTRS_RPC_SERVICE = exports.SEMATTRS_RPC_SYSTEM = exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = exports.SEMATTRS_MESSAGING_CONSUMER_ID = exports.SEMATTRS_MESSAGING_OPERATION = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = exports.SEMATTRS_MESSAGING_CONVERSATION_ID = exports.SEMATTRS_MESSAGING_MESSAGE_ID = exports.SEMATTRS_MESSAGING_URL = exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = exports.SEMATTRS_MESSAGING_PROTOCOL = exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = void 0; + exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = exports.FaasDocumentOperationValues = exports.FAASDOCUMENTOPERATIONVALUES_DELETE = exports.FAASDOCUMENTOPERATIONVALUES_EDIT = exports.FAASDOCUMENTOPERATIONVALUES_INSERT = exports.FaasTriggerValues = exports.FAASTRIGGERVALUES_OTHER = exports.FAASTRIGGERVALUES_TIMER = exports.FAASTRIGGERVALUES_PUBSUB = exports.FAASTRIGGERVALUES_HTTP = exports.FAASTRIGGERVALUES_DATASOURCE = exports.DbCassandraConsistencyLevelValues = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = exports.DbSystemValues = exports.DBSYSTEMVALUES_COCKROACHDB = exports.DBSYSTEMVALUES_MEMCACHED = exports.DBSYSTEMVALUES_ELASTICSEARCH = exports.DBSYSTEMVALUES_GEODE = exports.DBSYSTEMVALUES_NEO4J = exports.DBSYSTEMVALUES_DYNAMODB = exports.DBSYSTEMVALUES_COSMOSDB = exports.DBSYSTEMVALUES_COUCHDB = exports.DBSYSTEMVALUES_COUCHBASE = exports.DBSYSTEMVALUES_REDIS = exports.DBSYSTEMVALUES_MONGODB = exports.DBSYSTEMVALUES_HBASE = exports.DBSYSTEMVALUES_CASSANDRA = exports.DBSYSTEMVALUES_COLDFUSION = exports.DBSYSTEMVALUES_H2 = exports.DBSYSTEMVALUES_VERTICA = exports.DBSYSTEMVALUES_TERADATA = exports.DBSYSTEMVALUES_SYBASE = exports.DBSYSTEMVALUES_SQLITE = exports.DBSYSTEMVALUES_POINTBASE = exports.DBSYSTEMVALUES_PERVASIVE = exports.DBSYSTEMVALUES_NETEZZA = exports.DBSYSTEMVALUES_MARIADB = exports.DBSYSTEMVALUES_INTERBASE = exports.DBSYSTEMVALUES_INSTANTDB = exports.DBSYSTEMVALUES_INFORMIX = void 0; + exports.MESSAGINGOPERATIONVALUES_RECEIVE = exports.MessagingDestinationKindValues = exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = exports.HttpFlavorValues = exports.HTTPFLAVORVALUES_QUIC = exports.HTTPFLAVORVALUES_SPDY = exports.HTTPFLAVORVALUES_HTTP_2_0 = exports.HTTPFLAVORVALUES_HTTP_1_1 = exports.HTTPFLAVORVALUES_HTTP_1_0 = exports.NetHostConnectionSubtypeValues = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = exports.NetHostConnectionTypeValues = exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = exports.NETHOSTCONNECTIONTYPEVALUES_CELL = exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = exports.NetTransportValues = exports.NETTRANSPORTVALUES_OTHER = exports.NETTRANSPORTVALUES_INPROC = exports.NETTRANSPORTVALUES_PIPE = exports.NETTRANSPORTVALUES_UNIX = exports.NETTRANSPORTVALUES_IP = exports.NETTRANSPORTVALUES_IP_UDP = exports.NETTRANSPORTVALUES_IP_TCP = exports.FaasInvokedProviderValues = exports.FAASINVOKEDPROVIDERVALUES_GCP = exports.FAASINVOKEDPROVIDERVALUES_AZURE = exports.FAASINVOKEDPROVIDERVALUES_AWS = void 0; + exports.MessageTypeValues = exports.MESSAGETYPEVALUES_RECEIVED = exports.MESSAGETYPEVALUES_SENT = exports.RpcGrpcStatusCodeValues = exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = exports.RPCGRPCSTATUSCODEVALUES_ABORTED = exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = exports.RPCGRPCSTATUSCODEVALUES_OK = exports.MessagingOperationValues = exports.MESSAGINGOPERATIONVALUES_PROCESS = void 0; + var utils_1 = require_utils3(); + var TMP_AWS_LAMBDA_INVOKED_ARN = "aws.lambda.invoked_arn"; + var TMP_DB_SYSTEM = "db.system"; + var TMP_DB_CONNECTION_STRING = "db.connection_string"; + var TMP_DB_USER = "db.user"; + var TMP_DB_JDBC_DRIVER_CLASSNAME = "db.jdbc.driver_classname"; + var TMP_DB_NAME = "db.name"; + var TMP_DB_STATEMENT = "db.statement"; + var TMP_DB_OPERATION = "db.operation"; + var TMP_DB_MSSQL_INSTANCE_NAME = "db.mssql.instance_name"; + var TMP_DB_CASSANDRA_KEYSPACE = "db.cassandra.keyspace"; + var TMP_DB_CASSANDRA_PAGE_SIZE = "db.cassandra.page_size"; + var TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = "db.cassandra.consistency_level"; + var TMP_DB_CASSANDRA_TABLE = "db.cassandra.table"; + var TMP_DB_CASSANDRA_IDEMPOTENCE = "db.cassandra.idempotence"; + var TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = "db.cassandra.speculative_execution_count"; + var TMP_DB_CASSANDRA_COORDINATOR_ID = "db.cassandra.coordinator.id"; + var TMP_DB_CASSANDRA_COORDINATOR_DC = "db.cassandra.coordinator.dc"; + var TMP_DB_HBASE_NAMESPACE = "db.hbase.namespace"; + var TMP_DB_REDIS_DATABASE_INDEX = "db.redis.database_index"; + var TMP_DB_MONGODB_COLLECTION = "db.mongodb.collection"; + var TMP_DB_SQL_TABLE = "db.sql.table"; + var TMP_EXCEPTION_TYPE = "exception.type"; + var TMP_EXCEPTION_MESSAGE = "exception.message"; + var TMP_EXCEPTION_STACKTRACE = "exception.stacktrace"; + var TMP_EXCEPTION_ESCAPED = "exception.escaped"; + var TMP_FAAS_TRIGGER = "faas.trigger"; + var TMP_FAAS_EXECUTION = "faas.execution"; + var TMP_FAAS_DOCUMENT_COLLECTION = "faas.document.collection"; + var TMP_FAAS_DOCUMENT_OPERATION = "faas.document.operation"; + var TMP_FAAS_DOCUMENT_TIME = "faas.document.time"; + var TMP_FAAS_DOCUMENT_NAME = "faas.document.name"; + var TMP_FAAS_TIME = "faas.time"; + var TMP_FAAS_CRON = "faas.cron"; + var TMP_FAAS_COLDSTART = "faas.coldstart"; + var TMP_FAAS_INVOKED_NAME = "faas.invoked_name"; + var TMP_FAAS_INVOKED_PROVIDER = "faas.invoked_provider"; + var TMP_FAAS_INVOKED_REGION = "faas.invoked_region"; + var TMP_NET_TRANSPORT = "net.transport"; + var TMP_NET_PEER_IP = "net.peer.ip"; + var TMP_NET_PEER_PORT = "net.peer.port"; + var TMP_NET_PEER_NAME = "net.peer.name"; + var TMP_NET_HOST_IP = "net.host.ip"; + var TMP_NET_HOST_PORT = "net.host.port"; + var TMP_NET_HOST_NAME = "net.host.name"; + var TMP_NET_HOST_CONNECTION_TYPE = "net.host.connection.type"; + var TMP_NET_HOST_CONNECTION_SUBTYPE = "net.host.connection.subtype"; + var TMP_NET_HOST_CARRIER_NAME = "net.host.carrier.name"; + var TMP_NET_HOST_CARRIER_MCC = "net.host.carrier.mcc"; + var TMP_NET_HOST_CARRIER_MNC = "net.host.carrier.mnc"; + var TMP_NET_HOST_CARRIER_ICC = "net.host.carrier.icc"; + var TMP_PEER_SERVICE = "peer.service"; + var TMP_ENDUSER_ID = "enduser.id"; + var TMP_ENDUSER_ROLE = "enduser.role"; + var TMP_ENDUSER_SCOPE = "enduser.scope"; + var TMP_THREAD_ID = "thread.id"; + var TMP_THREAD_NAME = "thread.name"; + var TMP_CODE_FUNCTION = "code.function"; + var TMP_CODE_NAMESPACE = "code.namespace"; + var TMP_CODE_FILEPATH = "code.filepath"; + var TMP_CODE_LINENO = "code.lineno"; + var TMP_HTTP_METHOD = "http.method"; + var TMP_HTTP_URL = "http.url"; + var TMP_HTTP_TARGET = "http.target"; + var TMP_HTTP_HOST = "http.host"; + var TMP_HTTP_SCHEME = "http.scheme"; + var TMP_HTTP_STATUS_CODE = "http.status_code"; + var TMP_HTTP_FLAVOR = "http.flavor"; + var TMP_HTTP_USER_AGENT = "http.user_agent"; + var TMP_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length"; + var TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed"; + var TMP_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length"; + var TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed"; + var TMP_HTTP_SERVER_NAME = "http.server_name"; + var TMP_HTTP_ROUTE = "http.route"; + var TMP_HTTP_CLIENT_IP = "http.client_ip"; + var TMP_AWS_DYNAMODB_TABLE_NAMES = "aws.dynamodb.table_names"; + var TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = "aws.dynamodb.consumed_capacity"; + var TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = "aws.dynamodb.item_collection_metrics"; + var TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = "aws.dynamodb.provisioned_read_capacity"; + var TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = "aws.dynamodb.provisioned_write_capacity"; + var TMP_AWS_DYNAMODB_CONSISTENT_READ = "aws.dynamodb.consistent_read"; + var TMP_AWS_DYNAMODB_PROJECTION = "aws.dynamodb.projection"; + var TMP_AWS_DYNAMODB_LIMIT = "aws.dynamodb.limit"; + var TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = "aws.dynamodb.attributes_to_get"; + var TMP_AWS_DYNAMODB_INDEX_NAME = "aws.dynamodb.index_name"; + var TMP_AWS_DYNAMODB_SELECT = "aws.dynamodb.select"; + var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = "aws.dynamodb.global_secondary_indexes"; + var TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = "aws.dynamodb.local_secondary_indexes"; + var TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = "aws.dynamodb.exclusive_start_table"; + var TMP_AWS_DYNAMODB_TABLE_COUNT = "aws.dynamodb.table_count"; + var TMP_AWS_DYNAMODB_SCAN_FORWARD = "aws.dynamodb.scan_forward"; + var TMP_AWS_DYNAMODB_SEGMENT = "aws.dynamodb.segment"; + var TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = "aws.dynamodb.total_segments"; + var TMP_AWS_DYNAMODB_COUNT = "aws.dynamodb.count"; + var TMP_AWS_DYNAMODB_SCANNED_COUNT = "aws.dynamodb.scanned_count"; + var TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = "aws.dynamodb.attribute_definitions"; + var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = "aws.dynamodb.global_secondary_index_updates"; + var TMP_MESSAGING_SYSTEM = "messaging.system"; + var TMP_MESSAGING_DESTINATION = "messaging.destination"; + var TMP_MESSAGING_DESTINATION_KIND = "messaging.destination_kind"; + var TMP_MESSAGING_TEMP_DESTINATION = "messaging.temp_destination"; + var TMP_MESSAGING_PROTOCOL = "messaging.protocol"; + var TMP_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version"; + var TMP_MESSAGING_URL = "messaging.url"; + var TMP_MESSAGING_MESSAGE_ID = "messaging.message_id"; + var TMP_MESSAGING_CONVERSATION_ID = "messaging.conversation_id"; + var TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = "messaging.message_payload_size_bytes"; + var TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = "messaging.message_payload_compressed_size_bytes"; + var TMP_MESSAGING_OPERATION = "messaging.operation"; + var TMP_MESSAGING_CONSUMER_ID = "messaging.consumer_id"; + var TMP_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key"; + var TMP_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message_key"; + var TMP_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer_group"; + var TMP_MESSAGING_KAFKA_CLIENT_ID = "messaging.kafka.client_id"; + var TMP_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition"; + var TMP_MESSAGING_KAFKA_TOMBSTONE = "messaging.kafka.tombstone"; + var TMP_RPC_SYSTEM = "rpc.system"; + var TMP_RPC_SERVICE = "rpc.service"; + var TMP_RPC_METHOD = "rpc.method"; + var TMP_RPC_GRPC_STATUS_CODE = "rpc.grpc.status_code"; + var TMP_RPC_JSONRPC_VERSION = "rpc.jsonrpc.version"; + var TMP_RPC_JSONRPC_REQUEST_ID = "rpc.jsonrpc.request_id"; + var TMP_RPC_JSONRPC_ERROR_CODE = "rpc.jsonrpc.error_code"; + var TMP_RPC_JSONRPC_ERROR_MESSAGE = "rpc.jsonrpc.error_message"; + var TMP_MESSAGE_TYPE = "message.type"; + var TMP_MESSAGE_ID = "message.id"; + var TMP_MESSAGE_COMPRESSED_SIZE = "message.compressed_size"; + var TMP_MESSAGE_UNCOMPRESSED_SIZE = "message.uncompressed_size"; + exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; + exports.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; + exports.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; + exports.SEMATTRS_DB_USER = TMP_DB_USER; + exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; + exports.SEMATTRS_DB_NAME = TMP_DB_NAME; + exports.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; + exports.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; + exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; + exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; + exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; + exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; + exports.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; + exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; + exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; + exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; + exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; + exports.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; + exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; + exports.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; + exports.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; + exports.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; + exports.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; + exports.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; + exports.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; + exports.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; + exports.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; + exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; + exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; + exports.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; + exports.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; + exports.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; + exports.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; + exports.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; + exports.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; + exports.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; + exports.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; + exports.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; + exports.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; + exports.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; + exports.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; + exports.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; + exports.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; + exports.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; + exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; + exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; + exports.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; + exports.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; + exports.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; + exports.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; + exports.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; + exports.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; + exports.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; + exports.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; + exports.SEMATTRS_THREAD_ID = TMP_THREAD_ID; + exports.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; + exports.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; + exports.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; + exports.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; + exports.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; + exports.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; + exports.SEMATTRS_HTTP_URL = TMP_HTTP_URL; + exports.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; + exports.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; + exports.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; + exports.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; + exports.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; + exports.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; + exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; + exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; + exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; + exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; + exports.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; + exports.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; + exports.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; + exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; + exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; + exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; + exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; + exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; + exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; + exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; + exports.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; + exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; + exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; + exports.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; + exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; + exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; + exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; + exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; + exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; + exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; + exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; + exports.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; + exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; + exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; + exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; + exports.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; + exports.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; + exports.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; + exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; + exports.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; + exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; + exports.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; + exports.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; + exports.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; + exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; + exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; + exports.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; + exports.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; + exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; + exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; + exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; + exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; + exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; + exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; + exports.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; + exports.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; + exports.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; + exports.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; + exports.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; + exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; + exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; + exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; + exports.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; + exports.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; + exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; + exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; + exports.SemanticAttributes = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_AWS_LAMBDA_INVOKED_ARN, + TMP_DB_SYSTEM, + TMP_DB_CONNECTION_STRING, + TMP_DB_USER, + TMP_DB_JDBC_DRIVER_CLASSNAME, + TMP_DB_NAME, + TMP_DB_STATEMENT, + TMP_DB_OPERATION, + TMP_DB_MSSQL_INSTANCE_NAME, + TMP_DB_CASSANDRA_KEYSPACE, + TMP_DB_CASSANDRA_PAGE_SIZE, + TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, + TMP_DB_CASSANDRA_TABLE, + TMP_DB_CASSANDRA_IDEMPOTENCE, + TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, + TMP_DB_CASSANDRA_COORDINATOR_ID, + TMP_DB_CASSANDRA_COORDINATOR_DC, + TMP_DB_HBASE_NAMESPACE, + TMP_DB_REDIS_DATABASE_INDEX, + TMP_DB_MONGODB_COLLECTION, + TMP_DB_SQL_TABLE, + TMP_EXCEPTION_TYPE, + TMP_EXCEPTION_MESSAGE, + TMP_EXCEPTION_STACKTRACE, + TMP_EXCEPTION_ESCAPED, + TMP_FAAS_TRIGGER, + TMP_FAAS_EXECUTION, + TMP_FAAS_DOCUMENT_COLLECTION, + TMP_FAAS_DOCUMENT_OPERATION, + TMP_FAAS_DOCUMENT_TIME, + TMP_FAAS_DOCUMENT_NAME, + TMP_FAAS_TIME, + TMP_FAAS_CRON, + TMP_FAAS_COLDSTART, + TMP_FAAS_INVOKED_NAME, + TMP_FAAS_INVOKED_PROVIDER, + TMP_FAAS_INVOKED_REGION, + TMP_NET_TRANSPORT, + TMP_NET_PEER_IP, + TMP_NET_PEER_PORT, + TMP_NET_PEER_NAME, + TMP_NET_HOST_IP, + TMP_NET_HOST_PORT, + TMP_NET_HOST_NAME, + TMP_NET_HOST_CONNECTION_TYPE, + TMP_NET_HOST_CONNECTION_SUBTYPE, + TMP_NET_HOST_CARRIER_NAME, + TMP_NET_HOST_CARRIER_MCC, + TMP_NET_HOST_CARRIER_MNC, + TMP_NET_HOST_CARRIER_ICC, + TMP_PEER_SERVICE, + TMP_ENDUSER_ID, + TMP_ENDUSER_ROLE, + TMP_ENDUSER_SCOPE, + TMP_THREAD_ID, + TMP_THREAD_NAME, + TMP_CODE_FUNCTION, + TMP_CODE_NAMESPACE, + TMP_CODE_FILEPATH, + TMP_CODE_LINENO, + TMP_HTTP_METHOD, + TMP_HTTP_URL, + TMP_HTTP_TARGET, + TMP_HTTP_HOST, + TMP_HTTP_SCHEME, + TMP_HTTP_STATUS_CODE, + TMP_HTTP_FLAVOR, + TMP_HTTP_USER_AGENT, + TMP_HTTP_REQUEST_CONTENT_LENGTH, + TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_RESPONSE_CONTENT_LENGTH, + TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_SERVER_NAME, + TMP_HTTP_ROUTE, + TMP_HTTP_CLIENT_IP, + TMP_AWS_DYNAMODB_TABLE_NAMES, + TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, + TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, + TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, + TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, + TMP_AWS_DYNAMODB_CONSISTENT_READ, + TMP_AWS_DYNAMODB_PROJECTION, + TMP_AWS_DYNAMODB_LIMIT, + TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, + TMP_AWS_DYNAMODB_INDEX_NAME, + TMP_AWS_DYNAMODB_SELECT, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, + TMP_AWS_DYNAMODB_TABLE_COUNT, + TMP_AWS_DYNAMODB_SCAN_FORWARD, + TMP_AWS_DYNAMODB_SEGMENT, + TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, + TMP_AWS_DYNAMODB_COUNT, + TMP_AWS_DYNAMODB_SCANNED_COUNT, + TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, + TMP_MESSAGING_SYSTEM, + TMP_MESSAGING_DESTINATION, + TMP_MESSAGING_DESTINATION_KIND, + TMP_MESSAGING_TEMP_DESTINATION, + TMP_MESSAGING_PROTOCOL, + TMP_MESSAGING_PROTOCOL_VERSION, + TMP_MESSAGING_URL, + TMP_MESSAGING_MESSAGE_ID, + TMP_MESSAGING_CONVERSATION_ID, + TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, + TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, + TMP_MESSAGING_OPERATION, + TMP_MESSAGING_CONSUMER_ID, + TMP_MESSAGING_RABBITMQ_ROUTING_KEY, + TMP_MESSAGING_KAFKA_MESSAGE_KEY, + TMP_MESSAGING_KAFKA_CONSUMER_GROUP, + TMP_MESSAGING_KAFKA_CLIENT_ID, + TMP_MESSAGING_KAFKA_PARTITION, + TMP_MESSAGING_KAFKA_TOMBSTONE, + TMP_RPC_SYSTEM, + TMP_RPC_SERVICE, + TMP_RPC_METHOD, + TMP_RPC_GRPC_STATUS_CODE, + TMP_RPC_JSONRPC_VERSION, + TMP_RPC_JSONRPC_REQUEST_ID, + TMP_RPC_JSONRPC_ERROR_CODE, + TMP_RPC_JSONRPC_ERROR_MESSAGE, + TMP_MESSAGE_TYPE, + TMP_MESSAGE_ID, + TMP_MESSAGE_COMPRESSED_SIZE, + TMP_MESSAGE_UNCOMPRESSED_SIZE + ]); + var TMP_DBSYSTEMVALUES_OTHER_SQL = "other_sql"; + var TMP_DBSYSTEMVALUES_MSSQL = "mssql"; + var TMP_DBSYSTEMVALUES_MYSQL = "mysql"; + var TMP_DBSYSTEMVALUES_ORACLE = "oracle"; + var TMP_DBSYSTEMVALUES_DB2 = "db2"; + var TMP_DBSYSTEMVALUES_POSTGRESQL = "postgresql"; + var TMP_DBSYSTEMVALUES_REDSHIFT = "redshift"; + var TMP_DBSYSTEMVALUES_HIVE = "hive"; + var TMP_DBSYSTEMVALUES_CLOUDSCAPE = "cloudscape"; + var TMP_DBSYSTEMVALUES_HSQLDB = "hsqldb"; + var TMP_DBSYSTEMVALUES_PROGRESS = "progress"; + var TMP_DBSYSTEMVALUES_MAXDB = "maxdb"; + var TMP_DBSYSTEMVALUES_HANADB = "hanadb"; + var TMP_DBSYSTEMVALUES_INGRES = "ingres"; + var TMP_DBSYSTEMVALUES_FIRSTSQL = "firstsql"; + var TMP_DBSYSTEMVALUES_EDB = "edb"; + var TMP_DBSYSTEMVALUES_CACHE = "cache"; + var TMP_DBSYSTEMVALUES_ADABAS = "adabas"; + var TMP_DBSYSTEMVALUES_FIREBIRD = "firebird"; + var TMP_DBSYSTEMVALUES_DERBY = "derby"; + var TMP_DBSYSTEMVALUES_FILEMAKER = "filemaker"; + var TMP_DBSYSTEMVALUES_INFORMIX = "informix"; + var TMP_DBSYSTEMVALUES_INSTANTDB = "instantdb"; + var TMP_DBSYSTEMVALUES_INTERBASE = "interbase"; + var TMP_DBSYSTEMVALUES_MARIADB = "mariadb"; + var TMP_DBSYSTEMVALUES_NETEZZA = "netezza"; + var TMP_DBSYSTEMVALUES_PERVASIVE = "pervasive"; + var TMP_DBSYSTEMVALUES_POINTBASE = "pointbase"; + var TMP_DBSYSTEMVALUES_SQLITE = "sqlite"; + var TMP_DBSYSTEMVALUES_SYBASE = "sybase"; + var TMP_DBSYSTEMVALUES_TERADATA = "teradata"; + var TMP_DBSYSTEMVALUES_VERTICA = "vertica"; + var TMP_DBSYSTEMVALUES_H2 = "h2"; + var TMP_DBSYSTEMVALUES_COLDFUSION = "coldfusion"; + var TMP_DBSYSTEMVALUES_CASSANDRA = "cassandra"; + var TMP_DBSYSTEMVALUES_HBASE = "hbase"; + var TMP_DBSYSTEMVALUES_MONGODB = "mongodb"; + var TMP_DBSYSTEMVALUES_REDIS = "redis"; + var TMP_DBSYSTEMVALUES_COUCHBASE = "couchbase"; + var TMP_DBSYSTEMVALUES_COUCHDB = "couchdb"; + var TMP_DBSYSTEMVALUES_COSMOSDB = "cosmosdb"; + var TMP_DBSYSTEMVALUES_DYNAMODB = "dynamodb"; + var TMP_DBSYSTEMVALUES_NEO4J = "neo4j"; + var TMP_DBSYSTEMVALUES_GEODE = "geode"; + var TMP_DBSYSTEMVALUES_ELASTICSEARCH = "elasticsearch"; + var TMP_DBSYSTEMVALUES_MEMCACHED = "memcached"; + var TMP_DBSYSTEMVALUES_COCKROACHDB = "cockroachdb"; + exports.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; + exports.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; + exports.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; + exports.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; + exports.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; + exports.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; + exports.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; + exports.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; + exports.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; + exports.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; + exports.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; + exports.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; + exports.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; + exports.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; + exports.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; + exports.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; + exports.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; + exports.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; + exports.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; + exports.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; + exports.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; + exports.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; + exports.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; + exports.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; + exports.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; + exports.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; + exports.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; + exports.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; + exports.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; + exports.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; + exports.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; + exports.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; + exports.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; + exports.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; + exports.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; + exports.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; + exports.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; + exports.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; + exports.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; + exports.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; + exports.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; + exports.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; + exports.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; + exports.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; + exports.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; + exports.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; + exports.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; + exports.DbSystemValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_DBSYSTEMVALUES_OTHER_SQL, + TMP_DBSYSTEMVALUES_MSSQL, + TMP_DBSYSTEMVALUES_MYSQL, + TMP_DBSYSTEMVALUES_ORACLE, + TMP_DBSYSTEMVALUES_DB2, + TMP_DBSYSTEMVALUES_POSTGRESQL, + TMP_DBSYSTEMVALUES_REDSHIFT, + TMP_DBSYSTEMVALUES_HIVE, + TMP_DBSYSTEMVALUES_CLOUDSCAPE, + TMP_DBSYSTEMVALUES_HSQLDB, + TMP_DBSYSTEMVALUES_PROGRESS, + TMP_DBSYSTEMVALUES_MAXDB, + TMP_DBSYSTEMVALUES_HANADB, + TMP_DBSYSTEMVALUES_INGRES, + TMP_DBSYSTEMVALUES_FIRSTSQL, + TMP_DBSYSTEMVALUES_EDB, + TMP_DBSYSTEMVALUES_CACHE, + TMP_DBSYSTEMVALUES_ADABAS, + TMP_DBSYSTEMVALUES_FIREBIRD, + TMP_DBSYSTEMVALUES_DERBY, + TMP_DBSYSTEMVALUES_FILEMAKER, + TMP_DBSYSTEMVALUES_INFORMIX, + TMP_DBSYSTEMVALUES_INSTANTDB, + TMP_DBSYSTEMVALUES_INTERBASE, + TMP_DBSYSTEMVALUES_MARIADB, + TMP_DBSYSTEMVALUES_NETEZZA, + TMP_DBSYSTEMVALUES_PERVASIVE, + TMP_DBSYSTEMVALUES_POINTBASE, + TMP_DBSYSTEMVALUES_SQLITE, + TMP_DBSYSTEMVALUES_SYBASE, + TMP_DBSYSTEMVALUES_TERADATA, + TMP_DBSYSTEMVALUES_VERTICA, + TMP_DBSYSTEMVALUES_H2, + TMP_DBSYSTEMVALUES_COLDFUSION, + TMP_DBSYSTEMVALUES_CASSANDRA, + TMP_DBSYSTEMVALUES_HBASE, + TMP_DBSYSTEMVALUES_MONGODB, + TMP_DBSYSTEMVALUES_REDIS, + TMP_DBSYSTEMVALUES_COUCHBASE, + TMP_DBSYSTEMVALUES_COUCHDB, + TMP_DBSYSTEMVALUES_COSMOSDB, + TMP_DBSYSTEMVALUES_DYNAMODB, + TMP_DBSYSTEMVALUES_NEO4J, + TMP_DBSYSTEMVALUES_GEODE, + TMP_DBSYSTEMVALUES_ELASTICSEARCH, + TMP_DBSYSTEMVALUES_MEMCACHED, + TMP_DBSYSTEMVALUES_COCKROACHDB + ]); + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = "all"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = "each_quorum"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = "quorum"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = "local_quorum"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = "one"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = "two"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = "three"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = "local_one"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = "any"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = "serial"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = "local_serial"; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; + exports.DbCassandraConsistencyLevelValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL + ]); + var TMP_FAASTRIGGERVALUES_DATASOURCE = "datasource"; + var TMP_FAASTRIGGERVALUES_HTTP = "http"; + var TMP_FAASTRIGGERVALUES_PUBSUB = "pubsub"; + var TMP_FAASTRIGGERVALUES_TIMER = "timer"; + var TMP_FAASTRIGGERVALUES_OTHER = "other"; + exports.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; + exports.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; + exports.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; + exports.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; + exports.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; + exports.FaasTriggerValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_FAASTRIGGERVALUES_DATASOURCE, + TMP_FAASTRIGGERVALUES_HTTP, + TMP_FAASTRIGGERVALUES_PUBSUB, + TMP_FAASTRIGGERVALUES_TIMER, + TMP_FAASTRIGGERVALUES_OTHER + ]); + var TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = "insert"; + var TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = "edit"; + var TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = "delete"; + exports.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; + exports.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; + exports.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; + exports.FaasDocumentOperationValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, + TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, + TMP_FAASDOCUMENTOPERATIONVALUES_DELETE + ]); + var TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + var TMP_FAASINVOKEDPROVIDERVALUES_AWS = "aws"; + var TMP_FAASINVOKEDPROVIDERVALUES_AZURE = "azure"; + var TMP_FAASINVOKEDPROVIDERVALUES_GCP = "gcp"; + exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; + exports.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; + exports.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; + exports.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; + exports.FaasInvokedProviderValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_FAASINVOKEDPROVIDERVALUES_AWS, + TMP_FAASINVOKEDPROVIDERVALUES_AZURE, + TMP_FAASINVOKEDPROVIDERVALUES_GCP + ]); + var TMP_NETTRANSPORTVALUES_IP_TCP = "ip_tcp"; + var TMP_NETTRANSPORTVALUES_IP_UDP = "ip_udp"; + var TMP_NETTRANSPORTVALUES_IP = "ip"; + var TMP_NETTRANSPORTVALUES_UNIX = "unix"; + var TMP_NETTRANSPORTVALUES_PIPE = "pipe"; + var TMP_NETTRANSPORTVALUES_INPROC = "inproc"; + var TMP_NETTRANSPORTVALUES_OTHER = "other"; + exports.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; + exports.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; + exports.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; + exports.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; + exports.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; + exports.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; + exports.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; + exports.NetTransportValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_NETTRANSPORTVALUES_IP_TCP, + TMP_NETTRANSPORTVALUES_IP_UDP, + TMP_NETTRANSPORTVALUES_IP, + TMP_NETTRANSPORTVALUES_UNIX, + TMP_NETTRANSPORTVALUES_PIPE, + TMP_NETTRANSPORTVALUES_INPROC, + TMP_NETTRANSPORTVALUES_OTHER + ]); + var TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = "wifi"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = "wired"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = "cell"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = "unavailable"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = "unknown"; + exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; + exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; + exports.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; + exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; + exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; + exports.NetHostConnectionTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, + TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, + TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN + ]); + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = "gprs"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = "edge"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = "umts"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = "cdma"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = "evdo_0"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = "evdo_a"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = "cdma2000_1xrtt"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = "hsdpa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = "hsupa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = "hspa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = "iden"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = "evdo_b"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = "lte"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = "ehrpd"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = "hspap"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = "gsm"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = "td_scdma"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = "iwlan"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = "nr"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = "nrnsa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = "lte_ca"; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; + exports.NetHostConnectionSubtypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA + ]); + var TMP_HTTPFLAVORVALUES_HTTP_1_0 = "1.0"; + var TMP_HTTPFLAVORVALUES_HTTP_1_1 = "1.1"; + var TMP_HTTPFLAVORVALUES_HTTP_2_0 = "2.0"; + var TMP_HTTPFLAVORVALUES_SPDY = "SPDY"; + var TMP_HTTPFLAVORVALUES_QUIC = "QUIC"; + exports.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; + exports.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; + exports.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; + exports.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; + exports.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; + exports.HttpFlavorValues = { + HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, + HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, + HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, + SPDY: TMP_HTTPFLAVORVALUES_SPDY, + QUIC: TMP_HTTPFLAVORVALUES_QUIC + }; + var TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = "queue"; + var TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = "topic"; + exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; + exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; + exports.MessagingDestinationKindValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, + TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC + ]); + var TMP_MESSAGINGOPERATIONVALUES_RECEIVE = "receive"; + var TMP_MESSAGINGOPERATIONVALUES_PROCESS = "process"; + exports.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; + exports.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; + exports.MessagingOperationValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_MESSAGINGOPERATIONVALUES_RECEIVE, + TMP_MESSAGINGOPERATIONVALUES_PROCESS + ]); + var TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; + var TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; + var TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; + var TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; + var TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; + var TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; + var TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; + var TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; + var TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; + var TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; + var TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; + var TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; + var TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; + var TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; + var TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; + var TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; + var TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; + exports.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; + exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; + exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; + exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; + exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; + exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; + exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; + exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; + exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; + exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; + exports.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; + exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; + exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; + exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; + exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; + exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; + exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; + exports.RpcGrpcStatusCodeValues = { + OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, + CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, + UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, + INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, + DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, + NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, + ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, + PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, + RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, + FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, + ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, + OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, + UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, + INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, + UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, + DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, + UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED + }; + var TMP_MESSAGETYPEVALUES_SENT = "SENT"; + var TMP_MESSAGETYPEVALUES_RECEIVED = "RECEIVED"; + exports.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; + exports.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; + exports.MessageTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_MESSAGETYPEVALUES_SENT, + TMP_MESSAGETYPEVALUES_RECEIVED + ]); + } +}); + +// node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js +var require_trace2 = __commonJS({ + "node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m2[k]; + } }); + } : function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + o[k2] = m2[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p2 in m2) + if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) + __createBinding(exports2, m2, p2); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_SemanticAttributes(), exports); + } +}); + +// node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js +var require_SemanticResourceAttributes = __commonJS({ + "node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SEMRESATTRS_K8S_STATEFULSET_NAME = exports.SEMRESATTRS_K8S_STATEFULSET_UID = exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = exports.SEMRESATTRS_K8S_REPLICASET_NAME = exports.SEMRESATTRS_K8S_REPLICASET_UID = exports.SEMRESATTRS_K8S_CONTAINER_NAME = exports.SEMRESATTRS_K8S_POD_NAME = exports.SEMRESATTRS_K8S_POD_UID = exports.SEMRESATTRS_K8S_NAMESPACE_NAME = exports.SEMRESATTRS_K8S_NODE_UID = exports.SEMRESATTRS_K8S_NODE_NAME = exports.SEMRESATTRS_K8S_CLUSTER_NAME = exports.SEMRESATTRS_HOST_IMAGE_VERSION = exports.SEMRESATTRS_HOST_IMAGE_ID = exports.SEMRESATTRS_HOST_IMAGE_NAME = exports.SEMRESATTRS_HOST_ARCH = exports.SEMRESATTRS_HOST_TYPE = exports.SEMRESATTRS_HOST_NAME = exports.SEMRESATTRS_HOST_ID = exports.SEMRESATTRS_FAAS_MAX_MEMORY = exports.SEMRESATTRS_FAAS_INSTANCE = exports.SEMRESATTRS_FAAS_VERSION = exports.SEMRESATTRS_FAAS_ID = exports.SEMRESATTRS_FAAS_NAME = exports.SEMRESATTRS_DEVICE_MODEL_NAME = exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = exports.SEMRESATTRS_DEVICE_ID = exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = exports.SEMRESATTRS_CONTAINER_RUNTIME = exports.SEMRESATTRS_CONTAINER_ID = exports.SEMRESATTRS_CONTAINER_NAME = exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = exports.SEMRESATTRS_AWS_ECS_TASK_ARN = exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = exports.SEMRESATTRS_CLOUD_PLATFORM = exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = exports.SEMRESATTRS_CLOUD_REGION = exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = exports.SEMRESATTRS_CLOUD_PROVIDER = void 0; + exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = exports.CLOUDPLATFORMVALUES_AZURE_AKS = exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = exports.CLOUDPLATFORMVALUES_AZURE_VM = exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = exports.CLOUDPLATFORMVALUES_AWS_EKS = exports.CLOUDPLATFORMVALUES_AWS_ECS = exports.CLOUDPLATFORMVALUES_AWS_EC2 = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = exports.CloudProviderValues = exports.CLOUDPROVIDERVALUES_GCP = exports.CLOUDPROVIDERVALUES_AZURE = exports.CLOUDPROVIDERVALUES_AWS = exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = exports.SemanticResourceAttributes = exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = exports.SEMRESATTRS_WEBENGINE_VERSION = exports.SEMRESATTRS_WEBENGINE_NAME = exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = exports.SEMRESATTRS_TELEMETRY_SDK_NAME = exports.SEMRESATTRS_SERVICE_VERSION = exports.SEMRESATTRS_SERVICE_INSTANCE_ID = exports.SEMRESATTRS_SERVICE_NAMESPACE = exports.SEMRESATTRS_SERVICE_NAME = exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = exports.SEMRESATTRS_PROCESS_OWNER = exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = exports.SEMRESATTRS_PROCESS_COMMAND_LINE = exports.SEMRESATTRS_PROCESS_COMMAND = exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = exports.SEMRESATTRS_PROCESS_PID = exports.SEMRESATTRS_OS_VERSION = exports.SEMRESATTRS_OS_NAME = exports.SEMRESATTRS_OS_DESCRIPTION = exports.SEMRESATTRS_OS_TYPE = exports.SEMRESATTRS_K8S_CRONJOB_NAME = exports.SEMRESATTRS_K8S_CRONJOB_UID = exports.SEMRESATTRS_K8S_JOB_NAME = exports.SEMRESATTRS_K8S_JOB_UID = exports.SEMRESATTRS_K8S_DAEMONSET_NAME = exports.SEMRESATTRS_K8S_DAEMONSET_UID = void 0; + exports.TelemetrySdkLanguageValues = exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = exports.TELEMETRYSDKLANGUAGEVALUES_PHP = exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = exports.TELEMETRYSDKLANGUAGEVALUES_GO = exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = exports.TELEMETRYSDKLANGUAGEVALUES_CPP = exports.OsTypeValues = exports.OSTYPEVALUES_Z_OS = exports.OSTYPEVALUES_SOLARIS = exports.OSTYPEVALUES_AIX = exports.OSTYPEVALUES_HPUX = exports.OSTYPEVALUES_DRAGONFLYBSD = exports.OSTYPEVALUES_OPENBSD = exports.OSTYPEVALUES_NETBSD = exports.OSTYPEVALUES_FREEBSD = exports.OSTYPEVALUES_DARWIN = exports.OSTYPEVALUES_LINUX = exports.OSTYPEVALUES_WINDOWS = exports.HostArchValues = exports.HOSTARCHVALUES_X86 = exports.HOSTARCHVALUES_PPC64 = exports.HOSTARCHVALUES_PPC32 = exports.HOSTARCHVALUES_IA64 = exports.HOSTARCHVALUES_ARM64 = exports.HOSTARCHVALUES_ARM32 = exports.HOSTARCHVALUES_AMD64 = exports.AwsEcsLaunchtypeValues = exports.AWSECSLAUNCHTYPEVALUES_FARGATE = exports.AWSECSLAUNCHTYPEVALUES_EC2 = exports.CloudPlatformValues = exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = void 0; + var utils_1 = require_utils3(); + var TMP_CLOUD_PROVIDER = "cloud.provider"; + var TMP_CLOUD_ACCOUNT_ID = "cloud.account.id"; + var TMP_CLOUD_REGION = "cloud.region"; + var TMP_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone"; + var TMP_CLOUD_PLATFORM = "cloud.platform"; + var TMP_AWS_ECS_CONTAINER_ARN = "aws.ecs.container.arn"; + var TMP_AWS_ECS_CLUSTER_ARN = "aws.ecs.cluster.arn"; + var TMP_AWS_ECS_LAUNCHTYPE = "aws.ecs.launchtype"; + var TMP_AWS_ECS_TASK_ARN = "aws.ecs.task.arn"; + var TMP_AWS_ECS_TASK_FAMILY = "aws.ecs.task.family"; + var TMP_AWS_ECS_TASK_REVISION = "aws.ecs.task.revision"; + var TMP_AWS_EKS_CLUSTER_ARN = "aws.eks.cluster.arn"; + var TMP_AWS_LOG_GROUP_NAMES = "aws.log.group.names"; + var TMP_AWS_LOG_GROUP_ARNS = "aws.log.group.arns"; + var TMP_AWS_LOG_STREAM_NAMES = "aws.log.stream.names"; + var TMP_AWS_LOG_STREAM_ARNS = "aws.log.stream.arns"; + var TMP_CONTAINER_NAME = "container.name"; + var TMP_CONTAINER_ID = "container.id"; + var TMP_CONTAINER_RUNTIME = "container.runtime"; + var TMP_CONTAINER_IMAGE_NAME = "container.image.name"; + var TMP_CONTAINER_IMAGE_TAG = "container.image.tag"; + var TMP_DEPLOYMENT_ENVIRONMENT = "deployment.environment"; + var TMP_DEVICE_ID = "device.id"; + var TMP_DEVICE_MODEL_IDENTIFIER = "device.model.identifier"; + var TMP_DEVICE_MODEL_NAME = "device.model.name"; + var TMP_FAAS_NAME = "faas.name"; + var TMP_FAAS_ID = "faas.id"; + var TMP_FAAS_VERSION = "faas.version"; + var TMP_FAAS_INSTANCE = "faas.instance"; + var TMP_FAAS_MAX_MEMORY = "faas.max_memory"; + var TMP_HOST_ID = "host.id"; + var TMP_HOST_NAME = "host.name"; + var TMP_HOST_TYPE = "host.type"; + var TMP_HOST_ARCH = "host.arch"; + var TMP_HOST_IMAGE_NAME = "host.image.name"; + var TMP_HOST_IMAGE_ID = "host.image.id"; + var TMP_HOST_IMAGE_VERSION = "host.image.version"; + var TMP_K8S_CLUSTER_NAME = "k8s.cluster.name"; + var TMP_K8S_NODE_NAME = "k8s.node.name"; + var TMP_K8S_NODE_UID = "k8s.node.uid"; + var TMP_K8S_NAMESPACE_NAME = "k8s.namespace.name"; + var TMP_K8S_POD_UID = "k8s.pod.uid"; + var TMP_K8S_POD_NAME = "k8s.pod.name"; + var TMP_K8S_CONTAINER_NAME = "k8s.container.name"; + var TMP_K8S_REPLICASET_UID = "k8s.replicaset.uid"; + var TMP_K8S_REPLICASET_NAME = "k8s.replicaset.name"; + var TMP_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; + var TMP_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; + var TMP_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; + var TMP_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; + var TMP_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; + var TMP_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; + var TMP_K8S_JOB_UID = "k8s.job.uid"; + var TMP_K8S_JOB_NAME = "k8s.job.name"; + var TMP_K8S_CRONJOB_UID = "k8s.cronjob.uid"; + var TMP_K8S_CRONJOB_NAME = "k8s.cronjob.name"; + var TMP_OS_TYPE = "os.type"; + var TMP_OS_DESCRIPTION = "os.description"; + var TMP_OS_NAME = "os.name"; + var TMP_OS_VERSION = "os.version"; + var TMP_PROCESS_PID = "process.pid"; + var TMP_PROCESS_EXECUTABLE_NAME = "process.executable.name"; + var TMP_PROCESS_EXECUTABLE_PATH = "process.executable.path"; + var TMP_PROCESS_COMMAND = "process.command"; + var TMP_PROCESS_COMMAND_LINE = "process.command_line"; + var TMP_PROCESS_COMMAND_ARGS = "process.command_args"; + var TMP_PROCESS_OWNER = "process.owner"; + var TMP_PROCESS_RUNTIME_NAME = "process.runtime.name"; + var TMP_PROCESS_RUNTIME_VERSION = "process.runtime.version"; + var TMP_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description"; + var TMP_SERVICE_NAME = "service.name"; + var TMP_SERVICE_NAMESPACE = "service.namespace"; + var TMP_SERVICE_INSTANCE_ID = "service.instance.id"; + var TMP_SERVICE_VERSION = "service.version"; + var TMP_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + var TMP_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + var TMP_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + var TMP_TELEMETRY_AUTO_VERSION = "telemetry.auto.version"; + var TMP_WEBENGINE_NAME = "webengine.name"; + var TMP_WEBENGINE_VERSION = "webengine.version"; + var TMP_WEBENGINE_DESCRIPTION = "webengine.description"; + exports.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; + exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; + exports.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; + exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; + exports.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; + exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; + exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; + exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; + exports.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; + exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; + exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; + exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; + exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; + exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; + exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; + exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; + exports.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; + exports.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; + exports.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; + exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; + exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; + exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; + exports.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; + exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; + exports.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; + exports.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; + exports.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; + exports.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; + exports.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; + exports.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; + exports.SEMRESATTRS_HOST_ID = TMP_HOST_ID; + exports.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; + exports.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; + exports.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; + exports.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; + exports.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; + exports.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; + exports.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; + exports.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; + exports.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; + exports.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; + exports.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; + exports.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; + exports.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; + exports.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; + exports.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; + exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; + exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; + exports.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; + exports.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; + exports.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; + exports.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; + exports.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; + exports.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; + exports.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; + exports.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; + exports.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; + exports.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; + exports.SEMRESATTRS_OS_NAME = TMP_OS_NAME; + exports.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; + exports.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; + exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; + exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; + exports.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; + exports.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; + exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; + exports.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; + exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; + exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; + exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; + exports.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; + exports.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; + exports.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; + exports.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; + exports.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; + exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; + exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; + exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; + exports.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; + exports.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; + exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; + exports.SemanticResourceAttributes = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_CLOUD_PROVIDER, + TMP_CLOUD_ACCOUNT_ID, + TMP_CLOUD_REGION, + TMP_CLOUD_AVAILABILITY_ZONE, + TMP_CLOUD_PLATFORM, + TMP_AWS_ECS_CONTAINER_ARN, + TMP_AWS_ECS_CLUSTER_ARN, + TMP_AWS_ECS_LAUNCHTYPE, + TMP_AWS_ECS_TASK_ARN, + TMP_AWS_ECS_TASK_FAMILY, + TMP_AWS_ECS_TASK_REVISION, + TMP_AWS_EKS_CLUSTER_ARN, + TMP_AWS_LOG_GROUP_NAMES, + TMP_AWS_LOG_GROUP_ARNS, + TMP_AWS_LOG_STREAM_NAMES, + TMP_AWS_LOG_STREAM_ARNS, + TMP_CONTAINER_NAME, + TMP_CONTAINER_ID, + TMP_CONTAINER_RUNTIME, + TMP_CONTAINER_IMAGE_NAME, + TMP_CONTAINER_IMAGE_TAG, + TMP_DEPLOYMENT_ENVIRONMENT, + TMP_DEVICE_ID, + TMP_DEVICE_MODEL_IDENTIFIER, + TMP_DEVICE_MODEL_NAME, + TMP_FAAS_NAME, + TMP_FAAS_ID, + TMP_FAAS_VERSION, + TMP_FAAS_INSTANCE, + TMP_FAAS_MAX_MEMORY, + TMP_HOST_ID, + TMP_HOST_NAME, + TMP_HOST_TYPE, + TMP_HOST_ARCH, + TMP_HOST_IMAGE_NAME, + TMP_HOST_IMAGE_ID, + TMP_HOST_IMAGE_VERSION, + TMP_K8S_CLUSTER_NAME, + TMP_K8S_NODE_NAME, + TMP_K8S_NODE_UID, + TMP_K8S_NAMESPACE_NAME, + TMP_K8S_POD_UID, + TMP_K8S_POD_NAME, + TMP_K8S_CONTAINER_NAME, + TMP_K8S_REPLICASET_UID, + TMP_K8S_REPLICASET_NAME, + TMP_K8S_DEPLOYMENT_UID, + TMP_K8S_DEPLOYMENT_NAME, + TMP_K8S_STATEFULSET_UID, + TMP_K8S_STATEFULSET_NAME, + TMP_K8S_DAEMONSET_UID, + TMP_K8S_DAEMONSET_NAME, + TMP_K8S_JOB_UID, + TMP_K8S_JOB_NAME, + TMP_K8S_CRONJOB_UID, + TMP_K8S_CRONJOB_NAME, + TMP_OS_TYPE, + TMP_OS_DESCRIPTION, + TMP_OS_NAME, + TMP_OS_VERSION, + TMP_PROCESS_PID, + TMP_PROCESS_EXECUTABLE_NAME, + TMP_PROCESS_EXECUTABLE_PATH, + TMP_PROCESS_COMMAND, + TMP_PROCESS_COMMAND_LINE, + TMP_PROCESS_COMMAND_ARGS, + TMP_PROCESS_OWNER, + TMP_PROCESS_RUNTIME_NAME, + TMP_PROCESS_RUNTIME_VERSION, + TMP_PROCESS_RUNTIME_DESCRIPTION, + TMP_SERVICE_NAME, + TMP_SERVICE_NAMESPACE, + TMP_SERVICE_INSTANCE_ID, + TMP_SERVICE_VERSION, + TMP_TELEMETRY_SDK_NAME, + TMP_TELEMETRY_SDK_LANGUAGE, + TMP_TELEMETRY_SDK_VERSION, + TMP_TELEMETRY_AUTO_VERSION, + TMP_WEBENGINE_NAME, + TMP_WEBENGINE_VERSION, + TMP_WEBENGINE_DESCRIPTION + ]); + var TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + var TMP_CLOUDPROVIDERVALUES_AWS = "aws"; + var TMP_CLOUDPROVIDERVALUES_AZURE = "azure"; + var TMP_CLOUDPROVIDERVALUES_GCP = "gcp"; + exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; + exports.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; + exports.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; + exports.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; + exports.CloudProviderValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_CLOUDPROVIDERVALUES_AWS, + TMP_CLOUDPROVIDERVALUES_AZURE, + TMP_CLOUDPROVIDERVALUES_GCP + ]); + var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs"; + var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = "alibaba_cloud_fc"; + var TMP_CLOUDPLATFORMVALUES_AWS_EC2 = "aws_ec2"; + var TMP_CLOUDPLATFORMVALUES_AWS_ECS = "aws_ecs"; + var TMP_CLOUDPLATFORMVALUES_AWS_EKS = "aws_eks"; + var TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = "aws_lambda"; + var TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk"; + var TMP_CLOUDPLATFORMVALUES_AZURE_VM = "azure_vm"; + var TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = "azure_container_instances"; + var TMP_CLOUDPLATFORMVALUES_AZURE_AKS = "azure_aks"; + var TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = "azure_functions"; + var TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = "azure_app_service"; + var TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = "gcp_compute_engine"; + var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = "gcp_cloud_run"; + var TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine"; + var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions"; + var TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = "gcp_app_engine"; + exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; + exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; + exports.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; + exports.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; + exports.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; + exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; + exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; + exports.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; + exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; + exports.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; + exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; + exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; + exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; + exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; + exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; + exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; + exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; + exports.CloudPlatformValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, + TMP_CLOUDPLATFORMVALUES_AWS_EC2, + TMP_CLOUDPLATFORMVALUES_AWS_ECS, + TMP_CLOUDPLATFORMVALUES_AWS_EKS, + TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, + TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, + TMP_CLOUDPLATFORMVALUES_AZURE_VM, + TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, + TMP_CLOUDPLATFORMVALUES_AZURE_AKS, + TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, + TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, + TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE + ]); + var TMP_AWSECSLAUNCHTYPEVALUES_EC2 = "ec2"; + var TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = "fargate"; + exports.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; + exports.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; + exports.AwsEcsLaunchtypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_AWSECSLAUNCHTYPEVALUES_EC2, + TMP_AWSECSLAUNCHTYPEVALUES_FARGATE + ]); + var TMP_HOSTARCHVALUES_AMD64 = "amd64"; + var TMP_HOSTARCHVALUES_ARM32 = "arm32"; + var TMP_HOSTARCHVALUES_ARM64 = "arm64"; + var TMP_HOSTARCHVALUES_IA64 = "ia64"; + var TMP_HOSTARCHVALUES_PPC32 = "ppc32"; + var TMP_HOSTARCHVALUES_PPC64 = "ppc64"; + var TMP_HOSTARCHVALUES_X86 = "x86"; + exports.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; + exports.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; + exports.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; + exports.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; + exports.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; + exports.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; + exports.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; + exports.HostArchValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_HOSTARCHVALUES_AMD64, + TMP_HOSTARCHVALUES_ARM32, + TMP_HOSTARCHVALUES_ARM64, + TMP_HOSTARCHVALUES_IA64, + TMP_HOSTARCHVALUES_PPC32, + TMP_HOSTARCHVALUES_PPC64, + TMP_HOSTARCHVALUES_X86 + ]); + var TMP_OSTYPEVALUES_WINDOWS = "windows"; + var TMP_OSTYPEVALUES_LINUX = "linux"; + var TMP_OSTYPEVALUES_DARWIN = "darwin"; + var TMP_OSTYPEVALUES_FREEBSD = "freebsd"; + var TMP_OSTYPEVALUES_NETBSD = "netbsd"; + var TMP_OSTYPEVALUES_OPENBSD = "openbsd"; + var TMP_OSTYPEVALUES_DRAGONFLYBSD = "dragonflybsd"; + var TMP_OSTYPEVALUES_HPUX = "hpux"; + var TMP_OSTYPEVALUES_AIX = "aix"; + var TMP_OSTYPEVALUES_SOLARIS = "solaris"; + var TMP_OSTYPEVALUES_Z_OS = "z_os"; + exports.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; + exports.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; + exports.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; + exports.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; + exports.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; + exports.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; + exports.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; + exports.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; + exports.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; + exports.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; + exports.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; + exports.OsTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_OSTYPEVALUES_WINDOWS, + TMP_OSTYPEVALUES_LINUX, + TMP_OSTYPEVALUES_DARWIN, + TMP_OSTYPEVALUES_FREEBSD, + TMP_OSTYPEVALUES_NETBSD, + TMP_OSTYPEVALUES_OPENBSD, + TMP_OSTYPEVALUES_DRAGONFLYBSD, + TMP_OSTYPEVALUES_HPUX, + TMP_OSTYPEVALUES_AIX, + TMP_OSTYPEVALUES_SOLARIS, + TMP_OSTYPEVALUES_Z_OS + ]); + var TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = "cpp"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = "dotnet"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = "erlang"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_GO = "go"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = "java"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = "nodejs"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = "php"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = "python"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = "ruby"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = "webjs"; + exports.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; + exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; + exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; + exports.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; + exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; + exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; + exports.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; + exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; + exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; + exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; + exports.TelemetrySdkLanguageValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, + TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, + TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, + TMP_TELEMETRYSDKLANGUAGEVALUES_GO, + TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, + TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, + TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, + TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, + TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, + TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS + ]); + } +}); + +// node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js +var require_resource = __commonJS({ + "node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m2[k]; + } }); + } : function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + o[k2] = m2[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p2 in m2) + if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) + __createBinding(exports2, m2, p2); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_SemanticResourceAttributes(), exports); + } +}); + +// node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js +var require_stable_attributes = __commonJS({ + "node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HTTP_REQUEST_METHOD_VALUE_POST = exports.HTTP_REQUEST_METHOD_VALUE_PATCH = exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = exports.HTTP_REQUEST_METHOD_VALUE_HEAD = exports.HTTP_REQUEST_METHOD_VALUE_GET = exports.HTTP_REQUEST_METHOD_VALUE_DELETE = exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = exports.HTTP_REQUEST_METHOD_VALUE_OTHER = exports.ATTR_HTTP_REQUEST_METHOD = exports.ATTR_HTTP_REQUEST_HEADER = exports.ATTR_EXCEPTION_TYPE = exports.ATTR_EXCEPTION_STACKTRACE = exports.ATTR_EXCEPTION_MESSAGE = exports.ATTR_EXCEPTION_ESCAPED = exports.ERROR_TYPE_VALUE_OTHER = exports.ATTR_ERROR_TYPE = exports.ATTR_CLIENT_PORT = exports.ATTR_CLIENT_ADDRESS = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = exports.ATTR_TELEMETRY_SDK_VERSION = exports.ATTR_TELEMETRY_SDK_NAME = exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = exports.ATTR_TELEMETRY_SDK_LANGUAGE = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = void 0; + exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = exports.ATTR_SIGNALR_CONNECTION_STATUS = exports.ATTR_SERVICE_VERSION = exports.ATTR_SERVICE_NAME = exports.ATTR_SERVER_PORT = exports.ATTR_SERVER_ADDRESS = exports.ATTR_OTEL_STATUS_DESCRIPTION = exports.OTEL_STATUS_CODE_VALUE_OK = exports.OTEL_STATUS_CODE_VALUE_ERROR = exports.ATTR_OTEL_STATUS_CODE = exports.ATTR_OTEL_SCOPE_VERSION = exports.ATTR_OTEL_SCOPE_NAME = exports.NETWORK_TYPE_VALUE_IPV6 = exports.NETWORK_TYPE_VALUE_IPV4 = exports.ATTR_NETWORK_TYPE = exports.NETWORK_TRANSPORT_VALUE_UNIX = exports.NETWORK_TRANSPORT_VALUE_UDP = exports.NETWORK_TRANSPORT_VALUE_TCP = exports.NETWORK_TRANSPORT_VALUE_QUIC = exports.NETWORK_TRANSPORT_VALUE_PIPE = exports.ATTR_NETWORK_TRANSPORT = exports.ATTR_NETWORK_PROTOCOL_VERSION = exports.ATTR_NETWORK_PROTOCOL_NAME = exports.ATTR_NETWORK_PEER_PORT = exports.ATTR_NETWORK_PEER_ADDRESS = exports.ATTR_NETWORK_LOCAL_PORT = exports.ATTR_NETWORK_LOCAL_ADDRESS = exports.JVM_THREAD_STATE_VALUE_WAITING = exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = exports.JVM_THREAD_STATE_VALUE_TERMINATED = exports.JVM_THREAD_STATE_VALUE_RUNNABLE = exports.JVM_THREAD_STATE_VALUE_NEW = exports.JVM_THREAD_STATE_VALUE_BLOCKED = exports.ATTR_JVM_THREAD_STATE = exports.ATTR_JVM_THREAD_DAEMON = exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = exports.JVM_MEMORY_TYPE_VALUE_HEAP = exports.ATTR_JVM_MEMORY_TYPE = exports.ATTR_JVM_MEMORY_POOL_NAME = exports.ATTR_JVM_GC_NAME = exports.ATTR_JVM_GC_ACTION = exports.ATTR_HTTP_ROUTE = exports.ATTR_HTTP_RESPONSE_STATUS_CODE = exports.ATTR_HTTP_RESPONSE_HEADER = exports.ATTR_HTTP_REQUEST_RESEND_COUNT = exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = exports.HTTP_REQUEST_METHOD_VALUE_TRACE = exports.HTTP_REQUEST_METHOD_VALUE_PUT = void 0; + exports.ATTR_USER_AGENT_ORIGINAL = exports.ATTR_URL_SCHEME = exports.ATTR_URL_QUERY = exports.ATTR_URL_PATH = exports.ATTR_URL_FULL = exports.ATTR_URL_FRAGMENT = exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = exports.ATTR_SIGNALR_TRANSPORT = void 0; + exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = "aspnetcore.rate_limiting.result"; + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; + exports.ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; + exports.ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + exports.ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = "aspnetcore.diagnostics.handler.type"; + exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = "aspnetcore.diagnostics.exception.result"; + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; + exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = "aspnetcore.rate_limiting.policy"; + exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = "aspnetcore.request.is_unhandled"; + exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = "aspnetcore.routing.is_fallback"; + exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = "aspnetcore.routing.match_status"; + exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; + exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; + exports.ATTR_CLIENT_ADDRESS = "client.address"; + exports.ATTR_CLIENT_PORT = "client.port"; + exports.ATTR_ERROR_TYPE = "error.type"; + exports.ERROR_TYPE_VALUE_OTHER = "_OTHER"; + exports.ATTR_EXCEPTION_ESCAPED = "exception.escaped"; + exports.ATTR_EXCEPTION_MESSAGE = "exception.message"; + exports.ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace"; + exports.ATTR_EXCEPTION_TYPE = "exception.type"; + var ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; + exports.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER; + exports.ATTR_HTTP_REQUEST_METHOD = "http.request.method"; + exports.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; + exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; + exports.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; + exports.HTTP_REQUEST_METHOD_VALUE_GET = "GET"; + exports.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; + exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; + exports.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; + exports.HTTP_REQUEST_METHOD_VALUE_POST = "POST"; + exports.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; + exports.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; + exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original"; + exports.ATTR_HTTP_REQUEST_RESEND_COUNT = "http.request.resend_count"; + var ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; + exports.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER; + exports.ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"; + exports.ATTR_HTTP_ROUTE = "http.route"; + exports.ATTR_JVM_GC_ACTION = "jvm.gc.action"; + exports.ATTR_JVM_GC_NAME = "jvm.gc.name"; + exports.ATTR_JVM_MEMORY_POOL_NAME = "jvm.memory.pool.name"; + exports.ATTR_JVM_MEMORY_TYPE = "jvm.memory.type"; + exports.JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; + exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; + exports.ATTR_JVM_THREAD_DAEMON = "jvm.thread.daemon"; + exports.ATTR_JVM_THREAD_STATE = "jvm.thread.state"; + exports.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; + exports.JVM_THREAD_STATE_VALUE_NEW = "new"; + exports.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; + exports.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; + exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; + exports.JVM_THREAD_STATE_VALUE_WAITING = "waiting"; + exports.ATTR_NETWORK_LOCAL_ADDRESS = "network.local.address"; + exports.ATTR_NETWORK_LOCAL_PORT = "network.local.port"; + exports.ATTR_NETWORK_PEER_ADDRESS = "network.peer.address"; + exports.ATTR_NETWORK_PEER_PORT = "network.peer.port"; + exports.ATTR_NETWORK_PROTOCOL_NAME = "network.protocol.name"; + exports.ATTR_NETWORK_PROTOCOL_VERSION = "network.protocol.version"; + exports.ATTR_NETWORK_TRANSPORT = "network.transport"; + exports.NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; + exports.NETWORK_TRANSPORT_VALUE_QUIC = "quic"; + exports.NETWORK_TRANSPORT_VALUE_TCP = "tcp"; + exports.NETWORK_TRANSPORT_VALUE_UDP = "udp"; + exports.NETWORK_TRANSPORT_VALUE_UNIX = "unix"; + exports.ATTR_NETWORK_TYPE = "network.type"; + exports.NETWORK_TYPE_VALUE_IPV4 = "ipv4"; + exports.NETWORK_TYPE_VALUE_IPV6 = "ipv6"; + exports.ATTR_OTEL_SCOPE_NAME = "otel.scope.name"; + exports.ATTR_OTEL_SCOPE_VERSION = "otel.scope.version"; + exports.ATTR_OTEL_STATUS_CODE = "otel.status_code"; + exports.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; + exports.OTEL_STATUS_CODE_VALUE_OK = "OK"; + exports.ATTR_OTEL_STATUS_DESCRIPTION = "otel.status_description"; + exports.ATTR_SERVER_ADDRESS = "server.address"; + exports.ATTR_SERVER_PORT = "server.port"; + exports.ATTR_SERVICE_NAME = "service.name"; + exports.ATTR_SERVICE_VERSION = "service.version"; + exports.ATTR_SIGNALR_CONNECTION_STATUS = "signalr.connection.status"; + exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; + exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; + exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; + exports.ATTR_SIGNALR_TRANSPORT = "signalr.transport"; + exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; + exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; + exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; + exports.ATTR_URL_FRAGMENT = "url.fragment"; + exports.ATTR_URL_FULL = "url.full"; + exports.ATTR_URL_PATH = "url.path"; + exports.ATTR_URL_QUERY = "url.query"; + exports.ATTR_URL_SCHEME = "url.scheme"; + exports.ATTR_USER_AGENT_ORIGINAL = "user_agent.original"; + } +}); + +// node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js +var require_stable_metrics = __commonJS({ + "node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = exports.METRIC_KESTREL_REJECTED_CONNECTIONS = exports.METRIC_KESTREL_QUEUED_REQUESTS = exports.METRIC_KESTREL_QUEUED_CONNECTIONS = exports.METRIC_KESTREL_CONNECTION_DURATION = exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = exports.METRIC_JVM_THREAD_COUNT = exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = exports.METRIC_JVM_MEMORY_USED = exports.METRIC_JVM_MEMORY_LIMIT = exports.METRIC_JVM_MEMORY_COMMITTED = exports.METRIC_JVM_GC_DURATION = exports.METRIC_JVM_CPU_TIME = exports.METRIC_JVM_CPU_RECENT_UTILIZATION = exports.METRIC_JVM_CPU_COUNT = exports.METRIC_JVM_CLASS_UNLOADED = exports.METRIC_JVM_CLASS_LOADED = exports.METRIC_JVM_CLASS_COUNT = exports.METRIC_HTTP_SERVER_REQUEST_DURATION = exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = void 0; + exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = "aspnetcore.diagnostics.exceptions"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = "aspnetcore.rate_limiting.active_request_leases"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = "aspnetcore.rate_limiting.queued_requests"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = "aspnetcore.rate_limiting.request.time_in_queue"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = "aspnetcore.rate_limiting.request_lease.duration"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = "aspnetcore.rate_limiting.requests"; + exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = "aspnetcore.routing.match_attempts"; + exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = "http.client.request.duration"; + exports.METRIC_HTTP_SERVER_REQUEST_DURATION = "http.server.request.duration"; + exports.METRIC_JVM_CLASS_COUNT = "jvm.class.count"; + exports.METRIC_JVM_CLASS_LOADED = "jvm.class.loaded"; + exports.METRIC_JVM_CLASS_UNLOADED = "jvm.class.unloaded"; + exports.METRIC_JVM_CPU_COUNT = "jvm.cpu.count"; + exports.METRIC_JVM_CPU_RECENT_UTILIZATION = "jvm.cpu.recent_utilization"; + exports.METRIC_JVM_CPU_TIME = "jvm.cpu.time"; + exports.METRIC_JVM_GC_DURATION = "jvm.gc.duration"; + exports.METRIC_JVM_MEMORY_COMMITTED = "jvm.memory.committed"; + exports.METRIC_JVM_MEMORY_LIMIT = "jvm.memory.limit"; + exports.METRIC_JVM_MEMORY_USED = "jvm.memory.used"; + exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = "jvm.memory.used_after_last_gc"; + exports.METRIC_JVM_THREAD_COUNT = "jvm.thread.count"; + exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = "kestrel.active_connections"; + exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = "kestrel.active_tls_handshakes"; + exports.METRIC_KESTREL_CONNECTION_DURATION = "kestrel.connection.duration"; + exports.METRIC_KESTREL_QUEUED_CONNECTIONS = "kestrel.queued_connections"; + exports.METRIC_KESTREL_QUEUED_REQUESTS = "kestrel.queued_requests"; + exports.METRIC_KESTREL_REJECTED_CONNECTIONS = "kestrel.rejected_connections"; + exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = "kestrel.tls_handshake.duration"; + exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = "kestrel.upgraded_connections"; + exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = "signalr.server.active_connections"; + exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = "signalr.server.connection.duration"; + } +}); + +// node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/index.js +var require_src2 = __commonJS({ + "node_modules/.pnpm/@opentelemetry+semantic-conventions@1.27.0/node_modules/@opentelemetry/semantic-conventions/build/src/index.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m2[k]; + } }); + } : function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + o[k2] = m2[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p2 in m2) + if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) + __createBinding(exports2, m2, p2); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_trace2(), exports); + __exportStar(require_resource(), exports); + __exportStar(require_stable_attributes(), exports); + __exportStar(require_stable_metrics(), exports); + } +}); + +// node_modules/.pnpm/shimmer@1.2.1/node_modules/shimmer/index.js +var require_shimmer = __commonJS({ + "node_modules/.pnpm/shimmer@1.2.1/node_modules/shimmer/index.js"(exports, module) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + function isFunction2(funktion) { + return typeof funktion === "function"; + } + var logger = console.error.bind(console); + function defineProperty(obj, name, value) { + var enumerable = !!obj[name] && obj.propertyIsEnumerable(name); + Object.defineProperty(obj, name, { + configurable: true, + enumerable, + writable: true, + value + }); + } + function shimmer3(options) { + if (options && options.logger) { + if (!isFunction2(options.logger)) + logger("new logger isn't a function, not replacing"); + else + logger = options.logger; + } + } + function wrap3(nodule, name, wrapper) { + if (!nodule || !nodule[name]) { + logger("no original function " + name + " to wrap"); + return; + } + if (!wrapper) { + logger("no wrapper function"); + logger(new Error().stack); + return; + } + if (!isFunction2(nodule[name]) || !isFunction2(wrapper)) { + logger("original object and wrapper must be functions"); + return; + } + var original = nodule[name]; + var wrapped = wrapper(original, name); + defineProperty(wrapped, "__original", original); + defineProperty(wrapped, "__unwrap", function() { + if (nodule[name] === wrapped) + defineProperty(nodule, name, original); + }); + defineProperty(wrapped, "__wrapped", true); + defineProperty(nodule, name, wrapped); + return wrapped; + } + function massWrap(nodules, names, wrapper) { + if (!nodules) { + logger("must provide one or more modules to patch"); + logger(new Error().stack); + return; + } else if (!Array.isArray(nodules)) { + nodules = [nodules]; + } + if (!(names && Array.isArray(names))) { + logger("must provide one or more functions to wrap on modules"); + return; + } + nodules.forEach(function(nodule) { + names.forEach(function(name) { + wrap3(nodule, name, wrapper); + }); + }); + } + function unwrap(nodule, name) { + if (!nodule || !nodule[name]) { + logger("no function to unwrap."); + logger(new Error().stack); + return; + } + if (!nodule[name].__unwrap) { + logger("no original to unwrap to -- has " + name + " already been unwrapped?"); + } else { + return nodule[name].__unwrap(); + } + } + function massUnwrap(nodules, names) { + if (!nodules) { + logger("must provide one or more modules to patch"); + logger(new Error().stack); + return; + } else if (!Array.isArray(nodules)) { + nodules = [nodules]; + } + if (!(names && Array.isArray(names))) { + logger("must provide one or more functions to unwrap on modules"); + return; + } + nodules.forEach(function(nodule) { + names.forEach(function(name) { + unwrap(nodule, name); + }); + }); + } + shimmer3.wrap = wrap3; + shimmer3.massWrap = massWrap; + shimmer3.unwrap = unwrap; + shimmer3.massUnwrap = massUnwrap; + module.exports = shimmer3; + } +}); + +// node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js +var require_react_development = __commonJS({ + "node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js"(exports, module) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + if (true) { + (function() { + "use strict"; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); + } + var ReactVersion = "18.3.1"; + var REACT_ELEMENT_TYPE = Symbol.for("react.element"); + var REACT_PORTAL_TYPE = Symbol.for("react.portal"); + var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); + var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); + var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); + var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); + var REACT_CONTEXT_TYPE = Symbol.for("react.context"); + var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); + var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); + var REACT_MEMO_TYPE = Symbol.for("react.memo"); + var REACT_LAZY_TYPE = Symbol.for("react.lazy"); + var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = "@@iterator"; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== "object") { + return null; + } + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { + return maybeIterator; + } + return null; + } + var ReactCurrentDispatcher = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + var ReactCurrentBatchConfig = { + transition: null + }; + var ReactCurrentActQueue = { + current: null, + // Used to reproduce behavior of `batchedUpdates` in legacy mode. + isBatchingLegacy: false, + didScheduleLegacyUpdate: false + }; + var ReactCurrentOwner = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + var ReactDebugCurrentFrame = {}; + var currentExtraStackFrame = null; + function setExtraStackFrame(stack) { + { + currentExtraStackFrame = stack; + } + } + { + ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { + { + currentExtraStackFrame = stack; + } + }; + ReactDebugCurrentFrame.getCurrentStack = null; + ReactDebugCurrentFrame.getStackAddendum = function() { + var stack = ""; + if (currentExtraStackFrame) { + stack += currentExtraStackFrame; + } + var impl = ReactDebugCurrentFrame.getCurrentStack; + if (impl) { + stack += impl() || ""; + } + return stack; + }; + } + var enableScopeAPI = false; + var enableCacheElement = false; + var enableTransitionTracing = false; + var enableLegacyHidden = false; + var enableDebugTracing = false; + var ReactSharedInternals = { + ReactCurrentDispatcher, + ReactCurrentBatchConfig, + ReactCurrentOwner + }; + { + ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; + } + function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + printWarning("warn", format, args); + } + } + } + function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning("error", format, args); + } + } + } + function printWarning(level, format, args) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var didWarnStateUpdateForUnmountedComponent = {}; + function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; + var warningKey = componentName + "." + callerName; + if (didWarnStateUpdateForUnmountedComponent[warningKey]) { + return; + } + error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); + didWarnStateUpdateForUnmountedComponent[warningKey] = true; + } + } + var ReactNoopUpdateQueue = { + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function(publicInstance) { + return false; + }, + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueForceUpdate: function(publicInstance, callback, callerName) { + warnNoop(publicInstance, "forceUpdate"); + }, + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { + warnNoop(publicInstance, "replaceState"); + }, + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @param {?function} callback Called after component is updated. + * @param {?string} Name of the calling function in the public API. + * @internal + */ + enqueueSetState: function(publicInstance, partialState, callback, callerName) { + warnNoop(publicInstance, "setState"); + } + }; + var assign = Object.assign; + var emptyObject = {}; + { + Object.freeze(emptyObject); + } + function Component2(props, context7, updater) { + this.props = props; + this.context = context7; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + Component2.prototype.isReactComponent = {}; + Component2.prototype.setState = function(partialState, callback) { + if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { + throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); + } + this.updater.enqueueSetState(this, partialState, callback, "setState"); + }; + Component2.prototype.forceUpdate = function(callback) { + this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); + }; + { + var deprecatedAPIs = { + isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], + replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] + }; + var defineDeprecationWarning = function(methodName, info) { + Object.defineProperty(Component2.prototype, methodName, { + get: function() { + warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); + return void 0; + } + }); + }; + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } + } + function ComponentDummy() { + } + ComponentDummy.prototype = Component2.prototype; + function PureComponent(props, context7, updater) { + this.props = props; + this.context = context7; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); + pureComponentPrototype.constructor = PureComponent; + assign(pureComponentPrototype, Component2.prototype); + pureComponentPrototype.isPureReactComponent = true; + function createRef() { + var refObject = { + current: null + }; + { + Object.seal(refObject); + } + return refObject; + } + var isArrayImpl = Array.isArray; + function isArray2(a2) { + return isArrayImpl(a2); + } + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentNameFromType(type) { + if (type == null) { + return null; + } + { + if (typeof type.tag === "number") { + error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); + } + } + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context7 = type; + return getContextName(context7) + ".Consumer"; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + ".Provider"; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + if (outerName !== null) { + return outerName; + } + return getComponentNameFromType(type.type) || "Memo"; + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentNameFromType(init(payload)); + } catch (x2) { + return null; + } + } + } + } + return null; + } + var hasOwnProperty2 = Object.prototype.hasOwnProperty; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; + { + didWarnAboutStringRefs = {}; + } + function hasValidRef(config) { + { + if (hasOwnProperty2.call(config, "ref")) { + var getter = Object.getOwnPropertyDescriptor(config, "ref").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.ref !== void 0; + } + function hasValidKey(config) { + { + if (hasOwnProperty2.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.key !== void 0; + } + function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = function() { + { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true + }); + } + function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = function() { + { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, "ref", { + get: warnAboutAccessingRef, + configurable: true + }); + } + function warnIfStringRefCannotBeAutoConverted(config) { + { + if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + var ReactElement = function(type, key, ref, self2, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type, + key, + ref, + props, + // Record the component responsible for creating this element. + _owner: owner + }; + { + element._store = {}; + Object.defineProperty(element._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: false + }); + Object.defineProperty(element, "_self", { + configurable: false, + enumerable: false, + writable: false, + value: self2 + }); + Object.defineProperty(element, "_source", { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + return element; + }; + function createElement6(type, config, children) { + var propName; + var props = {}; + var key = null; + var ref = null; + var self2 = null; + var source = null; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + { + warnIfStringRefCannotBeAutoConverted(config); + } + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + self2 = config.__self === void 0 ? null : config.__self; + source = config.__source === void 0 ? null : config.__source; + for (propName in config) { + if (hasOwnProperty2.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + { + if (Object.freeze) { + Object.freeze(childArray); + } + } + props.children = childArray; + } + if (type && type.defaultProps) { + var defaultProps16 = type.defaultProps; + for (propName in defaultProps16) { + if (props[propName] === void 0) { + props[propName] = defaultProps16[propName]; + } + } + } + { + if (key || ref) { + var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + } + return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props); + } + function cloneAndReplaceKey(oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + return newElement; + } + function cloneElement3(element, config, children) { + if (element === null || element === void 0) { + throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); + } + var propName; + var props = assign({}, element.props); + var key = element.key; + var ref = element.ref; + var self2 = element._self; + var source = element._source; + var owner = element._owner; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + owner = ReactCurrentOwner.current; + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + var defaultProps16; + if (element.type && element.type.defaultProps) { + defaultProps16 = element.type.defaultProps; + } + for (propName in config) { + if (hasOwnProperty2.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + if (config[propName] === void 0 && defaultProps16 !== void 0) { + props[propName] = defaultProps16[propName]; + } else { + props[propName] = config[propName]; + } + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + props.children = childArray; + } + return ReactElement(element.type, key, ref, self2, source, owner, props); + } + function isValidElement(object) { + return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + var SEPARATOR = "."; + var SUBSEPARATOR = ":"; + function escape(key) { + var escapeRegex = /[=:]/g; + var escaperLookup = { + "=": "=0", + ":": "=2" + }; + var escapedString = key.replace(escapeRegex, function(match) { + return escaperLookup[match]; + }); + return "$" + escapedString; + } + var didWarnAboutMaps = false; + var userProvidedKeyEscapeRegex = /\/+/g; + function escapeUserProvidedKey(text2) { + return text2.replace(userProvidedKeyEscapeRegex, "$&/"); + } + function getElementKey(element, index) { + if (typeof element === "object" && element !== null && element.key != null) { + { + checkKeyStringCoercion(element.key); + } + return escape("" + element.key); + } + return index.toString(36); + } + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if (type === "undefined" || type === "boolean") { + children = null; + } + var invokeCallback = false; + if (children === null) { + invokeCallback = true; + } else { + switch (type) { + case "string": + case "number": + invokeCallback = true; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + } + } + } + if (invokeCallback) { + var _child = children; + var mappedChild = callback(_child); + var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; + if (isArray2(mappedChild)) { + var escapedChildKey = ""; + if (childKey != null) { + escapedChildKey = escapeUserProvidedKey(childKey) + "/"; + } + mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) { + return c; + }); + } else if (mappedChild != null) { + if (isValidElement(mappedChild)) { + { + if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { + checkKeyStringCoercion(mappedChild.key); + } + } + mappedChild = cloneAndReplaceKey( + mappedChild, + // Keep both the (mapped) and old keys if they differ, just as + // traverseAllChildren used to do for objects as children + escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? ( + // $FlowFixMe Flow incorrectly thinks existing element's key can be a number + // eslint-disable-next-line react-internal/safe-string-coercion + escapeUserProvidedKey("" + mappedChild.key) + "/" + ) : "") + childKey + ); + } + array.push(mappedChild); + } + return 1; + } + var child; + var nextName; + var subtreeCount = 0; + var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; + if (isArray2(children)) { + for (var i = 0; i < children.length; i++) { + child = children[i]; + nextName = nextNamePrefix + getElementKey(child, i); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else { + var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { + var iterableChildren = children; + { + if (iteratorFn === iterableChildren.entries) { + if (!didWarnAboutMaps) { + warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); + } + didWarnAboutMaps = true; + } + } + var iterator = iteratorFn.call(iterableChildren); + var step; + var ii2 = 0; + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getElementKey(child, ii2++); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else if (type === "object") { + var childrenString = String(children); + throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); + } + } + return subtreeCount; + } + function mapChildren(children, func, context7) { + if (children == null) { + return children; + } + var result = []; + var count = 0; + mapIntoArray(children, result, "", "", function(child) { + return func.call(context7, child, count++); + }); + return result; + } + function countChildren(children) { + var n = 0; + mapChildren(children, function() { + n++; + }); + return n; + } + function forEachChildren(children, forEachFunc, forEachContext) { + mapChildren(children, function() { + forEachFunc.apply(this, arguments); + }, forEachContext); + } + function toArray(children) { + return mapChildren(children, function(child) { + return child; + }) || []; + } + function onlyChild(children) { + if (!isValidElement(children)) { + throw new Error("React.Children.only expected to receive a single React element child."); + } + return children; + } + function createContext4(defaultValue) { + var context7 = { + $$typeof: REACT_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: defaultValue, + _currentValue2: defaultValue, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + // Add these to use same hidden class in VM as ServerContext + _defaultValue: null, + _globalName: null + }; + context7.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context7 + }; + var hasWarnedAboutUsingNestedContextConsumers = false; + var hasWarnedAboutUsingConsumerProvider = false; + var hasWarnedAboutDisplayNameOnConsumer = false; + { + var Consumer = { + $$typeof: REACT_CONTEXT_TYPE, + _context: context7 + }; + Object.defineProperties(Consumer, { + Provider: { + get: function() { + if (!hasWarnedAboutUsingConsumerProvider) { + hasWarnedAboutUsingConsumerProvider = true; + error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); + } + return context7.Provider; + }, + set: function(_Provider) { + context7.Provider = _Provider; + } + }, + _currentValue: { + get: function() { + return context7._currentValue; + }, + set: function(_currentValue) { + context7._currentValue = _currentValue; + } + }, + _currentValue2: { + get: function() { + return context7._currentValue2; + }, + set: function(_currentValue2) { + context7._currentValue2 = _currentValue2; + } + }, + _threadCount: { + get: function() { + return context7._threadCount; + }, + set: function(_threadCount) { + context7._threadCount = _threadCount; + } + }, + Consumer: { + get: function() { + if (!hasWarnedAboutUsingNestedContextConsumers) { + hasWarnedAboutUsingNestedContextConsumers = true; + error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); + } + return context7.Consumer; + } + }, + displayName: { + get: function() { + return context7.displayName; + }, + set: function(displayName) { + if (!hasWarnedAboutDisplayNameOnConsumer) { + warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); + hasWarnedAboutDisplayNameOnConsumer = true; + } + } + } + }); + context7.Consumer = Consumer; + } + { + context7._currentRenderer = null; + context7._currentRenderer2 = null; + } + return context7; + } + var Uninitialized = -1; + var Pending = 0; + var Resolved = 1; + var Rejected = 2; + function lazyInitializer(payload) { + if (payload._status === Uninitialized) { + var ctor = payload._result; + var thenable = ctor(); + thenable.then(function(moduleObject2) { + if (payload._status === Pending || payload._status === Uninitialized) { + var resolved = payload; + resolved._status = Resolved; + resolved._result = moduleObject2; + } + }, function(error2) { + if (payload._status === Pending || payload._status === Uninitialized) { + var rejected = payload; + rejected._status = Rejected; + rejected._result = error2; + } + }); + if (payload._status === Uninitialized) { + var pending = payload; + pending._status = Pending; + pending._result = thenable; + } + } + if (payload._status === Resolved) { + var moduleObject = payload._result; + { + if (moduleObject === void 0) { + error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); + } + } + { + if (!("default" in moduleObject)) { + error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); + } + } + return moduleObject.default; + } else { + throw payload._result; + } + } + function lazy(ctor) { + var payload = { + // We use these fields to store the result. + _status: Uninitialized, + _result: ctor + }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: payload, + _init: lazyInitializer + }; + { + var defaultProps16; + var propTypes; + Object.defineProperties(lazyType, { + defaultProps: { + configurable: true, + get: function() { + return defaultProps16; + }, + set: function(newDefaultProps) { + error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + defaultProps16 = newDefaultProps; + Object.defineProperty(lazyType, "defaultProps", { + enumerable: true + }); + } + }, + propTypes: { + configurable: true, + get: function() { + return propTypes; + }, + set: function(newPropTypes) { + error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + propTypes = newPropTypes; + Object.defineProperty(lazyType, "propTypes", { + enumerable: true + }); + } + } + }); + } + return lazyType; + } + function forwardRef6(render) { + { + if (render != null && render.$$typeof === REACT_MEMO_TYPE) { + error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); + } else if (typeof render !== "function") { + error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render); + } else { + if (render.length !== 0 && render.length !== 2) { + error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); + } + } + if (render != null) { + if (render.defaultProps != null || render.propTypes != null) { + error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); + } + } + } + var elementType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render + }; + { + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (!render.name && !render.displayName) { + render.displayName = name; + } + } + }); + } + return elementType; + } + var REACT_MODULE_REFERENCE; + { + REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); + } + function isValidElementType(type) { + if (typeof type === "string" || typeof type === "function") { + return true; + } + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { + return true; + } + if (typeof type === "object" && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) { + return true; + } + } + return false; + } + function memo(type, compare) { + { + if (!isValidElementType(type)) { + error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); + } + } + var elementType = { + $$typeof: REACT_MEMO_TYPE, + type, + compare: compare === void 0 ? null : compare + }; + { + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (!type.name && !type.displayName) { + type.displayName = name; + } + } + }); + } + return elementType; + } + function resolveDispatcher() { + var dispatcher = ReactCurrentDispatcher.current; + { + if (dispatcher === null) { + error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); + } + } + return dispatcher; + } + function useContext4(Context2) { + var dispatcher = resolveDispatcher(); + { + if (Context2._context !== void 0) { + var realContext = Context2._context; + if (realContext.Consumer === Context2) { + error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); + } else if (realContext.Provider === Context2) { + error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); + } + } + } + return dispatcher.useContext(Context2); + } + function useState6(initialState) { + var dispatcher = resolveDispatcher(); + return dispatcher.useState(initialState); + } + function useReducer(reducer, initialArg, init) { + var dispatcher = resolveDispatcher(); + return dispatcher.useReducer(reducer, initialArg, init); + } + function useRef5(initialValue) { + var dispatcher = resolveDispatcher(); + return dispatcher.useRef(initialValue); + } + function useEffect9(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useEffect(create, deps); + } + function useInsertionEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useInsertionEffect(create, deps); + } + function useLayoutEffect3(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useLayoutEffect(create, deps); + } + function useCallback3(callback, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useCallback(callback, deps); + } + function useMemo3(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useMemo(create, deps); + } + function useImperativeHandle(ref, create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useImperativeHandle(ref, create, deps); + } + function useDebugValue(value, formatterFn) { + { + var dispatcher = resolveDispatcher(); + return dispatcher.useDebugValue(value, formatterFn); + } + } + function useTransition() { + var dispatcher = resolveDispatcher(); + return dispatcher.useTransition(); + } + function useDeferredValue(value) { + var dispatcher = resolveDispatcher(); + return dispatcher.useDeferredValue(value); + } + function useId2() { + var dispatcher = resolveDispatcher(); + return dispatcher.useId(); + } + function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var dispatcher = resolveDispatcher(); + return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + } + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() { + } + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true + }; + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + } + if (disabledDepth < 0) { + error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + } + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === void 0) { + try { + throw Error(); + } catch (x2) { + var match = x2.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ""; + } + } + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== void 0) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + try { + if (construct) { + var Fake = function() { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function() { + throw Error(); + } + }); + if (typeof Reflect === "object" && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x2) { + control = x2; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x2) { + control = x2; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x2) { + control = x2; + } + fn(); + } + } catch (sample) { + if (sample && control && typeof sample.stack === "string") { + var sampleLines = sample.stack.split("\n"); + var controlLines = control.stack.split("\n"); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + c--; + } + for (; s >= 1 && c >= 0; s--, c--) { + if (sampleLines[s] !== controlLines[c]) { + if (s !== 1 || c !== 1) { + do { + s--; + c--; + if (c < 0 || sampleLines[s] !== controlLines[c]) { + var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); + if (fn.displayName && _frame.includes("")) { + _frame = _frame.replace("", fn.displayName); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } + return _frame; + } + } while (s >= 1 && c >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + function shouldConstruct(Component3) { + var prototype = Component3.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) { + return ""; + } + if (typeof type === "function") { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + if (typeof type === "string") { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame("Suspense"); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame("SuspenseList"); + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x2) { + } + } + } + } + return ""; + } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + function checkPropTypes(typeSpecs, values2, location, componentName, element) { + { + var has = Function.call.bind(hasOwnProperty2); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); + err.name = "Invariant Violation"; + throw err; + } + error$1 = typeSpecs[typeSpecName](values2, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); + setCurrentlyValidatingElement(null); + } + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error("Failed %s type: %s", location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } + } + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + setExtraStackFrame(stack); + } else { + setExtraStackFrame(null); + } + } + } + var propTypesMisspellWarningShown; + { + propTypesMisspellWarningShown = false; + } + function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = getComponentNameFromType(ReactCurrentOwner.current.type); + if (name) { + return "\n\nCheck the render method of `" + name + "`."; + } + } + return ""; + } + function getSourceInfoErrorAddendum(source) { + if (source !== void 0) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ""); + var lineNumber = source.lineNumber; + return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; + } + return ""; + } + function getSourceInfoErrorAddendumForProps(elementProps) { + if (elementProps !== null && elementProps !== void 0) { + return getSourceInfoErrorAddendum(elementProps.__source); + } + return ""; + } + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + return info; + } + function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + var childOwner = ""; + if (element && element._owner && element._owner !== ReactCurrentOwner.current) { + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + { + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); + } + } + function validateChildKeys(node, parentType) { + if (typeof node !== "object") { + return; + } + if (isArray2(node)) { + for (var i = 0; i < node.length; i++) { + var child = node[i]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === "function") { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + function validatePropTypes(element) { + { + var type = element.type; + if (type === null || type === void 0 || typeof type === "string") { + return; + } + var propTypes; + if (typeof type === "function") { + propTypes = type.propTypes; + } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, "prop", name, element); + } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; + var _name = getComponentNameFromType(type); + error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); + } + if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { + error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + } + } + function validateFragmentProps(fragment) { + { + var keys2 = Object.keys(fragment.props); + for (var i = 0; i < keys2.length; i++) { + var key = keys2[i]; + if (key !== "children" && key !== "key") { + setCurrentlyValidatingElement$1(fragment); + error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error("Invalid attribute `ref` supplied to `React.Fragment`."); + setCurrentlyValidatingElement$1(null); + } + } + } + function createElementWithValidation(type, props, children) { + var validType = isValidElementType(type); + if (!validType) { + var info = ""; + if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { + info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; + } + var sourceInfo = getSourceInfoErrorAddendumForProps(props); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = "null"; + } else if (isArray2(type)) { + typeString = "array"; + } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; + info = " Did you accidentally export a JSX literal instead of a component?"; + } else { + typeString = typeof type; + } + { + error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); + } + } + var element = createElement6.apply(this, arguments); + if (element == null) { + return element; + } + if (validType) { + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], type); + } + } + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; + } + var didWarnAboutDeprecatedCreateFactory = false; + function createFactoryWithValidation(type) { + var validatedFactory = createElementWithValidation.bind(null, type); + validatedFactory.type = type; + { + if (!didWarnAboutDeprecatedCreateFactory) { + didWarnAboutDeprecatedCreateFactory = true; + warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); + } + Object.defineProperty(validatedFactory, "type", { + enumerable: false, + get: function() { + warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); + Object.defineProperty(this, "type", { + value: type + }); + return type; + } + }); + } + return validatedFactory; + } + function cloneElementWithValidation(element, props, children) { + var newElement = cloneElement3.apply(this, arguments); + for (var i = 2; i < arguments.length; i++) { + validateChildKeys(arguments[i], newElement.type); + } + validatePropTypes(newElement); + return newElement; + } + function startTransition2(scope, options) { + var prevTransition = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = {}; + var currentTransition = ReactCurrentBatchConfig.transition; + { + ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set(); + } + try { + scope(); + } finally { + ReactCurrentBatchConfig.transition = prevTransition; + { + if (prevTransition === null && currentTransition._updatedFibers) { + var updatedFibersCount = currentTransition._updatedFibers.size; + if (updatedFibersCount > 10) { + warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); + } + currentTransition._updatedFibers.clear(); + } + } + } + } + var didWarnAboutMessageChannel = false; + var enqueueTaskImpl = null; + function enqueueTask(task) { + if (enqueueTaskImpl === null) { + try { + var requireString = ("require" + Math.random()).slice(0, 7); + var nodeRequire = module && module[requireString]; + enqueueTaskImpl = nodeRequire.call(module, "timers").setImmediate; + } catch (_err) { + enqueueTaskImpl = function(callback) { + { + if (didWarnAboutMessageChannel === false) { + didWarnAboutMessageChannel = true; + if (typeof MessageChannel === "undefined") { + error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); + } + } + } + var channel = new MessageChannel(); + channel.port1.onmessage = callback; + channel.port2.postMessage(void 0); + }; + } + } + return enqueueTaskImpl(task); + } + var actScopeDepth = 0; + var didWarnNoAwaitAct = false; + function act(callback) { + { + var prevActScopeDepth = actScopeDepth; + actScopeDepth++; + if (ReactCurrentActQueue.current === null) { + ReactCurrentActQueue.current = []; + } + var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; + var result; + try { + ReactCurrentActQueue.isBatchingLegacy = true; + result = callback(); + if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { + var queue = ReactCurrentActQueue.current; + if (queue !== null) { + ReactCurrentActQueue.didScheduleLegacyUpdate = false; + flushActQueue(queue); + } + } + } catch (error2) { + popActScope(prevActScopeDepth); + throw error2; + } finally { + ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; + } + if (result !== null && typeof result === "object" && typeof result.then === "function") { + var thenableResult = result; + var wasAwaited = false; + var thenable = { + then: function(resolve, reject) { + wasAwaited = true; + thenableResult.then(function(returnValue2) { + popActScope(prevActScopeDepth); + if (actScopeDepth === 0) { + recursivelyFlushAsyncActWork(returnValue2, resolve, reject); + } else { + resolve(returnValue2); + } + }, function(error2) { + popActScope(prevActScopeDepth); + reject(error2); + }); + } + }; + { + if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { + Promise.resolve().then(function() { + }).then(function() { + if (!wasAwaited) { + didWarnNoAwaitAct = true; + error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); + } + }); + } + } + return thenable; + } else { + var returnValue = result; + popActScope(prevActScopeDepth); + if (actScopeDepth === 0) { + var _queue = ReactCurrentActQueue.current; + if (_queue !== null) { + flushActQueue(_queue); + ReactCurrentActQueue.current = null; + } + var _thenable = { + then: function(resolve, reject) { + if (ReactCurrentActQueue.current === null) { + ReactCurrentActQueue.current = []; + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + } + }; + return _thenable; + } else { + var _thenable2 = { + then: function(resolve, reject) { + resolve(returnValue); + } + }; + return _thenable2; + } + } + } + } + function popActScope(prevActScopeDepth) { + { + if (prevActScopeDepth !== actScopeDepth - 1) { + error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); + } + actScopeDepth = prevActScopeDepth; + } + } + function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { + { + var queue = ReactCurrentActQueue.current; + if (queue !== null) { + try { + flushActQueue(queue); + enqueueTask(function() { + if (queue.length === 0) { + ReactCurrentActQueue.current = null; + resolve(returnValue); + } else { + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } + }); + } catch (error2) { + reject(error2); + } + } else { + resolve(returnValue); + } + } + } + var isFlushing = false; + function flushActQueue(queue) { + { + if (!isFlushing) { + isFlushing = true; + var i = 0; + try { + for (; i < queue.length; i++) { + var callback = queue[i]; + do { + callback = callback(true); + } while (callback !== null); + } + queue.length = 0; + } catch (error2) { + queue = queue.slice(i + 1); + throw error2; + } finally { + isFlushing = false; + } + } + } + } + var createElement$1 = createElementWithValidation; + var cloneElement$1 = cloneElementWithValidation; + var createFactory2 = createFactoryWithValidation; + var Children4 = { + map: mapChildren, + forEach: forEachChildren, + count: countChildren, + toArray, + only: onlyChild + }; + exports.Children = Children4; + exports.Component = Component2; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.Profiler = REACT_PROFILER_TYPE; + exports.PureComponent = PureComponent; + exports.StrictMode = REACT_STRICT_MODE_TYPE; + exports.Suspense = REACT_SUSPENSE_TYPE; + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; + exports.act = act; + exports.cloneElement = cloneElement$1; + exports.createContext = createContext4; + exports.createElement = createElement$1; + exports.createFactory = createFactory2; + exports.createRef = createRef; + exports.forwardRef = forwardRef6; + exports.isValidElement = isValidElement; + exports.lazy = lazy; + exports.memo = memo; + exports.startTransition = startTransition2; + exports.unstable_act = act; + exports.useCallback = useCallback3; + exports.useContext = useContext4; + exports.useDebugValue = useDebugValue; + exports.useDeferredValue = useDeferredValue; + exports.useEffect = useEffect9; + exports.useId = useId2; + exports.useImperativeHandle = useImperativeHandle; + exports.useInsertionEffect = useInsertionEffect; + exports.useLayoutEffect = useLayoutEffect3; + exports.useMemo = useMemo3; + exports.useReducer = useReducer; + exports.useRef = useRef5; + exports.useState = useState6; + exports.useSyncExternalStore = useSyncExternalStore; + exports.useTransition = useTransition; + exports.version = ReactVersion; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); + } + })(); + } + } +}); + +// node_modules/.pnpm/react@18.3.1/node_modules/react/index.js +var require_react = __commonJS({ + "node_modules/.pnpm/react@18.3.1/node_modules/react/index.js"(exports, module) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + if (false) { + module.exports = null; + } else { + module.exports = require_react_development(); + } + } +}); + +// node_modules/.pnpm/react-dom@18.3.1_react@18.3.1/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js +var require_react_dom_server_legacy_browser_development = __commonJS({ + "node_modules/.pnpm/react-dom@18.3.1_react@18.3.1/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js"(exports) { + "use strict"; + init_checked_fetch(); + init_modules_watch_stub(); + if (true) { + (function() { + "use strict"; + var React9 = require_react(); + var ReactVersion = "18.3.1"; + var ReactSharedInternals = React9.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + printWarning("warn", format, args); + } + } + } + function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning("error", format, args); + } + } + } + function printWarning(level, format, args) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + function scheduleWork(callback) { + callback(); + } + function beginWriting(destination) { + } + function writeChunk(destination, chunk) { + writeChunkAndReturn(destination, chunk); + } + function writeChunkAndReturn(destination, chunk) { + return destination.push(chunk); + } + function completeWriting(destination) { + } + function close(destination) { + destination.push(null); + } + function stringToChunk(content) { + return content; + } + function stringToPrecomputedChunk(content) { + return content; + } + function closeWithError(destination, error2) { + destination.destroy(error2); + } + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + function testStringCoercion(value) { + return "" + value; + } + function checkAttributeStringCoercion(value, attributeName) { + { + if (willCoercionThrow(value)) { + error("The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before before using it here.", attributeName, typeName(value)); + return testStringCoercion(value); + } + } + } + function checkCSSPropertyStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error("The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); + return testStringCoercion(value); + } + } + } + function checkHtmlStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + var hasOwnProperty2 = Object.prototype.hasOwnProperty; + var RESERVED = 0; + var STRING = 1; + var BOOLEANISH_STRING = 2; + var BOOLEAN = 3; + var OVERLOADED_BOOLEAN = 4; + var NUMERIC = 5; + var POSITIVE_NUMERIC = 6; + var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; + var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; + var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$"); + var illegalAttributeNameCache = {}; + var validatedAttributeNameCache = {}; + function isAttributeNameSafe(attributeName) { + if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName)) { + return true; + } + if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName)) { + return false; + } + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + illegalAttributeNameCache[attributeName] = true; + { + error("Invalid attribute name: `%s`", attributeName); + } + return false; + } + function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } + switch (typeof value) { + case "function": + case "symbol": + return true; + case "boolean": { + if (isCustomComponentTag) { + return false; + } + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix2 = name.toLowerCase().slice(0, 5); + return prefix2 !== "data-" && prefix2 !== "aria-"; + } + } + default: + return false; + } + } + function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; + } + function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; + this.sanitizeURL = sanitizeURL2; + this.removeEmptyString = removeEmptyString; + } + var properties = {}; + var reservedProps = [ + "children", + "dangerouslySetInnerHTML", + // TODO: This prevents the assignment of defaultValue to regular + // elements (not just inputs). Now that ReactDOMInput assigns to the + // defaultValue property -- do we need this? + "defaultValue", + "defaultChecked", + "innerHTML", + "suppressContentEditableWarning", + "suppressHydrationWarning", + "style" + ]; + reservedProps.forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + RESERVED, + false, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) { + var name = _ref[0], attributeName = _ref[1]; + properties[name] = new PropertyInfoRecord( + name, + STRING, + false, + // mustUseProperty + attributeName, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + BOOLEANISH_STRING, + false, + // mustUseProperty + name.toLowerCase(), + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + BOOLEANISH_STRING, + false, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "allowFullScreen", + "async", + // Note: there is a special case that prevents it from being written to the DOM + // on the client side because the browsers are inconsistent. Instead we call focus(). + "autoFocus", + "autoPlay", + "controls", + "default", + "defer", + "disabled", + "disablePictureInPicture", + "disableRemotePlayback", + "formNoValidate", + "hidden", + "loop", + "noModule", + "noValidate", + "open", + "playsInline", + "readOnly", + "required", + "reversed", + "scoped", + "seamless", + // Microdata + "itemScope" + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + BOOLEAN, + false, + // mustUseProperty + name.toLowerCase(), + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "checked", + // Note: `option.selected` is not updated if `select.multiple` is + // disabled with `removeAttribute`. We have special logic for handling this. + "multiple", + "muted", + "selected" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + BOOLEAN, + true, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "capture", + "download" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + OVERLOADED_BOOLEAN, + false, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "cols", + "rows", + "size", + "span" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + POSITIVE_NUMERIC, + false, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + ["rowSpan", "start"].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + NUMERIC, + false, + // mustUseProperty + name.toLowerCase(), + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + var CAMELIZE = /[\-\:]([a-z])/g; + var capitalize = function(token) { + return token[1].toUpperCase(); + }; + [ + "accent-height", + "alignment-baseline", + "arabic-form", + "baseline-shift", + "cap-height", + "clip-path", + "clip-rule", + "color-interpolation", + "color-interpolation-filters", + "color-profile", + "color-rendering", + "dominant-baseline", + "enable-background", + "fill-opacity", + "fill-rule", + "flood-color", + "flood-opacity", + "font-family", + "font-size", + "font-size-adjust", + "font-stretch", + "font-style", + "font-variant", + "font-weight", + "glyph-name", + "glyph-orientation-horizontal", + "glyph-orientation-vertical", + "horiz-adv-x", + "horiz-origin-x", + "image-rendering", + "letter-spacing", + "lighting-color", + "marker-end", + "marker-mid", + "marker-start", + "overline-position", + "overline-thickness", + "paint-order", + "panose-1", + "pointer-events", + "rendering-intent", + "shape-rendering", + "stop-color", + "stop-opacity", + "strikethrough-position", + "strikethrough-thickness", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-opacity", + "stroke-width", + "text-anchor", + "text-decoration", + "text-rendering", + "underline-position", + "underline-thickness", + "unicode-bidi", + "unicode-range", + "units-per-em", + "v-alphabetic", + "v-hanging", + "v-ideographic", + "v-mathematical", + "vector-effect", + "vert-adv-y", + "vert-origin-x", + "vert-origin-y", + "word-spacing", + "writing-mode", + "xmlns:xlink", + "x-height" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord( + name, + STRING, + false, + // mustUseProperty + attributeName, + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "xlink:actuate", + "xlink:arcrole", + "xlink:role", + "xlink:show", + "xlink:title", + "xlink:type" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord( + name, + STRING, + false, + // mustUseProperty + attributeName, + "http://www.w3.org/1999/xlink", + false, + // sanitizeURL + false + ); + }); + [ + "xml:base", + "xml:lang", + "xml:space" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord( + name, + STRING, + false, + // mustUseProperty + attributeName, + "http://www.w3.org/XML/1998/namespace", + false, + // sanitizeURL + false + ); + }); + ["tabIndex", "crossOrigin"].forEach(function(attributeName) { + properties[attributeName] = new PropertyInfoRecord( + attributeName, + STRING, + false, + // mustUseProperty + attributeName.toLowerCase(), + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + var xlinkHref = "xlinkHref"; + properties[xlinkHref] = new PropertyInfoRecord( + "xlinkHref", + STRING, + false, + // mustUseProperty + "xlink:href", + "http://www.w3.org/1999/xlink", + true, + // sanitizeURL + false + ); + ["src", "href", "action", "formAction"].forEach(function(attributeName) { + properties[attributeName] = new PropertyInfoRecord( + attributeName, + STRING, + false, + // mustUseProperty + attributeName.toLowerCase(), + // attributeName + null, + // attributeNamespace + true, + // sanitizeURL + true + ); + }); + var isUnitlessNumber = { + animationIterationCount: true, + aspectRatio: true, + borderImageOutset: true, + borderImageSlice: true, + borderImageWidth: true, + boxFlex: true, + boxFlexGroup: true, + boxOrdinalGroup: true, + columnCount: true, + columns: true, + flex: true, + flexGrow: true, + flexPositive: true, + flexShrink: true, + flexNegative: true, + flexOrder: true, + gridArea: true, + gridRow: true, + gridRowEnd: true, + gridRowSpan: true, + gridRowStart: true, + gridColumn: true, + gridColumnEnd: true, + gridColumnSpan: true, + gridColumnStart: true, + fontWeight: true, + lineClamp: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + tabSize: true, + widows: true, + zIndex: true, + zoom: true, + // SVG-related properties + fillOpacity: true, + floodOpacity: true, + stopOpacity: true, + strokeDasharray: true, + strokeDashoffset: true, + strokeMiterlimit: true, + strokeOpacity: true, + strokeWidth: true + }; + function prefixKey(prefix2, key) { + return prefix2 + key.charAt(0).toUpperCase() + key.substring(1); + } + var prefixes = ["Webkit", "ms", "Moz", "O"]; + Object.keys(isUnitlessNumber).forEach(function(prop) { + prefixes.forEach(function(prefix2) { + isUnitlessNumber[prefixKey(prefix2, prop)] = isUnitlessNumber[prop]; + }); + }); + var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true + }; + function checkControlledValueProps(tagName, props) { + { + if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { + error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."); + } + if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { + error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."); + } + } + } + function isCustomComponent(tagName, props) { + if (tagName.indexOf("-") === -1) { + return typeof props.is === "string"; + } + switch (tagName) { + case "annotation-xml": + case "color-profile": + case "font-face": + case "font-face-src": + case "font-face-uri": + case "font-face-format": + case "font-face-name": + case "missing-glyph": + return false; + default: + return true; + } + } + var ariaProperties = { + "aria-current": 0, + // state + "aria-description": 0, + "aria-details": 0, + "aria-disabled": 0, + // state + "aria-hidden": 0, + // state + "aria-invalid": 0, + // state + "aria-keyshortcuts": 0, + "aria-label": 0, + "aria-roledescription": 0, + // Widget Attributes + "aria-autocomplete": 0, + "aria-checked": 0, + "aria-expanded": 0, + "aria-haspopup": 0, + "aria-level": 0, + "aria-modal": 0, + "aria-multiline": 0, + "aria-multiselectable": 0, + "aria-orientation": 0, + "aria-placeholder": 0, + "aria-pressed": 0, + "aria-readonly": 0, + "aria-required": 0, + "aria-selected": 0, + "aria-sort": 0, + "aria-valuemax": 0, + "aria-valuemin": 0, + "aria-valuenow": 0, + "aria-valuetext": 0, + // Live Region Attributes + "aria-atomic": 0, + "aria-busy": 0, + "aria-live": 0, + "aria-relevant": 0, + // Drag-and-Drop Attributes + "aria-dropeffect": 0, + "aria-grabbed": 0, + // Relationship Attributes + "aria-activedescendant": 0, + "aria-colcount": 0, + "aria-colindex": 0, + "aria-colspan": 0, + "aria-controls": 0, + "aria-describedby": 0, + "aria-errormessage": 0, + "aria-flowto": 0, + "aria-labelledby": 0, + "aria-owns": 0, + "aria-posinset": 0, + "aria-rowcount": 0, + "aria-rowindex": 0, + "aria-rowspan": 0, + "aria-setsize": 0 + }; + var warnedProperties = {}; + var rARIA = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$"); + var rARIACamel = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$"); + function validateProperty(tagName, name) { + { + if (hasOwnProperty2.call(warnedProperties, name) && warnedProperties[name]) { + return true; + } + if (rARIACamel.test(name)) { + var ariaName = "aria-" + name.slice(4).toLowerCase(); + var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; + if (correctName == null) { + error("Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.", name); + warnedProperties[name] = true; + return true; + } + if (name !== correctName) { + error("Invalid ARIA attribute `%s`. Did you mean `%s`?", name, correctName); + warnedProperties[name] = true; + return true; + } + } + if (rARIA.test(name)) { + var lowerCasedName = name.toLowerCase(); + var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; + if (standardName == null) { + warnedProperties[name] = true; + return false; + } + if (name !== standardName) { + error("Unknown ARIA attribute `%s`. Did you mean `%s`?", name, standardName); + warnedProperties[name] = true; + return true; + } + } + } + return true; + } + function warnInvalidARIAProps(type, props) { + { + var invalidProps = []; + for (var key in props) { + var isValid = validateProperty(type, key); + if (!isValid) { + invalidProps.push(key); + } + } + var unknownPropString = invalidProps.map(function(prop) { + return "`" + prop + "`"; + }).join(", "); + if (invalidProps.length === 1) { + error("Invalid aria prop %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type); + } else if (invalidProps.length > 1) { + error("Invalid aria props %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type); + } + } + } + function validateProperties(type, props) { + if (isCustomComponent(type, props)) { + return; + } + warnInvalidARIAProps(type, props); + } + var didWarnValueNull = false; + function validateProperties$1(type, props) { + { + if (type !== "input" && type !== "textarea" && type !== "select") { + return; + } + if (props != null && props.value === null && !didWarnValueNull) { + didWarnValueNull = true; + if (type === "select" && props.multiple) { + error("`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.", type); + } else { + error("`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.", type); + } + } + } + } + var possibleStandardNames = { + // HTML + accept: "accept", + acceptcharset: "acceptCharset", + "accept-charset": "acceptCharset", + accesskey: "accessKey", + action: "action", + allowfullscreen: "allowFullScreen", + alt: "alt", + as: "as", + async: "async", + autocapitalize: "autoCapitalize", + autocomplete: "autoComplete", + autocorrect: "autoCorrect", + autofocus: "autoFocus", + autoplay: "autoPlay", + autosave: "autoSave", + capture: "capture", + cellpadding: "cellPadding", + cellspacing: "cellSpacing", + challenge: "challenge", + charset: "charSet", + checked: "checked", + children: "children", + cite: "cite", + class: "className", + classid: "classID", + classname: "className", + cols: "cols", + colspan: "colSpan", + content: "content", + contenteditable: "contentEditable", + contextmenu: "contextMenu", + controls: "controls", + controlslist: "controlsList", + coords: "coords", + crossorigin: "crossOrigin", + dangerouslysetinnerhtml: "dangerouslySetInnerHTML", + data: "data", + datetime: "dateTime", + default: "default", + defaultchecked: "defaultChecked", + defaultvalue: "defaultValue", + defer: "defer", + dir: "dir", + disabled: "disabled", + disablepictureinpicture: "disablePictureInPicture", + disableremoteplayback: "disableRemotePlayback", + download: "download", + draggable: "draggable", + enctype: "encType", + enterkeyhint: "enterKeyHint", + for: "htmlFor", + form: "form", + formmethod: "formMethod", + formaction: "formAction", + formenctype: "formEncType", + formnovalidate: "formNoValidate", + formtarget: "formTarget", + frameborder: "frameBorder", + headers: "headers", + height: "height", + hidden: "hidden", + high: "high", + href: "href", + hreflang: "hrefLang", + htmlfor: "htmlFor", + httpequiv: "httpEquiv", + "http-equiv": "httpEquiv", + icon: "icon", + id: "id", + imagesizes: "imageSizes", + imagesrcset: "imageSrcSet", + innerhtml: "innerHTML", + inputmode: "inputMode", + integrity: "integrity", + is: "is", + itemid: "itemID", + itemprop: "itemProp", + itemref: "itemRef", + itemscope: "itemScope", + itemtype: "itemType", + keyparams: "keyParams", + keytype: "keyType", + kind: "kind", + label: "label", + lang: "lang", + list: "list", + loop: "loop", + low: "low", + manifest: "manifest", + marginwidth: "marginWidth", + marginheight: "marginHeight", + max: "max", + maxlength: "maxLength", + media: "media", + mediagroup: "mediaGroup", + method: "method", + min: "min", + minlength: "minLength", + multiple: "multiple", + muted: "muted", + name: "name", + nomodule: "noModule", + nonce: "nonce", + novalidate: "noValidate", + open: "open", + optimum: "optimum", + pattern: "pattern", + placeholder: "placeholder", + playsinline: "playsInline", + poster: "poster", + preload: "preload", + profile: "profile", + radiogroup: "radioGroup", + readonly: "readOnly", + referrerpolicy: "referrerPolicy", + rel: "rel", + required: "required", + reversed: "reversed", + role: "role", + rows: "rows", + rowspan: "rowSpan", + sandbox: "sandbox", + scope: "scope", + scoped: "scoped", + scrolling: "scrolling", + seamless: "seamless", + selected: "selected", + shape: "shape", + size: "size", + sizes: "sizes", + span: "span", + spellcheck: "spellCheck", + src: "src", + srcdoc: "srcDoc", + srclang: "srcLang", + srcset: "srcSet", + start: "start", + step: "step", + style: "style", + summary: "summary", + tabindex: "tabIndex", + target: "target", + title: "title", + type: "type", + usemap: "useMap", + value: "value", + width: "width", + wmode: "wmode", + wrap: "wrap", + // SVG + about: "about", + accentheight: "accentHeight", + "accent-height": "accentHeight", + accumulate: "accumulate", + additive: "additive", + alignmentbaseline: "alignmentBaseline", + "alignment-baseline": "alignmentBaseline", + allowreorder: "allowReorder", + alphabetic: "alphabetic", + amplitude: "amplitude", + arabicform: "arabicForm", + "arabic-form": "arabicForm", + ascent: "ascent", + attributename: "attributeName", + attributetype: "attributeType", + autoreverse: "autoReverse", + azimuth: "azimuth", + basefrequency: "baseFrequency", + baselineshift: "baselineShift", + "baseline-shift": "baselineShift", + baseprofile: "baseProfile", + bbox: "bbox", + begin: "begin", + bias: "bias", + by: "by", + calcmode: "calcMode", + capheight: "capHeight", + "cap-height": "capHeight", + clip: "clip", + clippath: "clipPath", + "clip-path": "clipPath", + clippathunits: "clipPathUnits", + cliprule: "clipRule", + "clip-rule": "clipRule", + color: "color", + colorinterpolation: "colorInterpolation", + "color-interpolation": "colorInterpolation", + colorinterpolationfilters: "colorInterpolationFilters", + "color-interpolation-filters": "colorInterpolationFilters", + colorprofile: "colorProfile", + "color-profile": "colorProfile", + colorrendering: "colorRendering", + "color-rendering": "colorRendering", + contentscripttype: "contentScriptType", + contentstyletype: "contentStyleType", + cursor: "cursor", + cx: "cx", + cy: "cy", + d: "d", + datatype: "datatype", + decelerate: "decelerate", + descent: "descent", + diffuseconstant: "diffuseConstant", + direction: "direction", + display: "display", + divisor: "divisor", + dominantbaseline: "dominantBaseline", + "dominant-baseline": "dominantBaseline", + dur: "dur", + dx: "dx", + dy: "dy", + edgemode: "edgeMode", + elevation: "elevation", + enablebackground: "enableBackground", + "enable-background": "enableBackground", + end: "end", + exponent: "exponent", + externalresourcesrequired: "externalResourcesRequired", + fill: "fill", + fillopacity: "fillOpacity", + "fill-opacity": "fillOpacity", + fillrule: "fillRule", + "fill-rule": "fillRule", + filter: "filter", + filterres: "filterRes", + filterunits: "filterUnits", + floodopacity: "floodOpacity", + "flood-opacity": "floodOpacity", + floodcolor: "floodColor", + "flood-color": "floodColor", + focusable: "focusable", + fontfamily: "fontFamily", + "font-family": "fontFamily", + fontsize: "fontSize", + "font-size": "fontSize", + fontsizeadjust: "fontSizeAdjust", + "font-size-adjust": "fontSizeAdjust", + fontstretch: "fontStretch", + "font-stretch": "fontStretch", + fontstyle: "fontStyle", + "font-style": "fontStyle", + fontvariant: "fontVariant", + "font-variant": "fontVariant", + fontweight: "fontWeight", + "font-weight": "fontWeight", + format: "format", + from: "from", + fx: "fx", + fy: "fy", + g1: "g1", + g2: "g2", + glyphname: "glyphName", + "glyph-name": "glyphName", + glyphorientationhorizontal: "glyphOrientationHorizontal", + "glyph-orientation-horizontal": "glyphOrientationHorizontal", + glyphorientationvertical: "glyphOrientationVertical", + "glyph-orientation-vertical": "glyphOrientationVertical", + glyphref: "glyphRef", + gradienttransform: "gradientTransform", + gradientunits: "gradientUnits", + hanging: "hanging", + horizadvx: "horizAdvX", + "horiz-adv-x": "horizAdvX", + horizoriginx: "horizOriginX", + "horiz-origin-x": "horizOriginX", + ideographic: "ideographic", + imagerendering: "imageRendering", + "image-rendering": "imageRendering", + in2: "in2", + in: "in", + inlist: "inlist", + intercept: "intercept", + k1: "k1", + k2: "k2", + k3: "k3", + k4: "k4", + k: "k", + kernelmatrix: "kernelMatrix", + kernelunitlength: "kernelUnitLength", + kerning: "kerning", + keypoints: "keyPoints", + keysplines: "keySplines", + keytimes: "keyTimes", + lengthadjust: "lengthAdjust", + letterspacing: "letterSpacing", + "letter-spacing": "letterSpacing", + lightingcolor: "lightingColor", + "lighting-color": "lightingColor", + limitingconeangle: "limitingConeAngle", + local: "local", + markerend: "markerEnd", + "marker-end": "markerEnd", + markerheight: "markerHeight", + markermid: "markerMid", + "marker-mid": "markerMid", + markerstart: "markerStart", + "marker-start": "markerStart", + markerunits: "markerUnits", + markerwidth: "markerWidth", + mask: "mask", + maskcontentunits: "maskContentUnits", + maskunits: "maskUnits", + mathematical: "mathematical", + mode: "mode", + numoctaves: "numOctaves", + offset: "offset", + opacity: "opacity", + operator: "operator", + order: "order", + orient: "orient", + orientation: "orientation", + origin: "origin", + overflow: "overflow", + overlineposition: "overlinePosition", + "overline-position": "overlinePosition", + overlinethickness: "overlineThickness", + "overline-thickness": "overlineThickness", + paintorder: "paintOrder", + "paint-order": "paintOrder", + panose1: "panose1", + "panose-1": "panose1", + pathlength: "pathLength", + patterncontentunits: "patternContentUnits", + patterntransform: "patternTransform", + patternunits: "patternUnits", + pointerevents: "pointerEvents", + "pointer-events": "pointerEvents", + points: "points", + pointsatx: "pointsAtX", + pointsaty: "pointsAtY", + pointsatz: "pointsAtZ", + prefix: "prefix", + preservealpha: "preserveAlpha", + preserveaspectratio: "preserveAspectRatio", + primitiveunits: "primitiveUnits", + property: "property", + r: "r", + radius: "radius", + refx: "refX", + refy: "refY", + renderingintent: "renderingIntent", + "rendering-intent": "renderingIntent", + repeatcount: "repeatCount", + repeatdur: "repeatDur", + requiredextensions: "requiredExtensions", + requiredfeatures: "requiredFeatures", + resource: "resource", + restart: "restart", + result: "result", + results: "results", + rotate: "rotate", + rx: "rx", + ry: "ry", + scale: "scale", + security: "security", + seed: "seed", + shaperendering: "shapeRendering", + "shape-rendering": "shapeRendering", + slope: "slope", + spacing: "spacing", + specularconstant: "specularConstant", + specularexponent: "specularExponent", + speed: "speed", + spreadmethod: "spreadMethod", + startoffset: "startOffset", + stddeviation: "stdDeviation", + stemh: "stemh", + stemv: "stemv", + stitchtiles: "stitchTiles", + stopcolor: "stopColor", + "stop-color": "stopColor", + stopopacity: "stopOpacity", + "stop-opacity": "stopOpacity", + strikethroughposition: "strikethroughPosition", + "strikethrough-position": "strikethroughPosition", + strikethroughthickness: "strikethroughThickness", + "strikethrough-thickness": "strikethroughThickness", + string: "string", + stroke: "stroke", + strokedasharray: "strokeDasharray", + "stroke-dasharray": "strokeDasharray", + strokedashoffset: "strokeDashoffset", + "stroke-dashoffset": "strokeDashoffset", + strokelinecap: "strokeLinecap", + "stroke-linecap": "strokeLinecap", + strokelinejoin: "strokeLinejoin", + "stroke-linejoin": "strokeLinejoin", + strokemiterlimit: "strokeMiterlimit", + "stroke-miterlimit": "strokeMiterlimit", + strokewidth: "strokeWidth", + "stroke-width": "strokeWidth", + strokeopacity: "strokeOpacity", + "stroke-opacity": "strokeOpacity", + suppresscontenteditablewarning: "suppressContentEditableWarning", + suppresshydrationwarning: "suppressHydrationWarning", + surfacescale: "surfaceScale", + systemlanguage: "systemLanguage", + tablevalues: "tableValues", + targetx: "targetX", + targety: "targetY", + textanchor: "textAnchor", + "text-anchor": "textAnchor", + textdecoration: "textDecoration", + "text-decoration": "textDecoration", + textlength: "textLength", + textrendering: "textRendering", + "text-rendering": "textRendering", + to: "to", + transform: "transform", + typeof: "typeof", + u1: "u1", + u2: "u2", + underlineposition: "underlinePosition", + "underline-position": "underlinePosition", + underlinethickness: "underlineThickness", + "underline-thickness": "underlineThickness", + unicode: "unicode", + unicodebidi: "unicodeBidi", + "unicode-bidi": "unicodeBidi", + unicoderange: "unicodeRange", + "unicode-range": "unicodeRange", + unitsperem: "unitsPerEm", + "units-per-em": "unitsPerEm", + unselectable: "unselectable", + valphabetic: "vAlphabetic", + "v-alphabetic": "vAlphabetic", + values: "values", + vectoreffect: "vectorEffect", + "vector-effect": "vectorEffect", + version: "version", + vertadvy: "vertAdvY", + "vert-adv-y": "vertAdvY", + vertoriginx: "vertOriginX", + "vert-origin-x": "vertOriginX", + vertoriginy: "vertOriginY", + "vert-origin-y": "vertOriginY", + vhanging: "vHanging", + "v-hanging": "vHanging", + videographic: "vIdeographic", + "v-ideographic": "vIdeographic", + viewbox: "viewBox", + viewtarget: "viewTarget", + visibility: "visibility", + vmathematical: "vMathematical", + "v-mathematical": "vMathematical", + vocab: "vocab", + widths: "widths", + wordspacing: "wordSpacing", + "word-spacing": "wordSpacing", + writingmode: "writingMode", + "writing-mode": "writingMode", + x1: "x1", + x2: "x2", + x: "x", + xchannelselector: "xChannelSelector", + xheight: "xHeight", + "x-height": "xHeight", + xlinkactuate: "xlinkActuate", + "xlink:actuate": "xlinkActuate", + xlinkarcrole: "xlinkArcrole", + "xlink:arcrole": "xlinkArcrole", + xlinkhref: "xlinkHref", + "xlink:href": "xlinkHref", + xlinkrole: "xlinkRole", + "xlink:role": "xlinkRole", + xlinkshow: "xlinkShow", + "xlink:show": "xlinkShow", + xlinktitle: "xlinkTitle", + "xlink:title": "xlinkTitle", + xlinktype: "xlinkType", + "xlink:type": "xlinkType", + xmlbase: "xmlBase", + "xml:base": "xmlBase", + xmllang: "xmlLang", + "xml:lang": "xmlLang", + xmlns: "xmlns", + "xml:space": "xmlSpace", + xmlnsxlink: "xmlnsXlink", + "xmlns:xlink": "xmlnsXlink", + xmlspace: "xmlSpace", + y1: "y1", + y2: "y2", + y: "y", + ychannelselector: "yChannelSelector", + z: "z", + zoomandpan: "zoomAndPan" + }; + var validateProperty$1 = function() { + }; + { + var warnedProperties$1 = {}; + var EVENT_NAME_REGEX = /^on./; + var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; + var rARIA$1 = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$"); + var rARIACamel$1 = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$"); + validateProperty$1 = function(tagName, name, value, eventRegistry) { + if (hasOwnProperty2.call(warnedProperties$1, name) && warnedProperties$1[name]) { + return true; + } + var lowerCasedName = name.toLowerCase(); + if (lowerCasedName === "onfocusin" || lowerCasedName === "onfocusout") { + error("React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React."); + warnedProperties$1[name] = true; + return true; + } + if (eventRegistry != null) { + var registrationNameDependencies = eventRegistry.registrationNameDependencies, possibleRegistrationNames = eventRegistry.possibleRegistrationNames; + if (registrationNameDependencies.hasOwnProperty(name)) { + return true; + } + var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null; + if (registrationName != null) { + error("Invalid event handler property `%s`. Did you mean `%s`?", name, registrationName); + warnedProperties$1[name] = true; + return true; + } + if (EVENT_NAME_REGEX.test(name)) { + error("Unknown event handler property `%s`. It will be ignored.", name); + warnedProperties$1[name] = true; + return true; + } + } else if (EVENT_NAME_REGEX.test(name)) { + if (INVALID_EVENT_NAME_REGEX.test(name)) { + error("Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.", name); + } + warnedProperties$1[name] = true; + return true; + } + if (rARIA$1.test(name) || rARIACamel$1.test(name)) { + return true; + } + if (lowerCasedName === "innerhtml") { + error("Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."); + warnedProperties$1[name] = true; + return true; + } + if (lowerCasedName === "aria") { + error("The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead."); + warnedProperties$1[name] = true; + return true; + } + if (lowerCasedName === "is" && value !== null && value !== void 0 && typeof value !== "string") { + error("Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.", typeof value); + warnedProperties$1[name] = true; + return true; + } + if (typeof value === "number" && isNaN(value)) { + error("Received NaN for the `%s` attribute. If this is expected, cast the value to a string.", name); + warnedProperties$1[name] = true; + return true; + } + var propertyInfo = getPropertyInfo(name); + var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; + if (possibleStandardNames.hasOwnProperty(lowerCasedName)) { + var standardName = possibleStandardNames[lowerCasedName]; + if (standardName !== name) { + error("Invalid DOM property `%s`. Did you mean `%s`?", name, standardName); + warnedProperties$1[name] = true; + return true; + } + } else if (!isReserved && name !== lowerCasedName) { + error("React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.", name, lowerCasedName); + warnedProperties$1[name] = true; + return true; + } + if (typeof value === "boolean" && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + if (value) { + error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.', value, name, name, value, name); + } else { + error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name); + } + warnedProperties$1[name] = true; + return true; + } + if (isReserved) { + return true; + } + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + warnedProperties$1[name] = true; + return false; + } + if ((value === "false" || value === "true") && propertyInfo !== null && propertyInfo.type === BOOLEAN) { + error("Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?", value, name, value === "false" ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".', name, value); + warnedProperties$1[name] = true; + return true; + } + return true; + }; + } + var warnUnknownProperties = function(type, props, eventRegistry) { + { + var unknownProps = []; + for (var key in props) { + var isValid = validateProperty$1(type, key, props[key], eventRegistry); + if (!isValid) { + unknownProps.push(key); + } + } + var unknownPropString = unknownProps.map(function(prop) { + return "`" + prop + "`"; + }).join(", "); + if (unknownProps.length === 1) { + error("Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type); + } else if (unknownProps.length > 1) { + error("Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type); + } + } + }; + function validateProperties$2(type, props, eventRegistry) { + if (isCustomComponent(type, props)) { + return; + } + warnUnknownProperties(type, props, eventRegistry); + } + var warnValidStyle = function() { + }; + { + var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; + var msPattern = /^-ms-/; + var hyphenPattern = /-(.)/g; + var badStyleValueWithSemicolonPattern = /;\s*$/; + var warnedStyleNames = {}; + var warnedStyleValues = {}; + var warnedForNaNValue = false; + var warnedForInfinityValue = false; + var camelize = function(string) { + return string.replace(hyphenPattern, function(_2, character) { + return character.toUpperCase(); + }); + }; + var warnHyphenatedStyleName = function(name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + warnedStyleNames[name] = true; + error( + "Unsupported style property %s. Did you mean %s?", + name, + // As Andi Smith suggests + // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix + // is converted to lowercase `ms`. + camelize(name.replace(msPattern, "ms-")) + ); + }; + var warnBadVendoredStyleName = function(name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + warnedStyleNames[name] = true; + error("Unsupported vendor-prefixed style property %s. Did you mean %s?", name, name.charAt(0).toUpperCase() + name.slice(1)); + }; + var warnStyleValueWithSemicolon = function(name, value) { + if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { + return; + } + warnedStyleValues[value] = true; + error(`Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`, name, value.replace(badStyleValueWithSemicolonPattern, "")); + }; + var warnStyleValueIsNaN = function(name, value) { + if (warnedForNaNValue) { + return; + } + warnedForNaNValue = true; + error("`NaN` is an invalid value for the `%s` css style property.", name); + }; + var warnStyleValueIsInfinity = function(name, value) { + if (warnedForInfinityValue) { + return; + } + warnedForInfinityValue = true; + error("`Infinity` is an invalid value for the `%s` css style property.", name); + }; + warnValidStyle = function(name, value) { + if (name.indexOf("-") > -1) { + warnHyphenatedStyleName(name); + } else if (badVendoredStyleNamePattern.test(name)) { + warnBadVendoredStyleName(name); + } else if (badStyleValueWithSemicolonPattern.test(value)) { + warnStyleValueWithSemicolon(name, value); + } + if (typeof value === "number") { + if (isNaN(value)) { + warnStyleValueIsNaN(name, value); + } else if (!isFinite(value)) { + warnStyleValueIsInfinity(name, value); + } + } + }; + } + var warnValidStyle$1 = warnValidStyle; + var matchHtmlRegExp = /["'&<>]/; + function escapeHtml(string) { + { + checkHtmlStringCoercion(string); + } + var str = "" + string; + var match = matchHtmlRegExp.exec(str); + if (!match) { + return str; + } + var escape; + var html = ""; + var index; + var lastIndex = 0; + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: + escape = """; + break; + case 38: + escape = "&"; + break; + case 39: + escape = "'"; + break; + case 60: + escape = "<"; + break; + case 62: + escape = ">"; + break; + default: + continue; + } + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + lastIndex = index + 1; + html += escape; + } + return lastIndex !== index ? html + str.substring(lastIndex, index) : html; + } + function escapeTextForBrowser(text2) { + if (typeof text2 === "boolean" || typeof text2 === "number") { + return "" + text2; + } + return escapeHtml(text2); + } + var uppercasePattern = /([A-Z])/g; + var msPattern$1 = /^ms-/; + function hyphenateStyleName(name) { + return name.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern$1, "-ms-"); + } + var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; + var didWarn = false; + function sanitizeURL(url) { + { + if (!didWarn && isJavaScriptProtocol.test(url)) { + didWarn = true; + error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url)); + } + } + } + var isArrayImpl = Array.isArray; + function isArray2(a2) { + return isArrayImpl(a2); + } + var startInlineScript = stringToPrecomputedChunk("');\nvar startScriptSrc = stringToPrecomputedChunk('');\n/**\n * This escaping function is designed to work with bootstrapScriptContent only.\n * because we know we are escaping the entire script. We can avoid for instance\n * escaping html comment string sequences that are valid javascript as well because\n * if there are no sebsequent ');\nfunction writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) {\n writeChunk(destination, responseState.startInlineScript);\n\n if (!responseState.sentCompleteSegmentFunction) {\n // The first time we write this, we'll need to include the full implementation.\n responseState.sentCompleteSegmentFunction = true;\n writeChunk(destination, completeSegmentScript1Full);\n } else {\n // Future calls can just reuse the same function.\n writeChunk(destination, completeSegmentScript1Partial);\n }\n\n writeChunk(destination, responseState.segmentPrefix);\n var formattedID = stringToChunk(contentSegmentID.toString(16));\n writeChunk(destination, formattedID);\n writeChunk(destination, completeSegmentScript2);\n writeChunk(destination, responseState.placeholderPrefix);\n writeChunk(destination, formattedID);\n return writeChunkAndReturn(destination, completeSegmentScript3);\n}\nvar completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC(\"');\nvar completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC(\"');\nvar completeBoundaryScript2 = stringToPrecomputedChunk('\",\"');\nvar completeBoundaryScript3 = stringToPrecomputedChunk('\")');\nfunction writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) {\n writeChunk(destination, responseState.startInlineScript);\n\n if (!responseState.sentCompleteBoundaryFunction) {\n // The first time we write this, we'll need to include the full implementation.\n responseState.sentCompleteBoundaryFunction = true;\n writeChunk(destination, completeBoundaryScript1Full);\n } else {\n // Future calls can just reuse the same function.\n writeChunk(destination, completeBoundaryScript1Partial);\n }\n\n if (boundaryID === null) {\n throw new Error('An ID must have been assigned before we can complete the boundary.');\n }\n\n var formattedContentID = stringToChunk(contentSegmentID.toString(16));\n writeChunk(destination, boundaryID);\n writeChunk(destination, completeBoundaryScript2);\n writeChunk(destination, responseState.segmentPrefix);\n writeChunk(destination, formattedContentID);\n return writeChunkAndReturn(destination, completeBoundaryScript3);\n}\nvar clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX(\"');\nvar clientRenderScript1Partial = stringToPrecomputedChunk('$RX(\"');\nvar clientRenderScript1A = stringToPrecomputedChunk('\"');\nvar clientRenderScript2 = stringToPrecomputedChunk(')');\nvar clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');\nfunction writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) {\n writeChunk(destination, responseState.startInlineScript);\n\n if (!responseState.sentClientRenderFunction) {\n // The first time we write this, we'll need to include the full implementation.\n responseState.sentClientRenderFunction = true;\n writeChunk(destination, clientRenderScript1Full);\n } else {\n // Future calls can just reuse the same function.\n writeChunk(destination, clientRenderScript1Partial);\n }\n\n if (boundaryID === null) {\n throw new Error('An ID must have been assigned before we can complete the boundary.');\n }\n\n writeChunk(destination, boundaryID);\n writeChunk(destination, clientRenderScript1A);\n\n if (errorDigest || errorMessage || errorComponentStack) {\n writeChunk(destination, clientRenderErrorScriptArgInterstitial);\n writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || '')));\n }\n\n if (errorMessage || errorComponentStack) {\n writeChunk(destination, clientRenderErrorScriptArgInterstitial);\n writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || '')));\n }\n\n if (errorComponentStack) {\n writeChunk(destination, clientRenderErrorScriptArgInterstitial);\n writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack)));\n }\n\n return writeChunkAndReturn(destination, clientRenderScript2);\n}\nvar regexForJSStringsInScripts = /[<\\u2028\\u2029]/g;\n\nfunction escapeJSStringsForInstructionScripts(input) {\n var escaped = JSON.stringify(input);\n return escaped.replace(regexForJSStringsInScripts, function (match) {\n switch (match) {\n // santizing breaking out of strings and script tags\n case '<':\n return \"\\\\u003c\";\n\n case \"\\u2028\":\n return \"\\\\u2028\";\n\n case \"\\u2029\":\n return \"\\\\u2029\";\n\n default:\n {\n // eslint-disable-next-line react-internal/prod-error-codes\n throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');\n }\n }\n });\n}\n\nfunction createResponseState$1(generateStaticMarkup, identifierPrefix) {\n var responseState = createResponseState(identifierPrefix, undefined);\n return {\n // Keep this in sync with ReactDOMServerFormatConfig\n bootstrapChunks: responseState.bootstrapChunks,\n startInlineScript: responseState.startInlineScript,\n placeholderPrefix: responseState.placeholderPrefix,\n segmentPrefix: responseState.segmentPrefix,\n boundaryPrefix: responseState.boundaryPrefix,\n idPrefix: responseState.idPrefix,\n nextSuspenseID: responseState.nextSuspenseID,\n sentCompleteSegmentFunction: responseState.sentCompleteSegmentFunction,\n sentCompleteBoundaryFunction: responseState.sentCompleteBoundaryFunction,\n sentClientRenderFunction: responseState.sentClientRenderFunction,\n // This is an extra field for the legacy renderer\n generateStaticMarkup: generateStaticMarkup\n };\n}\nfunction createRootFormatContext() {\n return {\n insertionMode: HTML_MODE,\n // We skip the root mode because we don't want to emit the DOCTYPE in legacy mode.\n selectedValue: null\n };\n}\nfunction pushTextInstance$1(target, text, responseState, textEmbedded) {\n if (responseState.generateStaticMarkup) {\n target.push(stringToChunk(escapeTextForBrowser(text)));\n return false;\n } else {\n return pushTextInstance(target, text, responseState, textEmbedded);\n }\n}\nfunction pushSegmentFinale$1(target, responseState, lastPushedText, textEmbedded) {\n if (responseState.generateStaticMarkup) {\n return;\n } else {\n return pushSegmentFinale(target, responseState, lastPushedText, textEmbedded);\n }\n}\nfunction writeStartCompletedSuspenseBoundary$1(destination, responseState) {\n if (responseState.generateStaticMarkup) {\n // A completed boundary is done and doesn't need a representation in the HTML\n // if we're not going to be hydrating it.\n return true;\n }\n\n return writeStartCompletedSuspenseBoundary(destination);\n}\nfunction writeStartClientRenderedSuspenseBoundary$1(destination, responseState, // flushing these error arguments are not currently supported in this legacy streaming format.\nerrorDigest, errorMessage, errorComponentStack) {\n if (responseState.generateStaticMarkup) {\n // A client rendered boundary is done and doesn't need a representation in the HTML\n // since we'll never hydrate it. This is arguably an error in static generation.\n return true;\n }\n\n return writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMessage, errorComponentStack);\n}\nfunction writeEndCompletedSuspenseBoundary$1(destination, responseState) {\n if (responseState.generateStaticMarkup) {\n return true;\n }\n\n return writeEndCompletedSuspenseBoundary(destination);\n}\nfunction writeEndClientRenderedSuspenseBoundary$1(destination, responseState) {\n if (responseState.generateStaticMarkup) {\n return true;\n }\n\n return writeEndClientRenderedSuspenseBoundary(destination);\n}\n\nvar assign = Object.assign;\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_SCOPE_TYPE = Symbol.for('react.scope');\nvar REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');\nvar REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');\nvar REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var displayName = outerType.displayName;\n\n if (displayName) {\n return displayName;\n }\n\n var functionName = innerType.displayName || innerType.name || '';\n return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return 'Profiler';\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n var context = type;\n return getContextName(context) + '.Consumer';\n\n case REACT_PROVIDER_TYPE:\n var provider = type;\n return getContextName(provider._context) + '.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n var outerName = type.displayName || null;\n\n if (outerName !== null) {\n return outerName;\n }\n\n return getComponentNameFromType(type.type) || 'Memo';\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n return getComponentNameFromType(init(payload));\n } catch (x) {\n return null;\n }\n }\n\n // eslint-disable-next-line no-fallthrough\n }\n }\n\n return null;\n}\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n {\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n prevLog = console.log;\n prevInfo = console.info;\n prevWarn = console.warn;\n prevError = console.error;\n prevGroup = console.group;\n prevGroupCollapsed = console.groupCollapsed;\n prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n var props = {\n configurable: true,\n enumerable: true,\n value: disabledLog,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n info: props,\n log: props,\n warn: props,\n error: props,\n group: props,\n groupCollapsed: props,\n groupEnd: props\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n disabledDepth++;\n }\n}\nfunction reenableLogs() {\n {\n disabledDepth--;\n\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n var props = {\n configurable: true,\n enumerable: true,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n log: assign({}, props, {\n value: prevLog\n }),\n info: assign({}, props, {\n value: prevInfo\n }),\n warn: assign({}, props, {\n value: prevWarn\n }),\n error: assign({}, props, {\n value: prevError\n }),\n group: assign({}, props, {\n value: prevGroup\n }),\n groupCollapsed: assign({}, props, {\n value: prevGroupCollapsed\n }),\n groupEnd: assign({}, props, {\n value: prevGroupEnd\n })\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n if (disabledDepth < 0) {\n error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n }\n }\n}\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n {\n if (prefix === undefined) {\n // Extract the VM specific prefix used by each line.\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = match && match[1] || '';\n }\n } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n return '\\n' + prefix + name;\n }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n // If something asked for a stack inside a fake render, it should get ignored.\n if ( !fn || reentry) {\n return '';\n }\n\n {\n var frame = componentFrameCache.get(fn);\n\n if (frame !== undefined) {\n return frame;\n }\n }\n\n var control;\n reentry = true;\n var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n Error.prepareStackTrace = undefined;\n var previousDispatcher;\n\n {\n previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function\n // for warnings.\n\n ReactCurrentDispatcher.current = null;\n disableLogs();\n }\n\n try {\n // This should throw.\n if (construct) {\n // Something should be setting the props in the constructor.\n var Fake = function () {\n throw Error();\n }; // $FlowFixMe\n\n\n Object.defineProperty(Fake.prototype, 'props', {\n set: function () {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n }\n });\n\n if (typeof Reflect === 'object' && Reflect.construct) {\n // We construct a different control for this case to include any extra\n // frames added by the construct call.\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n control = x;\n }\n\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x) {\n control = x;\n }\n\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x) {\n control = x;\n }\n\n fn();\n }\n } catch (sample) {\n // This is inlined manually because closure doesn't do it for us.\n if (sample && control && typeof sample.stack === 'string') {\n // This extracts the first frame from the sample that isn't also in the control.\n // Skipping one frame that we assume is the frame that calls the two.\n var sampleLines = sample.stack.split('\\n');\n var controlLines = control.stack.split('\\n');\n var s = sampleLines.length - 1;\n var c = controlLines.length - 1;\n\n while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n // We expect at least one stack frame to be shared.\n // Typically this will be the root most one. However, stack frames may be\n // cut off due to maximum stack limits. In this case, one maybe cut off\n // earlier than the other. We assume that the sample is longer or the same\n // and there for cut off earlier. So we should find the root most frame in\n // the sample somewhere in the control.\n c--;\n }\n\n for (; s >= 1 && c >= 0; s--, c--) {\n // Next we find the first one that isn't the same which should be the\n // frame that called our sample function and the control.\n if (sampleLines[s] !== controlLines[c]) {\n // In V8, the first line is describing the message but other VMs don't.\n // If we're about to return the first line, and the control is also on the same\n // line, that's a pretty good indicator that our sample threw at same line as\n // the control. I.e. before we entered the sample frame. So we ignore this result.\n // This can happen if you passed a class to function component, or non-function.\n if (s !== 1 || c !== 1) {\n do {\n s--;\n c--; // We may still have similar intermediate frames from the construct call.\n // The next one that isn't the same should be our match though.\n\n if (c < 0 || sampleLines[s] !== controlLines[c]) {\n // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"\"\n // but we have a user-provided \"displayName\"\n // splice it in to make the stack more readable.\n\n\n if (fn.displayName && _frame.includes('')) {\n _frame = _frame.replace('', fn.displayName);\n }\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, _frame);\n }\n } // Return the line we found.\n\n\n return _frame;\n }\n } while (s >= 1 && c >= 0);\n }\n\n break;\n }\n }\n }\n } finally {\n reentry = false;\n\n {\n ReactCurrentDispatcher.current = previousDispatcher;\n reenableLogs();\n }\n\n Error.prepareStackTrace = previousPrepareStackTrace;\n } // Fallback to just using the name if we couldn't make it throw.\n\n\n var name = fn ? fn.displayName || fn.name : '';\n var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, syntheticFrame);\n }\n }\n\n return syntheticFrame;\n}\n\nfunction describeClassComponentFrame(ctor, source, ownerFn) {\n {\n return describeNativeComponentFrame(ctor, true);\n }\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n {\n return describeNativeComponentFrame(fn, false);\n }\n}\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n if (type == null) {\n return '';\n }\n\n if (typeof type === 'function') {\n {\n return describeNativeComponentFrame(type, shouldConstruct(type));\n }\n }\n\n if (typeof type === 'string') {\n return describeBuiltInComponentFrame(type);\n }\n\n switch (type) {\n case REACT_SUSPENSE_TYPE:\n return describeBuiltInComponentFrame('Suspense');\n\n case REACT_SUSPENSE_LIST_TYPE:\n return describeBuiltInComponentFrame('SuspenseList');\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n return describeFunctionComponentFrame(type.render);\n\n case REACT_MEMO_TYPE:\n // Memo may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n // Lazy may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n } catch (x) {}\n }\n }\n }\n\n return '';\n}\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame.setExtraStackFrame(null);\n }\n }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n {\n // $FlowFixMe This is okay but Flow doesn't know it.\n var has = Function.call.bind(hasOwnProperty);\n\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n // eslint-disable-next-line react-internal/prod-error-codes\n var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');\n err.name = 'Invariant Violation';\n throw err;\n }\n\n error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n } catch (ex) {\n error$1 = ex;\n }\n\n if (error$1 && !(error$1 instanceof Error)) {\n setCurrentlyValidatingElement(element);\n\n error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);\n\n setCurrentlyValidatingElement(null);\n }\n\n if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error$1.message] = true;\n setCurrentlyValidatingElement(element);\n\n error('Failed %s type: %s', location, error$1.message);\n\n setCurrentlyValidatingElement(null);\n }\n }\n }\n }\n}\n\nvar warnedAboutMissingGetChildContext;\n\n{\n warnedAboutMissingGetChildContext = {};\n}\n\nvar emptyContextObject = {};\n\n{\n Object.freeze(emptyContextObject);\n}\n\nfunction getMaskedContext(type, unmaskedContext) {\n {\n var contextTypes = type.contextTypes;\n\n if (!contextTypes) {\n return emptyContextObject;\n }\n\n var context = {};\n\n for (var key in contextTypes) {\n context[key] = unmaskedContext[key];\n }\n\n {\n var name = getComponentNameFromType(type) || 'Unknown';\n checkPropTypes(contextTypes, context, 'context', name);\n }\n\n return context;\n }\n}\nfunction processChildContext(instance, type, parentContext, childContextTypes) {\n {\n // TODO (bvaughn) Replace this behavior with an invariant() in the future.\n // It has only been added in Fiber to match the (unintentional) behavior in Stack.\n if (typeof instance.getChildContext !== 'function') {\n {\n var componentName = getComponentNameFromType(type) || 'Unknown';\n\n if (!warnedAboutMissingGetChildContext[componentName]) {\n warnedAboutMissingGetChildContext[componentName] = true;\n\n error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);\n }\n }\n\n return parentContext;\n }\n\n var childContext = instance.getChildContext();\n\n for (var contextKey in childContext) {\n if (!(contextKey in childContextTypes)) {\n throw new Error((getComponentNameFromType(type) || 'Unknown') + \".getChildContext(): key \\\"\" + contextKey + \"\\\" is not defined in childContextTypes.\");\n }\n }\n\n {\n var name = getComponentNameFromType(type) || 'Unknown';\n checkPropTypes(childContextTypes, childContext, 'child context', name);\n }\n\n return assign({}, parentContext, childContext);\n }\n}\n\nvar rendererSigil;\n\n{\n // Use this to detect multiple renderers using the same context\n rendererSigil = {};\n} // Used to store the parent path of all context overrides in a shared linked list.\n// Forming a reverse tree.\n\n\nvar rootContextSnapshot = null; // We assume that this runtime owns the \"current\" field on all ReactContext instances.\n// This global (actually thread local) state represents what state all those \"current\",\n// fields are currently in.\n\nvar currentActiveSnapshot = null;\n\nfunction popNode(prev) {\n {\n prev.context._currentValue2 = prev.parentValue;\n }\n}\n\nfunction pushNode(next) {\n {\n next.context._currentValue2 = next.value;\n }\n}\n\nfunction popToNearestCommonAncestor(prev, next) {\n if (prev === next) ; else {\n popNode(prev);\n var parentPrev = prev.parent;\n var parentNext = next.parent;\n\n if (parentPrev === null) {\n if (parentNext !== null) {\n throw new Error('The stacks must reach the root at the same time. This is a bug in React.');\n }\n } else {\n if (parentNext === null) {\n throw new Error('The stacks must reach the root at the same time. This is a bug in React.');\n }\n\n popToNearestCommonAncestor(parentPrev, parentNext);\n } // On the way back, we push the new ones that weren't common.\n\n\n pushNode(next);\n }\n}\n\nfunction popAllPrevious(prev) {\n popNode(prev);\n var parentPrev = prev.parent;\n\n if (parentPrev !== null) {\n popAllPrevious(parentPrev);\n }\n}\n\nfunction pushAllNext(next) {\n var parentNext = next.parent;\n\n if (parentNext !== null) {\n pushAllNext(parentNext);\n }\n\n pushNode(next);\n}\n\nfunction popPreviousToCommonLevel(prev, next) {\n popNode(prev);\n var parentPrev = prev.parent;\n\n if (parentPrev === null) {\n throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');\n }\n\n if (parentPrev.depth === next.depth) {\n // We found the same level. Now we just need to find a shared ancestor.\n popToNearestCommonAncestor(parentPrev, next);\n } else {\n // We must still be deeper.\n popPreviousToCommonLevel(parentPrev, next);\n }\n}\n\nfunction popNextToCommonLevel(prev, next) {\n var parentNext = next.parent;\n\n if (parentNext === null) {\n throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');\n }\n\n if (prev.depth === parentNext.depth) {\n // We found the same level. Now we just need to find a shared ancestor.\n popToNearestCommonAncestor(prev, parentNext);\n } else {\n // We must still be deeper.\n popNextToCommonLevel(prev, parentNext);\n }\n\n pushNode(next);\n} // Perform context switching to the new snapshot.\n// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by\n// updating all the context's current values. That way reads, always just read the current value.\n// At the cost of updating contexts even if they're never read by this subtree.\n\n\nfunction switchContext(newSnapshot) {\n // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.\n // We also need to update any new contexts that are now on the stack with the deepest value.\n // The easiest way to update new contexts is to just reapply them in reverse order from the\n // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack\n // for that. Therefore this algorithm is recursive.\n // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.\n // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.\n // 3) Then we reapply new contexts on the way back up the stack.\n var prev = currentActiveSnapshot;\n var next = newSnapshot;\n\n if (prev !== next) {\n if (prev === null) {\n // $FlowFixMe: This has to be non-null since it's not equal to prev.\n pushAllNext(next);\n } else if (next === null) {\n popAllPrevious(prev);\n } else if (prev.depth === next.depth) {\n popToNearestCommonAncestor(prev, next);\n } else if (prev.depth > next.depth) {\n popPreviousToCommonLevel(prev, next);\n } else {\n popNextToCommonLevel(prev, next);\n }\n\n currentActiveSnapshot = next;\n }\n}\nfunction pushProvider(context, nextValue) {\n var prevValue;\n\n {\n prevValue = context._currentValue2;\n context._currentValue2 = nextValue;\n\n {\n if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {\n error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');\n }\n\n context._currentRenderer2 = rendererSigil;\n }\n }\n\n var prevNode = currentActiveSnapshot;\n var newNode = {\n parent: prevNode,\n depth: prevNode === null ? 0 : prevNode.depth + 1,\n context: context,\n parentValue: prevValue,\n value: nextValue\n };\n currentActiveSnapshot = newNode;\n return newNode;\n}\nfunction popProvider(context) {\n var prevSnapshot = currentActiveSnapshot;\n\n if (prevSnapshot === null) {\n throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');\n }\n\n {\n if (prevSnapshot.context !== context) {\n error('The parent context is not the expected context. This is probably a bug in React.');\n }\n }\n\n {\n var _value = prevSnapshot.parentValue;\n\n if (_value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {\n prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue;\n } else {\n prevSnapshot.context._currentValue2 = _value;\n }\n\n {\n if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) {\n error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');\n }\n\n context._currentRenderer2 = rendererSigil;\n }\n }\n\n return currentActiveSnapshot = prevSnapshot.parent;\n}\nfunction getActiveContext() {\n return currentActiveSnapshot;\n}\nfunction readContext(context) {\n var value = context._currentValue2;\n return value;\n}\n\n/**\n * `ReactInstanceMap` maintains a mapping from a public facing stateful\n * instance (key) and the internal representation (value). This allows public\n * methods to accept the user facing instance as an argument and map them back\n * to internal methods.\n *\n * Note that this module is currently shared and assumed to be stateless.\n * If this becomes an actual Map, that will break.\n */\nfunction get(key) {\n return key._reactInternals;\n}\nfunction set(key, value) {\n key._reactInternals = value;\n}\n\nvar didWarnAboutNoopUpdateForComponent = {};\nvar didWarnAboutDeprecatedWillMount = {};\nvar didWarnAboutUninitializedState;\nvar didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;\nvar didWarnAboutLegacyLifecyclesAndDerivedState;\nvar didWarnAboutUndefinedDerivedState;\nvar warnOnUndefinedDerivedState;\nvar warnOnInvalidCallback;\nvar didWarnAboutDirectlyAssigningPropsToState;\nvar didWarnAboutContextTypeAndContextTypes;\nvar didWarnAboutInvalidateContextType;\n\n{\n didWarnAboutUninitializedState = new Set();\n didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();\n didWarnAboutLegacyLifecyclesAndDerivedState = new Set();\n didWarnAboutDirectlyAssigningPropsToState = new Set();\n didWarnAboutUndefinedDerivedState = new Set();\n didWarnAboutContextTypeAndContextTypes = new Set();\n didWarnAboutInvalidateContextType = new Set();\n var didWarnOnInvalidCallback = new Set();\n\n warnOnInvalidCallback = function (callback, callerName) {\n if (callback === null || typeof callback === 'function') {\n return;\n }\n\n var key = callerName + '_' + callback;\n\n if (!didWarnOnInvalidCallback.has(key)) {\n didWarnOnInvalidCallback.add(key);\n\n error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);\n }\n };\n\n warnOnUndefinedDerivedState = function (type, partialState) {\n if (partialState === undefined) {\n var componentName = getComponentNameFromType(type) || 'Component';\n\n if (!didWarnAboutUndefinedDerivedState.has(componentName)) {\n didWarnAboutUndefinedDerivedState.add(componentName);\n\n error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);\n }\n }\n };\n}\n\nfunction warnNoop(publicInstance, callerName) {\n {\n var _constructor = publicInstance.constructor;\n var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';\n var warningKey = componentName + '.' + callerName;\n\n if (didWarnAboutNoopUpdateForComponent[warningKey]) {\n return;\n }\n\n error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\\n\\nPlease check the code for the %s component.', callerName, callerName, componentName);\n\n didWarnAboutNoopUpdateForComponent[warningKey] = true;\n }\n}\n\nvar classComponentUpdater = {\n isMounted: function (inst) {\n return false;\n },\n enqueueSetState: function (inst, payload, callback) {\n var internals = get(inst);\n\n if (internals.queue === null) {\n warnNoop(inst, 'setState');\n } else {\n internals.queue.push(payload);\n\n {\n if (callback !== undefined && callback !== null) {\n warnOnInvalidCallback(callback, 'setState');\n }\n }\n }\n },\n enqueueReplaceState: function (inst, payload, callback) {\n var internals = get(inst);\n internals.replace = true;\n internals.queue = [payload];\n\n {\n if (callback !== undefined && callback !== null) {\n warnOnInvalidCallback(callback, 'setState');\n }\n }\n },\n enqueueForceUpdate: function (inst, callback) {\n var internals = get(inst);\n\n if (internals.queue === null) {\n warnNoop(inst, 'forceUpdate');\n } else {\n {\n if (callback !== undefined && callback !== null) {\n warnOnInvalidCallback(callback, 'setState');\n }\n }\n }\n }\n};\n\nfunction applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {\n var partialState = getDerivedStateFromProps(nextProps, prevState);\n\n {\n warnOnUndefinedDerivedState(ctor, partialState);\n } // Merge the partial state and the previous state.\n\n\n var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);\n return newState;\n}\n\nfunction constructClassInstance(ctor, props, maskedLegacyContext) {\n var context = emptyContextObject;\n var contextType = ctor.contextType;\n\n {\n if ('contextType' in ctor) {\n var isValid = // Allow null for conditional declaration\n contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a \n\n if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {\n didWarnAboutInvalidateContextType.add(ctor);\n var addendum = '';\n\n if (contextType === undefined) {\n addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';\n } else if (typeof contextType !== 'object') {\n addendum = ' However, it is set to a ' + typeof contextType + '.';\n } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {\n addendum = ' Did you accidentally pass the Context.Provider instead?';\n } else if (contextType._context !== undefined) {\n // \n addendum = ' Did you accidentally pass the Context.Consumer instead?';\n } else {\n addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';\n }\n\n error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);\n }\n }\n }\n\n if (typeof contextType === 'object' && contextType !== null) {\n context = readContext(contextType);\n } else {\n context = maskedLegacyContext;\n }\n\n var instance = new ctor(props, context);\n\n {\n if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {\n var componentName = getComponentNameFromType(ctor) || 'Component';\n\n if (!didWarnAboutUninitializedState.has(componentName)) {\n didWarnAboutUninitializedState.add(componentName);\n\n error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);\n }\n } // If new component APIs are defined, \"unsafe\" lifecycles won't be called.\n // Warn about these lifecycles if they are present.\n // Don't warn about react-lifecycles-compat polyfilled methods though.\n\n\n if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {\n var foundWillMountName = null;\n var foundWillReceivePropsName = null;\n var foundWillUpdateName = null;\n\n if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {\n foundWillMountName = 'componentWillMount';\n } else if (typeof instance.UNSAFE_componentWillMount === 'function') {\n foundWillMountName = 'UNSAFE_componentWillMount';\n }\n\n if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {\n foundWillReceivePropsName = 'componentWillReceiveProps';\n } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';\n }\n\n if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {\n foundWillUpdateName = 'componentWillUpdate';\n } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {\n foundWillUpdateName = 'UNSAFE_componentWillUpdate';\n }\n\n if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {\n var _componentName = getComponentNameFromType(ctor) || 'Component';\n\n var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';\n\n if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {\n didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);\n\n error('Unsafe legacy lifecycles will not be called for components using new component APIs.\\n\\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\\n\\n' + 'The above lifecycles should be removed. Learn more about this warning here:\\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? \"\\n \" + foundWillMountName : '', foundWillReceivePropsName !== null ? \"\\n \" + foundWillReceivePropsName : '', foundWillUpdateName !== null ? \"\\n \" + foundWillUpdateName : '');\n }\n }\n }\n }\n\n return instance;\n}\n\nfunction checkClassInstance(instance, ctor, newProps) {\n {\n var name = getComponentNameFromType(ctor) || 'Component';\n var renderPresent = instance.render;\n\n if (!renderPresent) {\n if (ctor.prototype && typeof ctor.prototype.render === 'function') {\n error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);\n } else {\n error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);\n }\n }\n\n if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {\n error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);\n }\n\n if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);\n }\n\n if (instance.propTypes) {\n error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);\n }\n\n if (instance.contextType) {\n error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);\n }\n\n {\n if (instance.contextTypes) {\n error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);\n }\n\n if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {\n didWarnAboutContextTypeAndContextTypes.add(ctor);\n\n error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);\n }\n }\n\n if (typeof instance.componentShouldUpdate === 'function') {\n error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);\n }\n\n if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {\n error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');\n }\n\n if (typeof instance.componentDidUnmount === 'function') {\n error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);\n }\n\n if (typeof instance.componentDidReceiveProps === 'function') {\n error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);\n }\n\n if (typeof instance.componentWillRecieveProps === 'function') {\n error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);\n }\n\n if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {\n error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);\n }\n\n var hasMutatedProps = instance.props !== newProps;\n\n if (instance.props !== undefined && hasMutatedProps) {\n error('%s(...): When calling super() in `%s`, make sure to pass ' + \"up the same props that your component's constructor was passed.\", name, name);\n }\n\n if (instance.defaultProps) {\n error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {\n didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);\n\n error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));\n }\n\n if (typeof instance.getDerivedStateFromProps === 'function') {\n error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);\n }\n\n if (typeof instance.getDerivedStateFromError === 'function') {\n error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);\n }\n\n if (typeof ctor.getSnapshotBeforeUpdate === 'function') {\n error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);\n }\n\n var _state = instance.state;\n\n if (_state && (typeof _state !== 'object' || isArray(_state))) {\n error('%s.state: must be set to an object or null', name);\n }\n\n if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {\n error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);\n }\n }\n}\n\nfunction callComponentWillMount(type, instance) {\n var oldState = instance.state;\n\n if (typeof instance.componentWillMount === 'function') {\n {\n if ( instance.componentWillMount.__suppressDeprecationWarning !== true) {\n var componentName = getComponentNameFromType(type) || 'Unknown';\n\n if (!didWarnAboutDeprecatedWillMount[componentName]) {\n warn( // keep this warning in sync with ReactStrictModeWarning.js\n 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\\n\\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\\n' + '\\nPlease update the following components: %s', componentName);\n\n didWarnAboutDeprecatedWillMount[componentName] = true;\n }\n }\n }\n\n instance.componentWillMount();\n }\n\n if (typeof instance.UNSAFE_componentWillMount === 'function') {\n instance.UNSAFE_componentWillMount();\n }\n\n if (oldState !== instance.state) {\n {\n error('%s.componentWillMount(): Assigning directly to this.state is ' + \"deprecated (except inside a component's \" + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');\n }\n\n classComponentUpdater.enqueueReplaceState(instance, instance.state, null);\n }\n}\n\nfunction processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {\n if (internalInstance.queue !== null && internalInstance.queue.length > 0) {\n var oldQueue = internalInstance.queue;\n var oldReplace = internalInstance.replace;\n internalInstance.queue = null;\n internalInstance.replace = false;\n\n if (oldReplace && oldQueue.length === 1) {\n inst.state = oldQueue[0];\n } else {\n var nextState = oldReplace ? oldQueue[0] : inst.state;\n var dontMutate = true;\n\n for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {\n var partial = oldQueue[i];\n var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;\n\n if (partialState != null) {\n if (dontMutate) {\n dontMutate = false;\n nextState = assign({}, nextState, partialState);\n } else {\n assign(nextState, partialState);\n }\n }\n }\n\n inst.state = nextState;\n }\n } else {\n internalInstance.queue = null;\n }\n} // Invokes the mount life-cycles on a previously never rendered instance.\n\n\nfunction mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {\n {\n checkClassInstance(instance, ctor, newProps);\n }\n\n var initialState = instance.state !== undefined ? instance.state : null;\n instance.updater = classComponentUpdater;\n instance.props = newProps;\n instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.\n // The internal instance will be used to manage updates that happen during this mount.\n\n var internalInstance = {\n queue: [],\n replace: false\n };\n set(instance, internalInstance);\n var contextType = ctor.contextType;\n\n if (typeof contextType === 'object' && contextType !== null) {\n instance.context = readContext(contextType);\n } else {\n instance.context = maskedLegacyContext;\n }\n\n {\n if (instance.state === newProps) {\n var componentName = getComponentNameFromType(ctor) || 'Component';\n\n if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {\n didWarnAboutDirectlyAssigningPropsToState.add(componentName);\n\n error('%s: It is not recommended to assign props directly to state ' + \"because updates to props won't be reflected in state. \" + 'In most cases, it is better to use props directly.', componentName);\n }\n }\n }\n\n var getDerivedStateFromProps = ctor.getDerivedStateFromProps;\n\n if (typeof getDerivedStateFromProps === 'function') {\n instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);\n } // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n\n\n if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {\n callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's\n // process them now.\n\n processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);\n }\n}\n\n// Ids are base 32 strings whose binary representation corresponds to the\n// position of a node in a tree.\n// Every time the tree forks into multiple children, we add additional bits to\n// the left of the sequence that represent the position of the child within the\n// current level of children.\n//\n// 00101 00010001011010101\n// \u2570\u2500\u252C\u2500\u256F \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F\n// Fork 5 of 20 Parent id\n//\n// The leading 0s are important. In the above example, you only need 3 bits to\n// represent slot 5. However, you need 5 bits to represent all the forks at\n// the current level, so we must account for the empty bits at the end.\n//\n// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,\n// the zeroth id at a level would be indistinguishable from its parent.\n//\n// If a node has only one child, and does not materialize an id (i.e. does not\n// contain a useId hook), then we don't need to allocate any space in the\n// sequence. It's treated as a transparent indirection. For example, these two\n// trees produce the same ids:\n//\n// <> <>\n// \n// \n// \n// \n// \n//\n// However, we cannot skip any node that materializes an id. Otherwise, a parent\n// id that does not fork would be indistinguishable from its child id. For\n// example, this tree does not fork, but the parent and child must have\n// different ids.\n//\n// \n// \n// \n//\n// To handle this scenario, every time we materialize an id, we allocate a\n// new level with a single slot. You can think of this as a fork with only one\n// prong, or an array of children with length 1.\n//\n// It's possible for the size of the sequence to exceed 32 bits, the max\n// size for bitwise operations. When this happens, we make more room by\n// converting the right part of the id to a string and storing it in an overflow\n// variable. We use a base 32 string representation, because 32 is the largest\n// power of 2 that is supported by toString(). We want the base to be large so\n// that the resulting ids are compact, and we want the base to be a power of 2\n// because every log2(base) bits corresponds to a single character, i.e. every\n// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without\n// affecting the final result.\nvar emptyTreeContext = {\n id: 1,\n overflow: ''\n};\nfunction getTreeId(context) {\n var overflow = context.overflow;\n var idWithLeadingBit = context.id;\n var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);\n return id.toString(32) + overflow;\n}\nfunction pushTreeContext(baseContext, totalChildren, index) {\n var baseIdWithLeadingBit = baseContext.id;\n var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part\n // of the id; we use it to account for leading 0s.\n\n var baseLength = getBitLength(baseIdWithLeadingBit) - 1;\n var baseId = baseIdWithLeadingBit & ~(1 << baseLength);\n var slot = index + 1;\n var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into\n // consideration the leading 1 we use to mark the end of the sequence.\n\n if (length > 30) {\n // We overflowed the bitwise-safe range. Fall back to slower algorithm.\n // This branch assumes the length of the base id is greater than 5; it won't\n // work for smaller ids, because you need 5 bits per character.\n //\n // We encode the id in multiple steps: first the base id, then the\n // remaining digits.\n //\n // Each 5 bit sequence corresponds to a single base 32 character. So for\n // example, if the current id is 23 bits long, we can convert 20 of those\n // bits into a string of 4 characters, with 3 bits left over.\n //\n // First calculate how many bits in the base id represent a complete\n // sequence of characters.\n var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.\n\n var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.\n\n var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.\n\n var restOfBaseId = baseId >> numberOfOverflowBits;\n var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because\n // we made more room, this time it won't overflow.\n\n var restOfLength = getBitLength(totalChildren) + restOfBaseLength;\n var restOfNewBits = slot << restOfBaseLength;\n var id = restOfNewBits | restOfBaseId;\n var overflow = newOverflow + baseOverflow;\n return {\n id: 1 << restOfLength | id,\n overflow: overflow\n };\n } else {\n // Normal path\n var newBits = slot << baseLength;\n\n var _id = newBits | baseId;\n\n var _overflow = baseOverflow;\n return {\n id: 1 << length | _id,\n overflow: _overflow\n };\n }\n}\n\nfunction getBitLength(number) {\n return 32 - clz32(number);\n}\n\nfunction getLeadingBit(id) {\n return 1 << getBitLength(id) - 1;\n} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.\n\n\nvar clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.\n// Based on:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32\n\nvar log = Math.log;\nvar LN2 = Math.LN2;\n\nfunction clz32Fallback(x) {\n var asUint = x >>> 0;\n\n if (asUint === 0) {\n return 32;\n }\n\n return 31 - (log(asUint) / LN2 | 0) | 0;\n}\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar currentlyRenderingComponent = null;\nvar currentlyRenderingTask = null;\nvar firstWorkInProgressHook = null;\nvar workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook\n\nvar isReRender = false; // Whether an update was scheduled during the currently executing render pass.\n\nvar didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component\n\nvar localIdCounter = 0; // Lazily created map of render-phase updates\n\nvar renderPhaseUpdates = null; // Counter to prevent infinite loops.\n\nvar numberOfReRenders = 0;\nvar RE_RENDER_LIMIT = 25;\nvar isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook\n\nvar currentHookNameInDev;\n\nfunction resolveCurrentlyRenderingComponent() {\n if (currentlyRenderingComponent === null) {\n throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\\n' + '2. You might be breaking the Rules of Hooks\\n' + '3. You might have more than one copy of React in the same app\\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');\n }\n\n {\n if (isInHookUserCodeInDev) {\n error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');\n }\n }\n\n return currentlyRenderingComponent;\n}\n\nfunction areHookInputsEqual(nextDeps, prevDeps) {\n if (prevDeps === null) {\n {\n error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);\n }\n\n return false;\n }\n\n {\n // Don't bother comparing lengths in prod because these arrays should be\n // passed inline.\n if (nextDeps.length !== prevDeps.length) {\n error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\\n\\n' + 'Previous: %s\\n' + 'Incoming: %s', currentHookNameInDev, \"[\" + nextDeps.join(', ') + \"]\", \"[\" + prevDeps.join(', ') + \"]\");\n }\n }\n\n for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {\n if (objectIs(nextDeps[i], prevDeps[i])) {\n continue;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction createHook() {\n if (numberOfReRenders > 0) {\n throw new Error('Rendered more hooks than during the previous render');\n }\n\n return {\n memoizedState: null,\n queue: null,\n next: null\n };\n}\n\nfunction createWorkInProgressHook() {\n if (workInProgressHook === null) {\n // This is the first hook in the list\n if (firstWorkInProgressHook === null) {\n isReRender = false;\n firstWorkInProgressHook = workInProgressHook = createHook();\n } else {\n // There's already a work-in-progress. Reuse it.\n isReRender = true;\n workInProgressHook = firstWorkInProgressHook;\n }\n } else {\n if (workInProgressHook.next === null) {\n isReRender = false; // Append to the end of the list\n\n workInProgressHook = workInProgressHook.next = createHook();\n } else {\n // There's already a work-in-progress. Reuse it.\n isReRender = true;\n workInProgressHook = workInProgressHook.next;\n }\n }\n\n return workInProgressHook;\n}\n\nfunction prepareToUseHooks(task, componentIdentity) {\n currentlyRenderingComponent = componentIdentity;\n currentlyRenderingTask = task;\n\n {\n isInHookUserCodeInDev = false;\n } // The following should have already been reset\n // didScheduleRenderPhaseUpdate = false;\n // localIdCounter = 0;\n // firstWorkInProgressHook = null;\n // numberOfReRenders = 0;\n // renderPhaseUpdates = null;\n // workInProgressHook = null;\n\n\n localIdCounter = 0;\n}\nfunction finishHooks(Component, props, children, refOrContext) {\n // This must be called after every function component to prevent hooks from\n // being used in classes.\n while (didScheduleRenderPhaseUpdate) {\n // Updates were scheduled during the render phase. They are stored in\n // the `renderPhaseUpdates` map. Call the component again, reusing the\n // work-in-progress hooks and applying the additional updates on top. Keep\n // restarting until no more updates are scheduled.\n didScheduleRenderPhaseUpdate = false;\n localIdCounter = 0;\n numberOfReRenders += 1; // Start over from the beginning of the list\n\n workInProgressHook = null;\n children = Component(props, refOrContext);\n }\n\n resetHooksState();\n return children;\n}\nfunction checkDidRenderIdHook() {\n // This should be called immediately after every finishHooks call.\n // Conceptually, it's part of the return value of finishHooks; it's only a\n // separate function to avoid using an array tuple.\n var didRenderIdHook = localIdCounter !== 0;\n return didRenderIdHook;\n} // Reset the internal hooks state if an error occurs while rendering a component\n\nfunction resetHooksState() {\n {\n isInHookUserCodeInDev = false;\n }\n\n currentlyRenderingComponent = null;\n currentlyRenderingTask = null;\n didScheduleRenderPhaseUpdate = false;\n firstWorkInProgressHook = null;\n numberOfReRenders = 0;\n renderPhaseUpdates = null;\n workInProgressHook = null;\n}\n\nfunction readContext$1(context) {\n {\n if (isInHookUserCodeInDev) {\n error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');\n }\n }\n\n return readContext(context);\n}\n\nfunction useContext(context) {\n {\n currentHookNameInDev = 'useContext';\n }\n\n resolveCurrentlyRenderingComponent();\n return readContext(context);\n}\n\nfunction basicStateReducer(state, action) {\n // $FlowFixMe: Flow doesn't like mixed types\n return typeof action === 'function' ? action(state) : action;\n}\n\nfunction useState(initialState) {\n {\n currentHookNameInDev = 'useState';\n }\n\n return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers\n initialState);\n}\nfunction useReducer(reducer, initialArg, init) {\n {\n if (reducer !== basicStateReducer) {\n currentHookNameInDev = 'useReducer';\n }\n }\n\n currentlyRenderingComponent = resolveCurrentlyRenderingComponent();\n workInProgressHook = createWorkInProgressHook();\n\n if (isReRender) {\n // This is a re-render. Apply the new render phase updates to the previous\n // current hook.\n var queue = workInProgressHook.queue;\n var dispatch = queue.dispatch;\n\n if (renderPhaseUpdates !== null) {\n // Render phase updates are stored in a map of queue -> linked list\n var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);\n\n if (firstRenderPhaseUpdate !== undefined) {\n renderPhaseUpdates.delete(queue);\n var newState = workInProgressHook.memoizedState;\n var update = firstRenderPhaseUpdate;\n\n do {\n // Process this render phase update. We don't have to check the\n // priority because it will always be the same as the current\n // render's.\n var action = update.action;\n\n {\n isInHookUserCodeInDev = true;\n }\n\n newState = reducer(newState, action);\n\n {\n isInHookUserCodeInDev = false;\n }\n\n update = update.next;\n } while (update !== null);\n\n workInProgressHook.memoizedState = newState;\n return [newState, dispatch];\n }\n }\n\n return [workInProgressHook.memoizedState, dispatch];\n } else {\n {\n isInHookUserCodeInDev = true;\n }\n\n var initialState;\n\n if (reducer === basicStateReducer) {\n // Special case for `useState`.\n initialState = typeof initialArg === 'function' ? initialArg() : initialArg;\n } else {\n initialState = init !== undefined ? init(initialArg) : initialArg;\n }\n\n {\n isInHookUserCodeInDev = false;\n }\n\n workInProgressHook.memoizedState = initialState;\n\n var _queue = workInProgressHook.queue = {\n last: null,\n dispatch: null\n };\n\n var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue);\n\n return [workInProgressHook.memoizedState, _dispatch];\n }\n}\n\nfunction useMemo(nextCreate, deps) {\n currentlyRenderingComponent = resolveCurrentlyRenderingComponent();\n workInProgressHook = createWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n\n if (workInProgressHook !== null) {\n var prevState = workInProgressHook.memoizedState;\n\n if (prevState !== null) {\n if (nextDeps !== null) {\n var prevDeps = prevState[1];\n\n if (areHookInputsEqual(nextDeps, prevDeps)) {\n return prevState[0];\n }\n }\n }\n }\n\n {\n isInHookUserCodeInDev = true;\n }\n\n var nextValue = nextCreate();\n\n {\n isInHookUserCodeInDev = false;\n }\n\n workInProgressHook.memoizedState = [nextValue, nextDeps];\n return nextValue;\n}\n\nfunction useRef(initialValue) {\n currentlyRenderingComponent = resolveCurrentlyRenderingComponent();\n workInProgressHook = createWorkInProgressHook();\n var previousRef = workInProgressHook.memoizedState;\n\n if (previousRef === null) {\n var ref = {\n current: initialValue\n };\n\n {\n Object.seal(ref);\n }\n\n workInProgressHook.memoizedState = ref;\n return ref;\n } else {\n return previousRef;\n }\n}\n\nfunction useLayoutEffect(create, inputs) {\n {\n currentHookNameInDev = 'useLayoutEffect';\n\n error('useLayoutEffect does nothing on the server, because its effect cannot ' + \"be encoded into the server renderer's output format. This will lead \" + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');\n }\n}\n\nfunction dispatchAction(componentIdentity, queue, action) {\n if (numberOfReRenders >= RE_RENDER_LIMIT) {\n throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');\n }\n\n if (componentIdentity === currentlyRenderingComponent) {\n // This is a render phase update. Stash it in a lazily-created map of\n // queue -> linked list of updates. After this render pass, we'll restart\n // and apply the stashed updates on top of the work-in-progress hook.\n didScheduleRenderPhaseUpdate = true;\n var update = {\n action: action,\n next: null\n };\n\n if (renderPhaseUpdates === null) {\n renderPhaseUpdates = new Map();\n }\n\n var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);\n\n if (firstRenderPhaseUpdate === undefined) {\n renderPhaseUpdates.set(queue, update);\n } else {\n // Append the update to the end of the list.\n var lastRenderPhaseUpdate = firstRenderPhaseUpdate;\n\n while (lastRenderPhaseUpdate.next !== null) {\n lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;\n }\n\n lastRenderPhaseUpdate.next = update;\n }\n }\n}\n\nfunction useCallback(callback, deps) {\n return useMemo(function () {\n return callback;\n }, deps);\n} // TODO Decide on how to implement this hook for server rendering.\n// If a mutation occurs during render, consider triggering a Suspense boundary\n// and falling back to client rendering.\n\nfunction useMutableSource(source, getSnapshot, subscribe) {\n resolveCurrentlyRenderingComponent();\n return getSnapshot(source._source);\n}\n\nfunction useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {\n if (getServerSnapshot === undefined) {\n throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');\n }\n\n return getServerSnapshot();\n}\n\nfunction useDeferredValue(value) {\n resolveCurrentlyRenderingComponent();\n return value;\n}\n\nfunction unsupportedStartTransition() {\n throw new Error('startTransition cannot be called during server rendering.');\n}\n\nfunction useTransition() {\n resolveCurrentlyRenderingComponent();\n return [false, unsupportedStartTransition];\n}\n\nfunction useId() {\n var task = currentlyRenderingTask;\n var treeId = getTreeId(task.treeContext);\n var responseState = currentResponseState;\n\n if (responseState === null) {\n throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');\n }\n\n var localId = localIdCounter++;\n return makeId(responseState, treeId, localId);\n}\n\nfunction noop() {}\n\nvar Dispatcher = {\n readContext: readContext$1,\n useContext: useContext,\n useMemo: useMemo,\n useReducer: useReducer,\n useRef: useRef,\n useState: useState,\n useInsertionEffect: noop,\n useLayoutEffect: useLayoutEffect,\n useCallback: useCallback,\n // useImperativeHandle is not run in the server environment\n useImperativeHandle: noop,\n // Effects are not run in the server environment.\n useEffect: noop,\n // Debugging effect\n useDebugValue: noop,\n useDeferredValue: useDeferredValue,\n useTransition: useTransition,\n useId: useId,\n // Subscriptions are not setup in a server environment.\n useMutableSource: useMutableSource,\n useSyncExternalStore: useSyncExternalStore\n};\n\nvar currentResponseState = null;\nfunction setCurrentResponseState(responseState) {\n currentResponseState = responseState;\n}\n\nfunction getStackByComponentStackNode(componentStack) {\n try {\n var info = '';\n var node = componentStack;\n\n do {\n switch (node.tag) {\n case 0:\n info += describeBuiltInComponentFrame(node.type, null, null);\n break;\n\n case 1:\n info += describeFunctionComponentFrame(node.type, null, null);\n break;\n\n case 2:\n info += describeClassComponentFrame(node.type, null, null);\n break;\n }\n\n node = node.parent;\n } while (node);\n\n return info;\n } catch (x) {\n return '\\nError generating stack: ' + x.message + '\\n' + x.stack;\n }\n}\n\nvar ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\nvar PENDING = 0;\nvar COMPLETED = 1;\nvar FLUSHED = 2;\nvar ABORTED = 3;\nvar ERRORED = 4;\nvar OPEN = 0;\nvar CLOSING = 1;\nvar CLOSED = 2;\n// This is a default heuristic for how to split up the HTML content into progressive\n// loading. Our goal is to be able to display additional new content about every 500ms.\n// Faster than that is unnecessary and should be throttled on the client. It also\n// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower\n// end device but higher end suffer less from the overhead than lower end does from\n// not getting small enough pieces. We error on the side of low end.\n// We base this on low end 3G speeds which is about 500kbits per second. We assume\n// that there can be a reasonable drop off from max bandwidth which leaves you with\n// as little as 80%. We can receive half of that each 500ms - at best. In practice,\n// a little bandwidth is lost to processing and contention - e.g. CSS and images that\n// are downloaded along with the main content. So we estimate about half of that to be\n// the lower end throughput. In other words, we expect that you can at least show\n// about 12.5kb of content per 500ms. Not counting starting latency for the first\n// paint.\n// 500 * 1024 / 8 * .8 * 0.5 / 2\nvar DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;\n\nfunction defaultErrorHandler(error) {\n console['error'](error); // Don't transform to our wrapper\n\n return null;\n}\n\nfunction noop$1() {}\n\nfunction createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) {\n var pingedTasks = [];\n var abortSet = new Set();\n var request = {\n destination: null,\n responseState: responseState,\n progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,\n status: OPEN,\n fatalError: null,\n nextSegmentId: 0,\n allPendingTasks: 0,\n pendingRootTasks: 0,\n completedRootSegment: null,\n abortableTasks: abortSet,\n pingedTasks: pingedTasks,\n clientRenderedBoundaries: [],\n completedBoundaries: [],\n partialBoundaries: [],\n onError: onError === undefined ? defaultErrorHandler : onError,\n onAllReady: onAllReady === undefined ? noop$1 : onAllReady,\n onShellReady: onShellReady === undefined ? noop$1 : onShellReady,\n onShellError: onShellError === undefined ? noop$1 : onShellError,\n onFatalError: onFatalError === undefined ? noop$1 : onFatalError\n }; // This segment represents the root fallback.\n\n var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge\n false, false); // There is no parent so conceptually, we're unblocked to flush this segment.\n\n rootSegment.parentFlushed = true;\n var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext);\n pingedTasks.push(rootTask);\n return request;\n}\n\nfunction pingTask(request, task) {\n var pingedTasks = request.pingedTasks;\n pingedTasks.push(task);\n\n if (pingedTasks.length === 1) {\n scheduleWork(function () {\n return performWork(request);\n });\n }\n}\n\nfunction createSuspenseBoundary(request, fallbackAbortableTasks) {\n return {\n id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID,\n rootSegmentID: -1,\n parentFlushed: false,\n pendingTasks: 0,\n forceClientRender: false,\n completedSegments: [],\n byteSize: 0,\n fallbackAbortableTasks: fallbackAbortableTasks,\n errorDigest: null\n };\n}\n\nfunction createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) {\n request.allPendingTasks++;\n\n if (blockedBoundary === null) {\n request.pendingRootTasks++;\n } else {\n blockedBoundary.pendingTasks++;\n }\n\n var task = {\n node: node,\n ping: function () {\n return pingTask(request, task);\n },\n blockedBoundary: blockedBoundary,\n blockedSegment: blockedSegment,\n abortSet: abortSet,\n legacyContext: legacyContext,\n context: context,\n treeContext: treeContext\n };\n\n {\n task.componentStack = null;\n }\n\n abortSet.add(task);\n return task;\n}\n\nfunction createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) {\n return {\n status: PENDING,\n id: -1,\n // lazily assigned later\n index: index,\n parentFlushed: false,\n chunks: [],\n children: [],\n formatContext: formatContext,\n boundary: boundary,\n lastPushedText: lastPushedText,\n textEmbedded: textEmbedded\n };\n} // DEV-only global reference to the currently executing task\n\n\nvar currentTaskInDEV = null;\n\nfunction getCurrentStackInDEV() {\n {\n if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {\n return '';\n }\n\n return getStackByComponentStackNode(currentTaskInDEV.componentStack);\n }\n}\n\nfunction pushBuiltInComponentStackInDEV(task, type) {\n {\n task.componentStack = {\n tag: 0,\n parent: task.componentStack,\n type: type\n };\n }\n}\n\nfunction pushFunctionComponentStackInDEV(task, type) {\n {\n task.componentStack = {\n tag: 1,\n parent: task.componentStack,\n type: type\n };\n }\n}\n\nfunction pushClassComponentStackInDEV(task, type) {\n {\n task.componentStack = {\n tag: 2,\n parent: task.componentStack,\n type: type\n };\n }\n}\n\nfunction popComponentStackInDEV(task) {\n {\n if (task.componentStack === null) {\n error('Unexpectedly popped too many stack frames. This is a bug in React.');\n } else {\n task.componentStack = task.componentStack.parent;\n }\n }\n} // stash the component stack of an unwinding error until it is processed\n\n\nvar lastBoundaryErrorComponentStackDev = null;\n\nfunction captureBoundaryErrorDetailsDev(boundary, error) {\n {\n var errorMessage;\n\n if (typeof error === 'string') {\n errorMessage = error;\n } else if (error && typeof error.message === 'string') {\n errorMessage = error.message;\n } else {\n // eslint-disable-next-line react-internal/safe-string-coercion\n errorMessage = String(error);\n }\n\n var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV();\n lastBoundaryErrorComponentStackDev = null;\n boundary.errorMessage = errorMessage;\n boundary.errorComponentStack = errorComponentStack;\n }\n}\n\nfunction logRecoverableError(request, error) {\n // If this callback errors, we intentionally let that error bubble up to become a fatal error\n // so that someone fixes the error reporting instead of hiding it.\n var errorDigest = request.onError(error);\n\n if (errorDigest != null && typeof errorDigest !== 'string') {\n // eslint-disable-next-line react-internal/prod-error-codes\n throw new Error(\"onError returned something with a type other than \\\"string\\\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \\\"\" + typeof errorDigest + \"\\\" instead\");\n }\n\n return errorDigest;\n}\n\nfunction fatalError(request, error) {\n // This is called outside error handling code such as if the root errors outside\n // a suspense boundary or if the root suspense boundary's fallback errors.\n // It's also called if React itself or its host configs errors.\n var onShellError = request.onShellError;\n onShellError(error);\n var onFatalError = request.onFatalError;\n onFatalError(error);\n\n if (request.destination !== null) {\n request.status = CLOSED;\n closeWithError(request.destination, error);\n } else {\n request.status = CLOSING;\n request.fatalError = error;\n }\n}\n\nfunction renderSuspenseBoundary(request, task, props) {\n pushBuiltInComponentStackInDEV(task, 'Suspense');\n var parentBoundary = task.blockedBoundary;\n var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for\n // the fallback so that we can later replace that segment with the content.\n // This also lets us split out the main content even if it doesn't suspend,\n // in case it ends up generating a large subtree of content.\n\n var fallback = props.fallback;\n var content = props.children;\n var fallbackAbortSet = new Set();\n var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);\n var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.\n\n var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them\n false, false);\n parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent\n\n parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately.\n\n var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them\n false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is\n // no parent segment so there's nothing to wait on.\n\n contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.\n // I suspect that there might be some efficiency benefits from not creating the suspended task\n // and instead just using the stack if possible.\n // TODO: Call this directly instead of messing with saving and restoring contexts.\n // We can reuse the current context and task to render the content immediately without\n // context switching. We just need to temporarily switch which boundary and which segment\n // we're writing to. If something suspends, it'll spawn new suspended task with that context.\n\n task.blockedBoundary = newBoundary;\n task.blockedSegment = contentRootSegment;\n\n try {\n // We use the safe form because we don't handle suspending here. Only error handling.\n renderNode(request, task, content);\n pushSegmentFinale$1(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded);\n contentRootSegment.status = COMPLETED;\n queueCompletedSegment(newBoundary, contentRootSegment);\n\n if (newBoundary.pendingTasks === 0) {\n // This must have been the last segment we were waiting on. This boundary is now complete.\n // Therefore we won't need the fallback. We early return so that we don't have to create\n // the fallback.\n popComponentStackInDEV(task);\n return;\n }\n } catch (error) {\n contentRootSegment.status = ERRORED;\n newBoundary.forceClientRender = true;\n newBoundary.errorDigest = logRecoverableError(request, error);\n\n {\n captureBoundaryErrorDetailsDev(newBoundary, error);\n } // We don't need to decrement any task numbers because we didn't spawn any new task.\n // We don't need to schedule any task because we know the parent has written yet.\n // We do need to fallthrough to create the fallback though.\n\n } finally {\n task.blockedBoundary = parentBoundary;\n task.blockedSegment = parentSegment;\n } // We create suspended task for the fallback because we don't want to actually work\n // on it yet in case we finish the main content, so we queue for later.\n\n\n var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext);\n\n {\n suspendedFallbackTask.componentStack = task.componentStack;\n } // TODO: This should be queued at a separate lower priority queue so that we only work\n // on preparing fallbacks if we don't have any more main content to task on.\n\n\n request.pingedTasks.push(suspendedFallbackTask);\n popComponentStackInDEV(task);\n}\n\nfunction renderHostElement(request, task, type, props) {\n pushBuiltInComponentStackInDEV(task, type);\n var segment = task.blockedSegment;\n var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext);\n segment.lastPushedText = false;\n var prevContext = segment.formatContext;\n segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still\n // need to pop back up and finish this subtree of HTML.\n\n renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need\n // the correct context. Therefore this is not in a finally.\n\n segment.formatContext = prevContext;\n pushEndInstance(segment.chunks, type);\n segment.lastPushedText = false;\n popComponentStackInDEV(task);\n}\n\nfunction shouldConstruct$1(Component) {\n return Component.prototype && Component.prototype.isReactComponent;\n}\n\nfunction renderWithHooks(request, task, Component, props, secondArg) {\n var componentIdentity = {};\n prepareToUseHooks(task, componentIdentity);\n var result = Component(props, secondArg);\n return finishHooks(Component, props, result, secondArg);\n}\n\nfunction finishClassComponent(request, task, instance, Component, props) {\n var nextChildren = instance.render();\n\n {\n if (instance.props !== props) {\n if (!didWarnAboutReassigningProps) {\n error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');\n }\n\n didWarnAboutReassigningProps = true;\n }\n }\n\n {\n var childContextTypes = Component.childContextTypes;\n\n if (childContextTypes !== null && childContextTypes !== undefined) {\n var previousContext = task.legacyContext;\n var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes);\n task.legacyContext = mergedContext;\n renderNodeDestructive(request, task, nextChildren);\n task.legacyContext = previousContext;\n return;\n }\n }\n\n renderNodeDestructive(request, task, nextChildren);\n}\n\nfunction renderClassComponent(request, task, Component, props) {\n pushClassComponentStackInDEV(task, Component);\n var maskedContext = getMaskedContext(Component, task.legacyContext) ;\n var instance = constructClassInstance(Component, props, maskedContext);\n mountClassInstance(instance, Component, props, maskedContext);\n finishClassComponent(request, task, instance, Component, props);\n popComponentStackInDEV(task);\n}\n\nvar didWarnAboutBadClass = {};\nvar didWarnAboutModulePatternComponent = {};\nvar didWarnAboutContextTypeOnFunctionComponent = {};\nvar didWarnAboutGetDerivedStateOnFunctionComponent = {};\nvar didWarnAboutReassigningProps = false;\nvar didWarnAboutDefaultPropsOnFunctionComponent = {};\nvar didWarnAboutGenerators = false;\nvar didWarnAboutMaps = false;\nvar hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern\n// components for some reason.\n\nfunction renderIndeterminateComponent(request, task, Component, props) {\n var legacyContext;\n\n {\n legacyContext = getMaskedContext(Component, task.legacyContext);\n }\n\n pushFunctionComponentStackInDEV(task, Component);\n\n {\n if (Component.prototype && typeof Component.prototype.render === 'function') {\n var componentName = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutBadClass[componentName]) {\n error(\"The <%s /> component appears to have a render method, but doesn't extend React.Component. \" + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);\n\n didWarnAboutBadClass[componentName] = true;\n }\n }\n }\n\n var value = renderWithHooks(request, task, Component, props, legacyContext);\n var hasId = checkDidRenderIdHook();\n\n {\n // Support for module components is deprecated and is removed behind a flag.\n // Whether or not it would crash later, we want to show a good message in DEV first.\n if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {\n var _componentName = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutModulePatternComponent[_componentName]) {\n error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + \"If you can't use a class try assigning the prototype on the function as a workaround. \" + \"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it \" + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);\n\n didWarnAboutModulePatternComponent[_componentName] = true;\n }\n }\n }\n\n if ( // Run these checks in production only if the flag is off.\n // Eventually we'll delete this branch altogether.\n typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {\n {\n var _componentName2 = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutModulePatternComponent[_componentName2]) {\n error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + \"If you can't use a class try assigning the prototype on the function as a workaround. \" + \"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it \" + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);\n\n didWarnAboutModulePatternComponent[_componentName2] = true;\n }\n }\n\n mountClassInstance(value, Component, props, legacyContext);\n finishClassComponent(request, task, value, Component, props);\n } else {\n\n {\n validateFunctionComponentInDev(Component);\n } // We're now successfully past this task, and we don't have to pop back to\n // the previous task every again, so we can use the destructive recursive form.\n\n\n if (hasId) {\n // This component materialized an id. We treat this as its own level, with\n // a single \"child\" slot.\n var prevTreeContext = task.treeContext;\n var totalChildren = 1;\n var index = 0;\n task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);\n\n try {\n renderNodeDestructive(request, task, value);\n } finally {\n task.treeContext = prevTreeContext;\n }\n } else {\n renderNodeDestructive(request, task, value);\n }\n }\n\n popComponentStackInDEV(task);\n}\n\nfunction validateFunctionComponentInDev(Component) {\n {\n if (Component) {\n if (Component.childContextTypes) {\n error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');\n }\n }\n\n if ( Component.defaultProps !== undefined) {\n var componentName = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {\n error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);\n\n didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;\n }\n }\n\n if (typeof Component.getDerivedStateFromProps === 'function') {\n var _componentName3 = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {\n error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);\n\n didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;\n }\n }\n\n if (typeof Component.contextType === 'object' && Component.contextType !== null) {\n var _componentName4 = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {\n error('%s: Function components do not support contextType.', _componentName4);\n\n didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;\n }\n }\n }\n}\n\nfunction resolveDefaultProps(Component, baseProps) {\n if (Component && Component.defaultProps) {\n // Resolve default props. Taken from ReactElement\n var props = assign({}, baseProps);\n var defaultProps = Component.defaultProps;\n\n for (var propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n\n return props;\n }\n\n return baseProps;\n}\n\nfunction renderForwardRef(request, task, type, props, ref) {\n pushFunctionComponentStackInDEV(task, type.render);\n var children = renderWithHooks(request, task, type.render, props, ref);\n var hasId = checkDidRenderIdHook();\n\n if (hasId) {\n // This component materialized an id. We treat this as its own level, with\n // a single \"child\" slot.\n var prevTreeContext = task.treeContext;\n var totalChildren = 1;\n var index = 0;\n task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);\n\n try {\n renderNodeDestructive(request, task, children);\n } finally {\n task.treeContext = prevTreeContext;\n }\n } else {\n renderNodeDestructive(request, task, children);\n }\n\n popComponentStackInDEV(task);\n}\n\nfunction renderMemo(request, task, type, props, ref) {\n var innerType = type.type;\n var resolvedProps = resolveDefaultProps(innerType, props);\n renderElement(request, task, innerType, resolvedProps, ref);\n}\n\nfunction renderContextConsumer(request, task, context, props) {\n // The logic below for Context differs depending on PROD or DEV mode. In\n // DEV mode, we create a separate object for Context.Consumer that acts\n // like a proxy to Context. This proxy object adds unnecessary code in PROD\n // so we use the old behaviour (Context.Consumer references Context) to\n // reduce size and overhead. The separate object references context via\n // a property called \"_context\", which also gives us the ability to check\n // in DEV mode if this property exists or not and warn if it does not.\n {\n if (context._context === undefined) {\n // This may be because it's a Context (rather than a Consumer).\n // Or it may be because it's older React where they're the same thing.\n // We only want to warn if we're sure it's a new React.\n if (context !== context.Consumer) {\n if (!hasWarnedAboutUsingContextAsConsumer) {\n hasWarnedAboutUsingContextAsConsumer = true;\n\n error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?');\n }\n }\n } else {\n context = context._context;\n }\n }\n\n var render = props.children;\n\n {\n if (typeof render !== 'function') {\n error('A context consumer was rendered with multiple children, or a child ' + \"that isn't a function. A context consumer expects a single child \" + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');\n }\n }\n\n var newValue = readContext(context);\n var newChildren = render(newValue);\n renderNodeDestructive(request, task, newChildren);\n}\n\nfunction renderContextProvider(request, task, type, props) {\n var context = type._context;\n var value = props.value;\n var children = props.children;\n var prevSnapshot;\n\n {\n prevSnapshot = task.context;\n }\n\n task.context = pushProvider(context, value);\n renderNodeDestructive(request, task, children);\n task.context = popProvider(context);\n\n {\n if (prevSnapshot !== task.context) {\n error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');\n }\n }\n}\n\nfunction renderLazyComponent(request, task, lazyComponent, props, ref) {\n pushBuiltInComponentStackInDEV(task, 'Lazy');\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n var Component = init(payload);\n var resolvedProps = resolveDefaultProps(Component, props);\n renderElement(request, task, Component, resolvedProps, ref);\n popComponentStackInDEV(task);\n}\n\nfunction renderElement(request, task, type, props, ref) {\n if (typeof type === 'function') {\n if (shouldConstruct$1(type)) {\n renderClassComponent(request, task, type, props);\n return;\n } else {\n renderIndeterminateComponent(request, task, type, props);\n return;\n }\n }\n\n if (typeof type === 'string') {\n renderHostElement(request, task, type, props);\n return;\n }\n\n switch (type) {\n // TODO: LegacyHidden acts the same as a fragment. This only works\n // because we currently assume that every instance of LegacyHidden is\n // accompanied by a host component wrapper. In the hidden mode, the host\n // component is given a `hidden` attribute, which ensures that the\n // initial HTML is not visible. To support the use of LegacyHidden as a\n // true fragment, without an extra DOM node, we would have to hide the\n // initial HTML in some other way.\n // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability.\n case REACT_LEGACY_HIDDEN_TYPE:\n case REACT_DEBUG_TRACING_MODE_TYPE:\n case REACT_STRICT_MODE_TYPE:\n case REACT_PROFILER_TYPE:\n case REACT_FRAGMENT_TYPE:\n {\n renderNodeDestructive(request, task, props.children);\n return;\n }\n\n case REACT_SUSPENSE_LIST_TYPE:\n {\n pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.\n\n renderNodeDestructive(request, task, props.children);\n popComponentStackInDEV(task);\n return;\n }\n\n case REACT_SCOPE_TYPE:\n {\n\n throw new Error('ReactDOMServer does not yet support scope components.');\n }\n // eslint-disable-next-line-no-fallthrough\n\n case REACT_SUSPENSE_TYPE:\n {\n {\n renderSuspenseBoundary(request, task, props);\n }\n\n return;\n }\n }\n\n if (typeof type === 'object' && type !== null) {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n {\n renderForwardRef(request, task, type, props, ref);\n return;\n }\n\n case REACT_MEMO_TYPE:\n {\n renderMemo(request, task, type, props, ref);\n return;\n }\n\n case REACT_PROVIDER_TYPE:\n {\n renderContextProvider(request, task, type, props);\n return;\n }\n\n case REACT_CONTEXT_TYPE:\n {\n renderContextConsumer(request, task, type, props);\n return;\n }\n\n case REACT_LAZY_TYPE:\n {\n renderLazyComponent(request, task, type, props);\n return;\n }\n }\n }\n\n var info = '';\n\n {\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and \" + 'named imports.';\n }\n }\n\n throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + (\"but got: \" + (type == null ? type : typeof type) + \".\" + info));\n}\n\nfunction validateIterable(iterable, iteratorFn) {\n {\n // We don't support rendering Generators because it's a mutation.\n // See https://github.com/facebook/react/issues/12995\n if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag\n iterable[Symbol.toStringTag] === 'Generator') {\n if (!didWarnAboutGenerators) {\n error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');\n }\n\n didWarnAboutGenerators = true;\n } // Warn about using Maps as children\n\n\n if (iterable.entries === iteratorFn) {\n if (!didWarnAboutMaps) {\n error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');\n }\n\n didWarnAboutMaps = true;\n }\n }\n}\n\nfunction renderNodeDestructive(request, task, node) {\n {\n // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture\n // a component stack at the right place in the tree. We don't do this in renderNode\n // becuase it is not called at every layer of the tree and we may lose frames\n try {\n return renderNodeDestructiveImpl(request, task, node);\n } catch (x) {\n if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else {\n // This is an error, stash the component stack if it is null.\n lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV();\n } // rethrow so normal suspense logic can handle thrown value accordingly\n\n\n throw x;\n }\n }\n} // This function by it self renders a node and consumes the task by mutating it\n// to update the current execution state.\n\n\nfunction renderNodeDestructiveImpl(request, task, node) {\n // Stash the node we're working on. We'll pick up from this task in case\n // something suspends.\n task.node = node; // Handle object types\n\n if (typeof node === 'object' && node !== null) {\n switch (node.$$typeof) {\n case REACT_ELEMENT_TYPE:\n {\n var element = node;\n var type = element.type;\n var props = element.props;\n var ref = element.ref;\n renderElement(request, task, type, props, ref);\n return;\n }\n\n case REACT_PORTAL_TYPE:\n throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');\n // eslint-disable-next-line-no-fallthrough\n\n case REACT_LAZY_TYPE:\n {\n var lazyNode = node;\n var payload = lazyNode._payload;\n var init = lazyNode._init;\n var resolvedNode;\n\n {\n try {\n resolvedNode = init(payload);\n } catch (x) {\n if (typeof x === 'object' && x !== null && typeof x.then === 'function') {\n // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be\n // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position\n // vs Component position. We do not want the frame for Errors so we exclusively do this in\n // the wakeable branch\n pushBuiltInComponentStackInDEV(task, 'Lazy');\n }\n\n throw x;\n }\n }\n\n renderNodeDestructive(request, task, resolvedNode);\n return;\n }\n }\n\n if (isArray(node)) {\n renderChildrenArray(request, task, node);\n return;\n }\n\n var iteratorFn = getIteratorFn(node);\n\n if (iteratorFn) {\n {\n validateIterable(node, iteratorFn);\n }\n\n var iterator = iteratorFn.call(node);\n\n if (iterator) {\n // We need to know how many total children are in this set, so that we\n // can allocate enough id slots to acommodate them. So we must exhaust\n // the iterator before we start recursively rendering the children.\n // TODO: This is not great but I think it's inherent to the id\n // generation algorithm.\n var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that.\n\n if (!step.done) {\n var children = [];\n\n do {\n children.push(step.value);\n step = iterator.next();\n } while (!step.done);\n\n renderChildrenArray(request, task, children);\n return;\n }\n\n return;\n }\n }\n\n var childString = Object.prototype.toString.call(node);\n throw new Error(\"Objects are not valid as a React child (found: \" + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + \"). \" + 'If you meant to render a collection of children, use an array ' + 'instead.');\n }\n\n if (typeof node === 'string') {\n var segment = task.blockedSegment;\n segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText);\n return;\n }\n\n if (typeof node === 'number') {\n var _segment = task.blockedSegment;\n _segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText);\n return;\n }\n\n {\n if (typeof node === 'function') {\n error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.');\n }\n }\n}\n\nfunction renderChildrenArray(request, task, children) {\n var totalChildren = children.length;\n\n for (var i = 0; i < totalChildren; i++) {\n var prevTreeContext = task.treeContext;\n task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);\n\n try {\n // We need to use the non-destructive form so that we can safely pop back\n // up and render the sibling if something suspends.\n renderNode(request, task, children[i]);\n } finally {\n task.treeContext = prevTreeContext;\n }\n }\n}\n\nfunction spawnNewSuspendedTask(request, task, x) {\n // Something suspended, we'll need to create a new segment and resolve it later.\n var segment = task.blockedSegment;\n var insertionIndex = segment.chunks.length;\n var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed\n segment.lastPushedText, // Assume we are text embedded at the trailing edge\n true);\n segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment \"consumed\" it\n\n segment.lastPushedText = false;\n var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext);\n\n {\n if (task.componentStack !== null) {\n // We pop one task off the stack because the node that suspended will be tried again,\n // which will add it back onto the stack.\n newTask.componentStack = task.componentStack.parent;\n }\n }\n\n var ping = newTask.ping;\n x.then(ping, ping);\n} // This is a non-destructive form of rendering a node. If it suspends it spawns\n// a new task and restores the context of this task to what it was before.\n\n\nfunction renderNode(request, task, node) {\n // TODO: Store segment.children.length here and reset it in case something\n // suspended partially through writing something.\n // Snapshot the current context in case something throws to interrupt the\n // process.\n var previousFormatContext = task.blockedSegment.formatContext;\n var previousLegacyContext = task.legacyContext;\n var previousContext = task.context;\n var previousComponentStack = null;\n\n {\n previousComponentStack = task.componentStack;\n }\n\n try {\n return renderNodeDestructive(request, task, node);\n } catch (x) {\n resetHooksState();\n\n if (typeof x === 'object' && x !== null && typeof x.then === 'function') {\n spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner\n // functions in case nothing throws so we don't use \"finally\" here.\n\n task.blockedSegment.formatContext = previousFormatContext;\n task.legacyContext = previousLegacyContext;\n task.context = previousContext; // Restore all active ReactContexts to what they were before.\n\n switchContext(previousContext);\n\n {\n task.componentStack = previousComponentStack;\n }\n\n return;\n } else {\n // Restore the context. We assume that this will be restored by the inner\n // functions in case nothing throws so we don't use \"finally\" here.\n task.blockedSegment.formatContext = previousFormatContext;\n task.legacyContext = previousLegacyContext;\n task.context = previousContext; // Restore all active ReactContexts to what they were before.\n\n switchContext(previousContext);\n\n {\n task.componentStack = previousComponentStack;\n } // We assume that we don't need the correct context.\n // Let's terminate the rest of the tree and don't render any siblings.\n\n\n throw x;\n }\n }\n}\n\nfunction erroredTask(request, boundary, segment, error) {\n // Report the error to a global handler.\n var errorDigest = logRecoverableError(request, error);\n\n if (boundary === null) {\n fatalError(request, error);\n } else {\n boundary.pendingTasks--;\n\n if (!boundary.forceClientRender) {\n boundary.forceClientRender = true;\n boundary.errorDigest = errorDigest;\n\n {\n captureBoundaryErrorDetailsDev(boundary, error);\n } // Regardless of what happens next, this boundary won't be displayed,\n // so we can flush it, if the parent already flushed.\n\n\n if (boundary.parentFlushed) {\n // We don't have a preference where in the queue this goes since it's likely\n // to error on the client anyway. However, intentionally client-rendered\n // boundaries should be flushed earlier so that they can start on the client.\n // We reuse the same queue for errors.\n request.clientRenderedBoundaries.push(boundary);\n }\n }\n }\n\n request.allPendingTasks--;\n\n if (request.allPendingTasks === 0) {\n var onAllReady = request.onAllReady;\n onAllReady();\n }\n}\n\nfunction abortTaskSoft(task) {\n // This aborts task without aborting the parent boundary that it blocks.\n // It's used for when we didn't need this task to complete the tree.\n // If task was needed, then it should use abortTask instead.\n var request = this;\n var boundary = task.blockedBoundary;\n var segment = task.blockedSegment;\n segment.status = ABORTED;\n finishedTask(request, boundary, segment);\n}\n\nfunction abortTask(task, request, reason) {\n // This aborts the task and aborts the parent that it blocks, putting it into\n // client rendered mode.\n var boundary = task.blockedBoundary;\n var segment = task.blockedSegment;\n segment.status = ABORTED;\n\n if (boundary === null) {\n request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close\n // the request;\n\n if (request.status !== CLOSED) {\n request.status = CLOSED;\n\n if (request.destination !== null) {\n close(request.destination);\n }\n }\n } else {\n boundary.pendingTasks--;\n\n if (!boundary.forceClientRender) {\n boundary.forceClientRender = true;\n\n var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;\n\n boundary.errorDigest = request.onError(_error);\n\n {\n var errorPrefix = 'The server did not finish this Suspense boundary: ';\n\n if (_error && typeof _error.message === 'string') {\n _error = errorPrefix + _error.message;\n } else {\n // eslint-disable-next-line react-internal/safe-string-coercion\n _error = errorPrefix + String(_error);\n }\n\n var previousTaskInDev = currentTaskInDEV;\n currentTaskInDEV = task;\n\n try {\n captureBoundaryErrorDetailsDev(boundary, _error);\n } finally {\n currentTaskInDEV = previousTaskInDev;\n }\n }\n\n if (boundary.parentFlushed) {\n request.clientRenderedBoundaries.push(boundary);\n }\n } // If this boundary was still pending then we haven't already cancelled its fallbacks.\n // We'll need to abort the fallbacks, which will also error that parent boundary.\n\n\n boundary.fallbackAbortableTasks.forEach(function (fallbackTask) {\n return abortTask(fallbackTask, request, reason);\n });\n boundary.fallbackAbortableTasks.clear();\n request.allPendingTasks--;\n\n if (request.allPendingTasks === 0) {\n var onAllReady = request.onAllReady;\n onAllReady();\n }\n }\n}\n\nfunction queueCompletedSegment(boundary, segment) {\n if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) {\n // This is an empty segment. There's nothing to write, so we can instead transfer the ID\n // to the child. That way any existing references point to the child.\n var childSegment = segment.children[0];\n childSegment.id = segment.id;\n childSegment.parentFlushed = true;\n\n if (childSegment.status === COMPLETED) {\n queueCompletedSegment(boundary, childSegment);\n }\n } else {\n var completedSegments = boundary.completedSegments;\n completedSegments.push(segment);\n }\n}\n\nfunction finishedTask(request, boundary, segment) {\n if (boundary === null) {\n if (segment.parentFlushed) {\n if (request.completedRootSegment !== null) {\n throw new Error('There can only be one root segment. This is a bug in React.');\n }\n\n request.completedRootSegment = segment;\n }\n\n request.pendingRootTasks--;\n\n if (request.pendingRootTasks === 0) {\n // We have completed the shell so the shell can't error anymore.\n request.onShellError = noop$1;\n var onShellReady = request.onShellReady;\n onShellReady();\n }\n } else {\n boundary.pendingTasks--;\n\n if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) {\n // This must have been the last segment we were waiting on. This boundary is now complete.\n if (segment.parentFlushed) {\n // Our parent segment already flushed, so we need to schedule this segment to be emitted.\n // If it is a segment that was aborted, we'll write other content instead so we don't need\n // to emit it.\n if (segment.status === COMPLETED) {\n queueCompletedSegment(boundary, segment);\n }\n }\n\n if (boundary.parentFlushed) {\n // The segment might be part of a segment that didn't flush yet, but if the boundary's\n // parent flushed, we need to schedule the boundary to be emitted.\n request.completedBoundaries.push(boundary);\n } // We can now cancel any pending task on the fallback since we won't need to show it anymore.\n // This needs to happen after we read the parentFlushed flags because aborting can finish\n // work which can trigger user code, which can start flushing, which can change those flags.\n\n\n boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);\n boundary.fallbackAbortableTasks.clear();\n } else {\n if (segment.parentFlushed) {\n // Our parent already flushed, so we need to schedule this segment to be emitted.\n // If it is a segment that was aborted, we'll write other content instead so we don't need\n // to emit it.\n if (segment.status === COMPLETED) {\n queueCompletedSegment(boundary, segment);\n var completedSegments = boundary.completedSegments;\n\n if (completedSegments.length === 1) {\n // This is the first time since we last flushed that we completed anything.\n // We can schedule this boundary to emit its partially completed segments early\n // in case the parent has already been flushed.\n if (boundary.parentFlushed) {\n request.partialBoundaries.push(boundary);\n }\n }\n }\n }\n }\n }\n\n request.allPendingTasks--;\n\n if (request.allPendingTasks === 0) {\n // This needs to be called at the very end so that we can synchronously write the result\n // in the callback if needed.\n var onAllReady = request.onAllReady;\n onAllReady();\n }\n}\n\nfunction retryTask(request, task) {\n var segment = task.blockedSegment;\n\n if (segment.status !== PENDING) {\n // We completed this by other means before we had a chance to retry it.\n return;\n } // We restore the context to what it was when we suspended.\n // We don't restore it after we leave because it's likely that we'll end up\n // needing a very similar context soon again.\n\n\n switchContext(task.context);\n var prevTaskInDEV = null;\n\n {\n prevTaskInDEV = currentTaskInDEV;\n currentTaskInDEV = task;\n }\n\n try {\n // We call the destructive form that mutates this task. That way if something\n // suspends again, we can reuse the same task instead of spawning a new one.\n renderNodeDestructive(request, task, task.node);\n pushSegmentFinale$1(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded);\n task.abortSet.delete(task);\n segment.status = COMPLETED;\n finishedTask(request, task.blockedBoundary, segment);\n } catch (x) {\n resetHooksState();\n\n if (typeof x === 'object' && x !== null && typeof x.then === 'function') {\n // Something suspended again, let's pick it back up later.\n var ping = task.ping;\n x.then(ping, ping);\n } else {\n task.abortSet.delete(task);\n segment.status = ERRORED;\n erroredTask(request, task.blockedBoundary, segment, x);\n }\n } finally {\n {\n currentTaskInDEV = prevTaskInDEV;\n }\n }\n}\n\nfunction performWork(request) {\n if (request.status === CLOSED) {\n return;\n }\n\n var prevContext = getActiveContext();\n var prevDispatcher = ReactCurrentDispatcher$1.current;\n ReactCurrentDispatcher$1.current = Dispatcher;\n var prevGetCurrentStackImpl;\n\n {\n prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack;\n ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV;\n }\n\n var prevResponseState = currentResponseState;\n setCurrentResponseState(request.responseState);\n\n try {\n var pingedTasks = request.pingedTasks;\n var i;\n\n for (i = 0; i < pingedTasks.length; i++) {\n var task = pingedTasks[i];\n retryTask(request, task);\n }\n\n pingedTasks.splice(0, i);\n\n if (request.destination !== null) {\n flushCompletedQueues(request, request.destination);\n }\n } catch (error) {\n logRecoverableError(request, error);\n fatalError(request, error);\n } finally {\n setCurrentResponseState(prevResponseState);\n ReactCurrentDispatcher$1.current = prevDispatcher;\n\n {\n ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl;\n }\n\n if (prevDispatcher === Dispatcher) {\n // This means that we were in a reentrant work loop. This could happen\n // in a renderer that supports synchronous work like renderToString,\n // when it's called from within another renderer.\n // Normally we don't bother switching the contexts to their root/default\n // values when leaving because we'll likely need the same or similar\n // context again. However, when we're inside a synchronous loop like this\n // we'll to restore the context to what it was before returning.\n switchContext(prevContext);\n }\n }\n}\n\nfunction flushSubtree(request, destination, segment) {\n segment.parentFlushed = true;\n\n switch (segment.status) {\n case PENDING:\n {\n // We're emitting a placeholder for this segment to be filled in later.\n // Therefore we'll need to assign it an ID - to refer to it by.\n var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately\n\n segment.lastPushedText = false;\n segment.textEmbedded = false;\n return writePlaceholder(destination, request.responseState, segmentID);\n }\n\n case COMPLETED:\n {\n segment.status = FLUSHED;\n var r = true;\n var chunks = segment.chunks;\n var chunkIdx = 0;\n var children = segment.children;\n\n for (var childIdx = 0; childIdx < children.length; childIdx++) {\n var nextChild = children[childIdx]; // Write all the chunks up until the next child.\n\n for (; chunkIdx < nextChild.index; chunkIdx++) {\n writeChunk(destination, chunks[chunkIdx]);\n }\n\n r = flushSegment(request, destination, nextChild);\n } // Finally just write all the remaining chunks\n\n\n for (; chunkIdx < chunks.length - 1; chunkIdx++) {\n writeChunk(destination, chunks[chunkIdx]);\n }\n\n if (chunkIdx < chunks.length) {\n r = writeChunkAndReturn(destination, chunks[chunkIdx]);\n }\n\n return r;\n }\n\n default:\n {\n throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');\n }\n }\n}\n\nfunction flushSegment(request, destination, segment) {\n var boundary = segment.boundary;\n\n if (boundary === null) {\n // Not a suspense boundary.\n return flushSubtree(request, destination, segment);\n }\n\n boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to\n // emit the content or the fallback now.\n\n if (boundary.forceClientRender) {\n // Emit a client rendered suspense boundary wrapper.\n // We never queue the inner boundary so we'll never emit its content or partial segments.\n writeStartClientRenderedSuspenseBoundary$1(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback.\n\n flushSubtree(request, destination, segment);\n return writeEndClientRenderedSuspenseBoundary$1(destination, request.responseState);\n } else if (boundary.pendingTasks > 0) {\n // This boundary is still loading. Emit a pending suspense boundary wrapper.\n // Assign an ID to refer to the future content by.\n boundary.rootSegmentID = request.nextSegmentId++;\n\n if (boundary.completedSegments.length > 0) {\n // If this is at least partially complete, we can queue it to be partially emitted early.\n request.partialBoundaries.push(boundary);\n } /// This is the first time we should have referenced this ID.\n\n\n var id = boundary.id = assignSuspenseBoundaryID(request.responseState);\n writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback.\n\n flushSubtree(request, destination, segment);\n return writeEndPendingSuspenseBoundary(destination, request.responseState);\n } else if (boundary.byteSize > request.progressiveChunkSize) {\n // This boundary is large and will be emitted separately so that we can progressively show\n // other content. We add it to the queue during the flush because we have to ensure that\n // the parent flushes first so that there's something to inject it into.\n // We also have to make sure that it's emitted into the queue in a deterministic slot.\n // I.e. we can't insert it here when it completes.\n // Assign an ID to refer to the future content by.\n boundary.rootSegmentID = request.nextSegmentId++;\n request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.\n\n writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback.\n\n flushSubtree(request, destination, segment);\n return writeEndPendingSuspenseBoundary(destination, request.responseState);\n } else {\n // We can inline this boundary's content as a complete boundary.\n writeStartCompletedSuspenseBoundary$1(destination, request.responseState);\n var completedSegments = boundary.completedSegments;\n\n if (completedSegments.length !== 1) {\n throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');\n }\n\n var contentSegment = completedSegments[0];\n flushSegment(request, destination, contentSegment);\n return writeEndCompletedSuspenseBoundary$1(destination, request.responseState);\n }\n}\n\nfunction flushClientRenderedBoundary(request, destination, boundary) {\n return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack);\n}\n\nfunction flushSegmentContainer(request, destination, segment) {\n writeStartSegment(destination, request.responseState, segment.formatContext, segment.id);\n flushSegment(request, destination, segment);\n return writeEndSegment(destination, segment.formatContext);\n}\n\nfunction flushCompletedBoundary(request, destination, boundary) {\n var completedSegments = boundary.completedSegments;\n var i = 0;\n\n for (; i < completedSegments.length; i++) {\n var segment = completedSegments[i];\n flushPartiallyCompletedSegment(request, destination, boundary, segment);\n }\n\n completedSegments.length = 0;\n return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID);\n}\n\nfunction flushPartialBoundary(request, destination, boundary) {\n var completedSegments = boundary.completedSegments;\n var i = 0;\n\n for (; i < completedSegments.length; i++) {\n var segment = completedSegments[i];\n\n if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {\n i++;\n completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority\n // might want to write later.\n\n return false;\n }\n }\n\n completedSegments.splice(0, i);\n return true;\n}\n\nfunction flushPartiallyCompletedSegment(request, destination, boundary, segment) {\n if (segment.status === FLUSHED) {\n // We've already flushed this inline.\n return true;\n }\n\n var segmentID = segment.id;\n\n if (segmentID === -1) {\n // This segment wasn't previously referred to. This happens at the root of\n // a boundary. We make kind of a leap here and assume this is the root.\n var rootSegmentID = segment.id = boundary.rootSegmentID;\n\n if (rootSegmentID === -1) {\n throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');\n }\n\n return flushSegmentContainer(request, destination, segment);\n } else {\n flushSegmentContainer(request, destination, segment);\n return writeCompletedSegmentInstruction(destination, request.responseState, segmentID);\n }\n}\n\nfunction flushCompletedQueues(request, destination) {\n\n try {\n // The structure of this is to go through each queue one by one and write\n // until the sink tells us to stop. When we should stop, we still finish writing\n // that item fully and then yield. At that point we remove the already completed\n // items up until the point we completed them.\n // TODO: Emit preloading.\n // TODO: It's kind of unfortunate to keep checking this array after we've already\n // emitted the root.\n var completedRootSegment = request.completedRootSegment;\n\n if (completedRootSegment !== null && request.pendingRootTasks === 0) {\n flushSegment(request, destination, completedRootSegment);\n request.completedRootSegment = null;\n writeCompletedRoot(destination, request.responseState);\n } // We emit client rendering instructions for already emitted boundaries first.\n // This is so that we can signal to the client to start client rendering them as\n // soon as possible.\n\n\n var clientRenderedBoundaries = request.clientRenderedBoundaries;\n var i;\n\n for (i = 0; i < clientRenderedBoundaries.length; i++) {\n var boundary = clientRenderedBoundaries[i];\n\n if (!flushClientRenderedBoundary(request, destination, boundary)) {\n request.destination = null;\n i++;\n clientRenderedBoundaries.splice(0, i);\n return;\n }\n }\n\n clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries\n // that are completely done since we can actually show them, than it is to emit\n // any individual segments from a partially complete boundary.\n\n var completedBoundaries = request.completedBoundaries;\n\n for (i = 0; i < completedBoundaries.length; i++) {\n var _boundary = completedBoundaries[i];\n\n if (!flushCompletedBoundary(request, destination, _boundary)) {\n request.destination = null;\n i++;\n completedBoundaries.splice(0, i);\n return;\n }\n }\n\n completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before\n // we continue with lower priorities.\n\n completeWriting(destination);\n beginWriting(destination); // TODO: Here we'll emit data used by hydration.\n // Next we emit any segments of any boundaries that are partially complete\n // but not deeply complete.\n\n var partialBoundaries = request.partialBoundaries;\n\n for (i = 0; i < partialBoundaries.length; i++) {\n var _boundary2 = partialBoundaries[i];\n\n if (!flushPartialBoundary(request, destination, _boundary2)) {\n request.destination = null;\n i++;\n partialBoundaries.splice(0, i);\n return;\n }\n }\n\n partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had\n // boundaries added to it in case they were too larged to be inlined.\n // New ones might be added in this loop.\n\n var largeBoundaries = request.completedBoundaries;\n\n for (i = 0; i < largeBoundaries.length; i++) {\n var _boundary3 = largeBoundaries[i];\n\n if (!flushCompletedBoundary(request, destination, _boundary3)) {\n request.destination = null;\n i++;\n largeBoundaries.splice(0, i);\n return;\n }\n }\n\n largeBoundaries.splice(0, i);\n } finally {\n\n if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because\n // either they have pending task or they're complete.\n ) {\n {\n if (request.abortableTasks.size !== 0) {\n error('There was still abortable task at the root when we closed. This is a bug in React.');\n }\n } // We're done.\n\n\n close(destination);\n }\n }\n}\n\nfunction startWork(request) {\n scheduleWork(function () {\n return performWork(request);\n });\n}\nfunction startFlowing(request, destination) {\n if (request.status === CLOSING) {\n request.status = CLOSED;\n closeWithError(destination, request.fatalError);\n return;\n }\n\n if (request.status === CLOSED) {\n return;\n }\n\n if (request.destination !== null) {\n // We're already flowing.\n return;\n }\n\n request.destination = destination;\n\n try {\n flushCompletedQueues(request, destination);\n } catch (error) {\n logRecoverableError(request, error);\n fatalError(request, error);\n }\n} // This is called to early terminate a request. It puts all pending boundaries in client rendered state.\n\nfunction abort(request, reason) {\n try {\n var abortableTasks = request.abortableTasks;\n abortableTasks.forEach(function (task) {\n return abortTask(task, request, reason);\n });\n abortableTasks.clear();\n\n if (request.destination !== null) {\n flushCompletedQueues(request, request.destination);\n }\n } catch (error) {\n logRecoverableError(request, error);\n fatalError(request, error);\n }\n}\n\nfunction onError() {// Non-fatal errors are ignored.\n}\n\nfunction renderToStringImpl(children, options, generateStaticMarkup, abortReason) {\n var didFatal = false;\n var fatalError = null;\n var result = '';\n var destination = {\n push: function (chunk) {\n if (chunk !== null) {\n result += chunk;\n }\n\n return true;\n },\n destroy: function (error) {\n didFatal = true;\n fatalError = error;\n }\n };\n var readyToStream = false;\n\n function onShellReady() {\n readyToStream = true;\n }\n\n var request = createRequest(children, createResponseState$1(generateStaticMarkup, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined);\n startWork(request); // If anything suspended and is still pending, we'll abort it before writing.\n // That way we write only client-rendered boundaries from the start.\n\n abort(request, abortReason);\n startFlowing(request, destination);\n\n if (didFatal) {\n throw fatalError;\n }\n\n if (!readyToStream) {\n // Note: This error message is the one we use on the client. It doesn't\n // really make sense here. But this is the legacy server renderer, anyway.\n // We're going to delete it soon.\n throw new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To fix, ' + 'updates that suspend should be wrapped with startTransition.');\n }\n\n return result;\n}\n\nfunction renderToString(children, options) {\n return renderToStringImpl(children, options, false, 'The server used \"renderToString\" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to \"renderToReadableStream\" which supports Suspense on the server');\n}\n\nfunction renderToStaticMarkup(children, options) {\n return renderToStringImpl(children, options, true, 'The server used \"renderToStaticMarkup\" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to \"renderToReadableStream\" which supports Suspense on the server');\n}\n\nfunction renderToNodeStream() {\n throw new Error('ReactDOMServer.renderToNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToString() instead.');\n}\n\nfunction renderToStaticNodeStream() {\n throw new Error('ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.');\n}\n\nexports.renderToNodeStream = renderToNodeStream;\nexports.renderToStaticMarkup = renderToStaticMarkup;\nexports.renderToStaticNodeStream = renderToStaticNodeStream;\nexports.renderToString = renderToString;\nexports.version = ReactVersion;\n })();\n}\n", "/**\n * @license React\n * react-dom-server.browser.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n'use strict';\n\nvar React = require('react');\n\nvar ReactVersion = '18.3.1';\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\n// by calls to these methods by a Babel plugin.\n//\n// In PROD (or in packages without access to React internals),\n// they are left as they are instead.\n\nfunction warn(format) {\n {\n {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n printWarning('warn', format, args);\n }\n }\n}\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\nfunction scheduleWork(callback) {\n callback();\n}\nvar VIEW_SIZE = 512;\nvar currentView = null;\nvar writtenBytes = 0;\nfunction beginWriting(destination) {\n currentView = new Uint8Array(VIEW_SIZE);\n writtenBytes = 0;\n}\nfunction writeChunk(destination, chunk) {\n if (chunk.length === 0) {\n return;\n }\n\n if (chunk.length > VIEW_SIZE) {\n // this chunk may overflow a single view which implies it was not\n // one that is cached by the streaming renderer. We will enqueu\n // it directly and expect it is not re-used\n if (writtenBytes > 0) {\n destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));\n currentView = new Uint8Array(VIEW_SIZE);\n writtenBytes = 0;\n }\n\n destination.enqueue(chunk);\n return;\n }\n\n var bytesToWrite = chunk;\n var allowableBytes = currentView.length - writtenBytes;\n\n if (allowableBytes < bytesToWrite.length) {\n // this chunk would overflow the current view. We enqueue a full view\n // and start a new view with the remaining chunk\n if (allowableBytes === 0) {\n // the current view is already full, send it\n destination.enqueue(currentView);\n } else {\n // fill up the current view and apply the remaining chunk bytes\n // to a new view.\n currentView.set(bytesToWrite.subarray(0, allowableBytes), writtenBytes); // writtenBytes += allowableBytes; // this can be skipped because we are going to immediately reset the view\n\n destination.enqueue(currentView);\n bytesToWrite = bytesToWrite.subarray(allowableBytes);\n }\n\n currentView = new Uint8Array(VIEW_SIZE);\n writtenBytes = 0;\n }\n\n currentView.set(bytesToWrite, writtenBytes);\n writtenBytes += bytesToWrite.length;\n}\nfunction writeChunkAndReturn(destination, chunk) {\n writeChunk(destination, chunk); // in web streams there is no backpressure so we can alwas write more\n\n return true;\n}\nfunction completeWriting(destination) {\n if (currentView && writtenBytes > 0) {\n destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes));\n currentView = null;\n writtenBytes = 0;\n }\n}\nfunction close(destination) {\n destination.close();\n}\nvar textEncoder = new TextEncoder();\nfunction stringToChunk(content) {\n return textEncoder.encode(content);\n}\nfunction stringToPrecomputedChunk(content) {\n return textEncoder.encode(content);\n}\nfunction closeWithError(destination, error) {\n if (typeof destination.error === 'function') {\n // $FlowFixMe: This is an Error object or the destination accepts other types.\n destination.error(error);\n } else {\n // Earlier implementations doesn't support this method. In that environment you're\n // supposed to throw from a promise returned but we don't return a promise in our\n // approach. We could fork this implementation but this is environment is an edge\n // case to begin with. It's even less common to run this in an older environment.\n // Even then, this is not where errors are supposed to happen and they get reported\n // to a global callback in addition to this anyway. So it's fine just to close this.\n destination.close();\n }\n}\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n {\n // toStringTag is needed for namespaced types like Temporal.Instant\n var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n return type;\n }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n {\n try {\n testStringCoercion(value);\n return false;\n } catch (e) {\n return true;\n }\n }\n}\n\nfunction testStringCoercion(value) {\n // If you ended up here by following an exception call stack, here's what's\n // happened: you supplied an object or symbol value to React (as a prop, key,\n // DOM attribute, CSS property, string ref, etc.) and when React tried to\n // coerce it to a string using `'' + value`, an exception was thrown.\n //\n // The most common types that will cause this exception are `Symbol` instances\n // and Temporal objects like `Temporal.Instant`. But any object that has a\n // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this\n // exception. (Library authors do this to prevent users from using built-in\n // numeric operators like `+` or comparison operators like `>=` because custom\n // methods are needed to perform accurate arithmetic or comparison.)\n //\n // To fix the problem, coerce this object or symbol value to a string before\n // passing it to React. The most reliable way is usually `String(value)`.\n //\n // To find which value is throwing, check the browser or debugger console.\n // Before this exception was thrown, there should be `console.error` output\n // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the\n // problem and how that type was used: key, atrribute, input value prop, etc.\n // In most cases, this console output also shows the component and its\n // ancestor components where the exception happened.\n //\n // eslint-disable-next-line react-internal/safe-string-coercion\n return '' + value;\n}\n\nfunction checkAttributeStringCoercion(value, attributeName) {\n {\n if (willCoercionThrow(value)) {\n error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\nfunction checkCSSPropertyStringCoercion(value, propName) {\n {\n if (willCoercionThrow(value)) {\n error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\nfunction checkHtmlStringCoercion(value) {\n {\n if (willCoercionThrow(value)) {\n error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\n// A reserved attribute.\n// It is handled by React separately and shouldn't be written to the DOM.\nvar RESERVED = 0; // A simple string attribute.\n// Attributes that aren't in the filter are presumed to have this type.\n\nvar STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called\n// \"enumerated\" attributes with \"true\" and \"false\" as possible values.\n// When true, it should be set to a \"true\" string.\n// When false, it should be set to a \"false\" string.\n\nvar BOOLEANISH_STRING = 2; // A real boolean attribute.\n// When true, it should be present (set either to an empty string or its name).\n// When false, it should be omitted.\n\nvar BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.\n// When true, it should be present (set either to an empty string or its name).\n// When false, it should be omitted.\n// For any other value, should be present with that value.\n\nvar OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.\n// When falsy, it should be removed.\n\nvar NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.\n// When falsy, it should be removed.\n\nvar POSITIVE_NUMERIC = 6;\n\n/* eslint-disable max-len */\nvar ATTRIBUTE_NAME_START_CHAR = \":A-Z_a-z\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD\";\n/* eslint-enable max-len */\n\nvar ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + \"\\\\-.0-9\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040\";\nvar VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');\nvar illegalAttributeNameCache = {};\nvar validatedAttributeNameCache = {};\nfunction isAttributeNameSafe(attributeName) {\n if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {\n return true;\n }\n\n if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {\n return false;\n }\n\n if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {\n validatedAttributeNameCache[attributeName] = true;\n return true;\n }\n\n illegalAttributeNameCache[attributeName] = true;\n\n {\n error('Invalid attribute name: `%s`', attributeName);\n }\n\n return false;\n}\nfunction shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {\n if (propertyInfo !== null && propertyInfo.type === RESERVED) {\n return false;\n }\n\n switch (typeof value) {\n case 'function': // $FlowIssue symbol is perfectly valid here\n\n case 'symbol':\n // eslint-disable-line\n return true;\n\n case 'boolean':\n {\n if (isCustomComponentTag) {\n return false;\n }\n\n if (propertyInfo !== null) {\n return !propertyInfo.acceptsBooleans;\n } else {\n var prefix = name.toLowerCase().slice(0, 5);\n return prefix !== 'data-' && prefix !== 'aria-';\n }\n }\n\n default:\n return false;\n }\n}\nfunction getPropertyInfo(name) {\n return properties.hasOwnProperty(name) ? properties[name] : null;\n}\n\nfunction PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) {\n this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;\n this.attributeName = attributeName;\n this.attributeNamespace = attributeNamespace;\n this.mustUseProperty = mustUseProperty;\n this.propertyName = name;\n this.type = type;\n this.sanitizeURL = sanitizeURL;\n this.removeEmptyString = removeEmptyString;\n} // When adding attributes to this list, be sure to also add them to\n// the `possibleStandardNames` module to ensure casing and incorrect\n// name warnings.\n\n\nvar properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.\n\nvar reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular\n// elements (not just inputs). Now that ReactDOMInput assigns to the\n// defaultValue property -- do we need this?\n'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];\n\nreservedProps.forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // A few React string attributes have a different name.\n// This is a mapping from React prop names to the attribute names.\n\n[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {\n var name = _ref[0],\n attributeName = _ref[1];\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // These are \"enumerated\" HTML attributes that accept \"true\" and \"false\".\n// In React, we let users pass `true` and `false` even though technically\n// these aren't boolean attributes (they are coerced to strings).\n\n['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty\n name.toLowerCase(), // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // These are \"enumerated\" SVG attributes that accept \"true\" and \"false\".\n// In React, we let users pass `true` and `false` even though technically\n// these aren't boolean attributes (they are coerced to strings).\n// Since these are SVG attributes, their attribute names are case-sensitive.\n\n['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // These are HTML boolean attributes.\n\n['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM\n// on the client side because the browsers are inconsistent. Instead we call focus().\n'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata\n'itemScope'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty\n name.toLowerCase(), // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // These are the few React props that we set as DOM properties\n// rather than attributes. These are all booleans.\n\n['checked', // Note: `option.selected` is not updated if `select.multiple` is\n// disabled with `removeAttribute`. We have special logic for handling this.\n'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // These are HTML attributes that are \"overloaded booleans\": they behave like\n// booleans, but can also accept a string value.\n\n['capture', 'download' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // These are HTML attributes that must be positive numbers.\n\n['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // These are HTML attributes that must be numbers.\n\n['rowSpan', 'start'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty\n name.toLowerCase(), // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n});\nvar CAMELIZE = /[\\-\\:]([a-z])/g;\n\nvar capitalize = function (token) {\n return token[1].toUpperCase();\n}; // This is a list of all SVG attributes that need special casing, namespacing,\n// or boolean value assignment. Regular attributes that just accept strings\n// and have the same names are omitted, just like in the HTML attribute filter.\n// Some of these attributes can be hard to find. This list was created by\n// scraping the MDN documentation.\n\n\n['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (attributeName) {\n var name = attributeName.replace(CAMELIZE, capitalize);\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // String SVG attributes with the xlink namespace.\n\n['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (attributeName) {\n var name = attributeName.replace(CAMELIZE, capitalize);\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL\n false);\n}); // String SVG attributes with the xml namespace.\n\n['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (attributeName) {\n var name = attributeName.replace(CAMELIZE, capitalize);\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL\n false);\n}); // These attribute exists both in HTML and SVG.\n// The attribute name is case-sensitive in SVG so we can't just use\n// the React name like we do for attributes that exist only in HTML.\n\n['tabIndex', 'crossOrigin'].forEach(function (attributeName) {\n properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty\n attributeName.toLowerCase(), // attributeName\n null, // attributeNamespace\n false, // sanitizeURL\n false);\n}); // These attributes accept URLs. These must not allow javascript: URLS.\n// These will also need to accept Trusted Types object in the future.\n\nvar xlinkHref = 'xlinkHref';\nproperties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty\n'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL\nfalse);\n['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {\n properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty\n attributeName.toLowerCase(), // attributeName\n null, // attributeNamespace\n true, // sanitizeURL\n true);\n});\n\n/**\n * CSS properties which accept numbers but are not in units of \"px\".\n */\nvar isUnitlessNumber = {\n animationIterationCount: true,\n aspectRatio: true,\n borderImageOutset: true,\n borderImageSlice: true,\n borderImageWidth: true,\n boxFlex: true,\n boxFlexGroup: true,\n boxOrdinalGroup: true,\n columnCount: true,\n columns: true,\n flex: true,\n flexGrow: true,\n flexPositive: true,\n flexShrink: true,\n flexNegative: true,\n flexOrder: true,\n gridArea: true,\n gridRow: true,\n gridRowEnd: true,\n gridRowSpan: true,\n gridRowStart: true,\n gridColumn: true,\n gridColumnEnd: true,\n gridColumnSpan: true,\n gridColumnStart: true,\n fontWeight: true,\n lineClamp: true,\n lineHeight: true,\n opacity: true,\n order: true,\n orphans: true,\n tabSize: true,\n widows: true,\n zIndex: true,\n zoom: true,\n // SVG-related properties\n fillOpacity: true,\n floodOpacity: true,\n stopOpacity: true,\n strokeDasharray: true,\n strokeDashoffset: true,\n strokeMiterlimit: true,\n strokeOpacity: true,\n strokeWidth: true\n};\n/**\n * @param {string} prefix vendor-specific prefix, eg: Webkit\n * @param {string} key style name, eg: transitionDuration\n * @return {string} style name prefixed with `prefix`, properly camelCased, eg:\n * WebkitTransitionDuration\n */\n\nfunction prefixKey(prefix, key) {\n return prefix + key.charAt(0).toUpperCase() + key.substring(1);\n}\n/**\n * Support style names that may come passed in prefixed by adding permutations\n * of vendor prefixes.\n */\n\n\nvar prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an\n// infinite loop, because it iterates over the newly added props too.\n\nObject.keys(isUnitlessNumber).forEach(function (prop) {\n prefixes.forEach(function (prefix) {\n isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];\n });\n});\n\nvar hasReadOnlyValue = {\n button: true,\n checkbox: true,\n image: true,\n hidden: true,\n radio: true,\n reset: true,\n submit: true\n};\nfunction checkControlledValueProps(tagName, props) {\n {\n if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {\n error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');\n }\n\n if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {\n error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');\n }\n }\n}\n\nfunction isCustomComponent(tagName, props) {\n if (tagName.indexOf('-') === -1) {\n return typeof props.is === 'string';\n }\n\n switch (tagName) {\n // These are reserved SVG and MathML elements.\n // We don't mind this list too much because we expect it to never grow.\n // The alternative is to track the namespace in a few places which is convoluted.\n // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts\n case 'annotation-xml':\n case 'color-profile':\n case 'font-face':\n case 'font-face-src':\n case 'font-face-uri':\n case 'font-face-format':\n case 'font-face-name':\n case 'missing-glyph':\n return false;\n\n default:\n return true;\n }\n}\n\nvar ariaProperties = {\n 'aria-current': 0,\n // state\n 'aria-description': 0,\n 'aria-details': 0,\n 'aria-disabled': 0,\n // state\n 'aria-hidden': 0,\n // state\n 'aria-invalid': 0,\n // state\n 'aria-keyshortcuts': 0,\n 'aria-label': 0,\n 'aria-roledescription': 0,\n // Widget Attributes\n 'aria-autocomplete': 0,\n 'aria-checked': 0,\n 'aria-expanded': 0,\n 'aria-haspopup': 0,\n 'aria-level': 0,\n 'aria-modal': 0,\n 'aria-multiline': 0,\n 'aria-multiselectable': 0,\n 'aria-orientation': 0,\n 'aria-placeholder': 0,\n 'aria-pressed': 0,\n 'aria-readonly': 0,\n 'aria-required': 0,\n 'aria-selected': 0,\n 'aria-sort': 0,\n 'aria-valuemax': 0,\n 'aria-valuemin': 0,\n 'aria-valuenow': 0,\n 'aria-valuetext': 0,\n // Live Region Attributes\n 'aria-atomic': 0,\n 'aria-busy': 0,\n 'aria-live': 0,\n 'aria-relevant': 0,\n // Drag-and-Drop Attributes\n 'aria-dropeffect': 0,\n 'aria-grabbed': 0,\n // Relationship Attributes\n 'aria-activedescendant': 0,\n 'aria-colcount': 0,\n 'aria-colindex': 0,\n 'aria-colspan': 0,\n 'aria-controls': 0,\n 'aria-describedby': 0,\n 'aria-errormessage': 0,\n 'aria-flowto': 0,\n 'aria-labelledby': 0,\n 'aria-owns': 0,\n 'aria-posinset': 0,\n 'aria-rowcount': 0,\n 'aria-rowindex': 0,\n 'aria-rowspan': 0,\n 'aria-setsize': 0\n};\n\nvar warnedProperties = {};\nvar rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');\nvar rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');\n\nfunction validateProperty(tagName, name) {\n {\n if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {\n return true;\n }\n\n if (rARIACamel.test(name)) {\n var ariaName = 'aria-' + name.slice(4).toLowerCase();\n var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM\n // DOM properties, then it is an invalid aria-* attribute.\n\n if (correctName == null) {\n error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);\n\n warnedProperties[name] = true;\n return true;\n } // aria-* attributes should be lowercase; suggest the lowercase version.\n\n\n if (name !== correctName) {\n error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);\n\n warnedProperties[name] = true;\n return true;\n }\n }\n\n if (rARIA.test(name)) {\n var lowerCasedName = name.toLowerCase();\n var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM\n // DOM properties, then it is an invalid aria-* attribute.\n\n if (standardName == null) {\n warnedProperties[name] = true;\n return false;\n } // aria-* attributes should be lowercase; suggest the lowercase version.\n\n\n if (name !== standardName) {\n error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);\n\n warnedProperties[name] = true;\n return true;\n }\n }\n }\n\n return true;\n}\n\nfunction warnInvalidARIAProps(type, props) {\n {\n var invalidProps = [];\n\n for (var key in props) {\n var isValid = validateProperty(type, key);\n\n if (!isValid) {\n invalidProps.push(key);\n }\n }\n\n var unknownPropString = invalidProps.map(function (prop) {\n return '`' + prop + '`';\n }).join(', ');\n\n if (invalidProps.length === 1) {\n error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);\n } else if (invalidProps.length > 1) {\n error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type);\n }\n }\n}\n\nfunction validateProperties(type, props) {\n if (isCustomComponent(type, props)) {\n return;\n }\n\n warnInvalidARIAProps(type, props);\n}\n\nvar didWarnValueNull = false;\nfunction validateProperties$1(type, props) {\n {\n if (type !== 'input' && type !== 'textarea' && type !== 'select') {\n return;\n }\n\n if (props != null && props.value === null && !didWarnValueNull) {\n didWarnValueNull = true;\n\n if (type === 'select' && props.multiple) {\n error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);\n } else {\n error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);\n }\n }\n }\n}\n\n// When adding attributes to the HTML or SVG allowed attribute list, be sure to\n// also add them to this module to ensure casing and incorrect name\n// warnings.\nvar possibleStandardNames = {\n // HTML\n accept: 'accept',\n acceptcharset: 'acceptCharset',\n 'accept-charset': 'acceptCharset',\n accesskey: 'accessKey',\n action: 'action',\n allowfullscreen: 'allowFullScreen',\n alt: 'alt',\n as: 'as',\n async: 'async',\n autocapitalize: 'autoCapitalize',\n autocomplete: 'autoComplete',\n autocorrect: 'autoCorrect',\n autofocus: 'autoFocus',\n autoplay: 'autoPlay',\n autosave: 'autoSave',\n capture: 'capture',\n cellpadding: 'cellPadding',\n cellspacing: 'cellSpacing',\n challenge: 'challenge',\n charset: 'charSet',\n checked: 'checked',\n children: 'children',\n cite: 'cite',\n class: 'className',\n classid: 'classID',\n classname: 'className',\n cols: 'cols',\n colspan: 'colSpan',\n content: 'content',\n contenteditable: 'contentEditable',\n contextmenu: 'contextMenu',\n controls: 'controls',\n controlslist: 'controlsList',\n coords: 'coords',\n crossorigin: 'crossOrigin',\n dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',\n data: 'data',\n datetime: 'dateTime',\n default: 'default',\n defaultchecked: 'defaultChecked',\n defaultvalue: 'defaultValue',\n defer: 'defer',\n dir: 'dir',\n disabled: 'disabled',\n disablepictureinpicture: 'disablePictureInPicture',\n disableremoteplayback: 'disableRemotePlayback',\n download: 'download',\n draggable: 'draggable',\n enctype: 'encType',\n enterkeyhint: 'enterKeyHint',\n for: 'htmlFor',\n form: 'form',\n formmethod: 'formMethod',\n formaction: 'formAction',\n formenctype: 'formEncType',\n formnovalidate: 'formNoValidate',\n formtarget: 'formTarget',\n frameborder: 'frameBorder',\n headers: 'headers',\n height: 'height',\n hidden: 'hidden',\n high: 'high',\n href: 'href',\n hreflang: 'hrefLang',\n htmlfor: 'htmlFor',\n httpequiv: 'httpEquiv',\n 'http-equiv': 'httpEquiv',\n icon: 'icon',\n id: 'id',\n imagesizes: 'imageSizes',\n imagesrcset: 'imageSrcSet',\n innerhtml: 'innerHTML',\n inputmode: 'inputMode',\n integrity: 'integrity',\n is: 'is',\n itemid: 'itemID',\n itemprop: 'itemProp',\n itemref: 'itemRef',\n itemscope: 'itemScope',\n itemtype: 'itemType',\n keyparams: 'keyParams',\n keytype: 'keyType',\n kind: 'kind',\n label: 'label',\n lang: 'lang',\n list: 'list',\n loop: 'loop',\n low: 'low',\n manifest: 'manifest',\n marginwidth: 'marginWidth',\n marginheight: 'marginHeight',\n max: 'max',\n maxlength: 'maxLength',\n media: 'media',\n mediagroup: 'mediaGroup',\n method: 'method',\n min: 'min',\n minlength: 'minLength',\n multiple: 'multiple',\n muted: 'muted',\n name: 'name',\n nomodule: 'noModule',\n nonce: 'nonce',\n novalidate: 'noValidate',\n open: 'open',\n optimum: 'optimum',\n pattern: 'pattern',\n placeholder: 'placeholder',\n playsinline: 'playsInline',\n poster: 'poster',\n preload: 'preload',\n profile: 'profile',\n radiogroup: 'radioGroup',\n readonly: 'readOnly',\n referrerpolicy: 'referrerPolicy',\n rel: 'rel',\n required: 'required',\n reversed: 'reversed',\n role: 'role',\n rows: 'rows',\n rowspan: 'rowSpan',\n sandbox: 'sandbox',\n scope: 'scope',\n scoped: 'scoped',\n scrolling: 'scrolling',\n seamless: 'seamless',\n selected: 'selected',\n shape: 'shape',\n size: 'size',\n sizes: 'sizes',\n span: 'span',\n spellcheck: 'spellCheck',\n src: 'src',\n srcdoc: 'srcDoc',\n srclang: 'srcLang',\n srcset: 'srcSet',\n start: 'start',\n step: 'step',\n style: 'style',\n summary: 'summary',\n tabindex: 'tabIndex',\n target: 'target',\n title: 'title',\n type: 'type',\n usemap: 'useMap',\n value: 'value',\n width: 'width',\n wmode: 'wmode',\n wrap: 'wrap',\n // SVG\n about: 'about',\n accentheight: 'accentHeight',\n 'accent-height': 'accentHeight',\n accumulate: 'accumulate',\n additive: 'additive',\n alignmentbaseline: 'alignmentBaseline',\n 'alignment-baseline': 'alignmentBaseline',\n allowreorder: 'allowReorder',\n alphabetic: 'alphabetic',\n amplitude: 'amplitude',\n arabicform: 'arabicForm',\n 'arabic-form': 'arabicForm',\n ascent: 'ascent',\n attributename: 'attributeName',\n attributetype: 'attributeType',\n autoreverse: 'autoReverse',\n azimuth: 'azimuth',\n basefrequency: 'baseFrequency',\n baselineshift: 'baselineShift',\n 'baseline-shift': 'baselineShift',\n baseprofile: 'baseProfile',\n bbox: 'bbox',\n begin: 'begin',\n bias: 'bias',\n by: 'by',\n calcmode: 'calcMode',\n capheight: 'capHeight',\n 'cap-height': 'capHeight',\n clip: 'clip',\n clippath: 'clipPath',\n 'clip-path': 'clipPath',\n clippathunits: 'clipPathUnits',\n cliprule: 'clipRule',\n 'clip-rule': 'clipRule',\n color: 'color',\n colorinterpolation: 'colorInterpolation',\n 'color-interpolation': 'colorInterpolation',\n colorinterpolationfilters: 'colorInterpolationFilters',\n 'color-interpolation-filters': 'colorInterpolationFilters',\n colorprofile: 'colorProfile',\n 'color-profile': 'colorProfile',\n colorrendering: 'colorRendering',\n 'color-rendering': 'colorRendering',\n contentscripttype: 'contentScriptType',\n contentstyletype: 'contentStyleType',\n cursor: 'cursor',\n cx: 'cx',\n cy: 'cy',\n d: 'd',\n datatype: 'datatype',\n decelerate: 'decelerate',\n descent: 'descent',\n diffuseconstant: 'diffuseConstant',\n direction: 'direction',\n display: 'display',\n divisor: 'divisor',\n dominantbaseline: 'dominantBaseline',\n 'dominant-baseline': 'dominantBaseline',\n dur: 'dur',\n dx: 'dx',\n dy: 'dy',\n edgemode: 'edgeMode',\n elevation: 'elevation',\n enablebackground: 'enableBackground',\n 'enable-background': 'enableBackground',\n end: 'end',\n exponent: 'exponent',\n externalresourcesrequired: 'externalResourcesRequired',\n fill: 'fill',\n fillopacity: 'fillOpacity',\n 'fill-opacity': 'fillOpacity',\n fillrule: 'fillRule',\n 'fill-rule': 'fillRule',\n filter: 'filter',\n filterres: 'filterRes',\n filterunits: 'filterUnits',\n floodopacity: 'floodOpacity',\n 'flood-opacity': 'floodOpacity',\n floodcolor: 'floodColor',\n 'flood-color': 'floodColor',\n focusable: 'focusable',\n fontfamily: 'fontFamily',\n 'font-family': 'fontFamily',\n fontsize: 'fontSize',\n 'font-size': 'fontSize',\n fontsizeadjust: 'fontSizeAdjust',\n 'font-size-adjust': 'fontSizeAdjust',\n fontstretch: 'fontStretch',\n 'font-stretch': 'fontStretch',\n fontstyle: 'fontStyle',\n 'font-style': 'fontStyle',\n fontvariant: 'fontVariant',\n 'font-variant': 'fontVariant',\n fontweight: 'fontWeight',\n 'font-weight': 'fontWeight',\n format: 'format',\n from: 'from',\n fx: 'fx',\n fy: 'fy',\n g1: 'g1',\n g2: 'g2',\n glyphname: 'glyphName',\n 'glyph-name': 'glyphName',\n glyphorientationhorizontal: 'glyphOrientationHorizontal',\n 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',\n glyphorientationvertical: 'glyphOrientationVertical',\n 'glyph-orientation-vertical': 'glyphOrientationVertical',\n glyphref: 'glyphRef',\n gradienttransform: 'gradientTransform',\n gradientunits: 'gradientUnits',\n hanging: 'hanging',\n horizadvx: 'horizAdvX',\n 'horiz-adv-x': 'horizAdvX',\n horizoriginx: 'horizOriginX',\n 'horiz-origin-x': 'horizOriginX',\n ideographic: 'ideographic',\n imagerendering: 'imageRendering',\n 'image-rendering': 'imageRendering',\n in2: 'in2',\n in: 'in',\n inlist: 'inlist',\n intercept: 'intercept',\n k1: 'k1',\n k2: 'k2',\n k3: 'k3',\n k4: 'k4',\n k: 'k',\n kernelmatrix: 'kernelMatrix',\n kernelunitlength: 'kernelUnitLength',\n kerning: 'kerning',\n keypoints: 'keyPoints',\n keysplines: 'keySplines',\n keytimes: 'keyTimes',\n lengthadjust: 'lengthAdjust',\n letterspacing: 'letterSpacing',\n 'letter-spacing': 'letterSpacing',\n lightingcolor: 'lightingColor',\n 'lighting-color': 'lightingColor',\n limitingconeangle: 'limitingConeAngle',\n local: 'local',\n markerend: 'markerEnd',\n 'marker-end': 'markerEnd',\n markerheight: 'markerHeight',\n markermid: 'markerMid',\n 'marker-mid': 'markerMid',\n markerstart: 'markerStart',\n 'marker-start': 'markerStart',\n markerunits: 'markerUnits',\n markerwidth: 'markerWidth',\n mask: 'mask',\n maskcontentunits: 'maskContentUnits',\n maskunits: 'maskUnits',\n mathematical: 'mathematical',\n mode: 'mode',\n numoctaves: 'numOctaves',\n offset: 'offset',\n opacity: 'opacity',\n operator: 'operator',\n order: 'order',\n orient: 'orient',\n orientation: 'orientation',\n origin: 'origin',\n overflow: 'overflow',\n overlineposition: 'overlinePosition',\n 'overline-position': 'overlinePosition',\n overlinethickness: 'overlineThickness',\n 'overline-thickness': 'overlineThickness',\n paintorder: 'paintOrder',\n 'paint-order': 'paintOrder',\n panose1: 'panose1',\n 'panose-1': 'panose1',\n pathlength: 'pathLength',\n patterncontentunits: 'patternContentUnits',\n patterntransform: 'patternTransform',\n patternunits: 'patternUnits',\n pointerevents: 'pointerEvents',\n 'pointer-events': 'pointerEvents',\n points: 'points',\n pointsatx: 'pointsAtX',\n pointsaty: 'pointsAtY',\n pointsatz: 'pointsAtZ',\n prefix: 'prefix',\n preservealpha: 'preserveAlpha',\n preserveaspectratio: 'preserveAspectRatio',\n primitiveunits: 'primitiveUnits',\n property: 'property',\n r: 'r',\n radius: 'radius',\n refx: 'refX',\n refy: 'refY',\n renderingintent: 'renderingIntent',\n 'rendering-intent': 'renderingIntent',\n repeatcount: 'repeatCount',\n repeatdur: 'repeatDur',\n requiredextensions: 'requiredExtensions',\n requiredfeatures: 'requiredFeatures',\n resource: 'resource',\n restart: 'restart',\n result: 'result',\n results: 'results',\n rotate: 'rotate',\n rx: 'rx',\n ry: 'ry',\n scale: 'scale',\n security: 'security',\n seed: 'seed',\n shaperendering: 'shapeRendering',\n 'shape-rendering': 'shapeRendering',\n slope: 'slope',\n spacing: 'spacing',\n specularconstant: 'specularConstant',\n specularexponent: 'specularExponent',\n speed: 'speed',\n spreadmethod: 'spreadMethod',\n startoffset: 'startOffset',\n stddeviation: 'stdDeviation',\n stemh: 'stemh',\n stemv: 'stemv',\n stitchtiles: 'stitchTiles',\n stopcolor: 'stopColor',\n 'stop-color': 'stopColor',\n stopopacity: 'stopOpacity',\n 'stop-opacity': 'stopOpacity',\n strikethroughposition: 'strikethroughPosition',\n 'strikethrough-position': 'strikethroughPosition',\n strikethroughthickness: 'strikethroughThickness',\n 'strikethrough-thickness': 'strikethroughThickness',\n string: 'string',\n stroke: 'stroke',\n strokedasharray: 'strokeDasharray',\n 'stroke-dasharray': 'strokeDasharray',\n strokedashoffset: 'strokeDashoffset',\n 'stroke-dashoffset': 'strokeDashoffset',\n strokelinecap: 'strokeLinecap',\n 'stroke-linecap': 'strokeLinecap',\n strokelinejoin: 'strokeLinejoin',\n 'stroke-linejoin': 'strokeLinejoin',\n strokemiterlimit: 'strokeMiterlimit',\n 'stroke-miterlimit': 'strokeMiterlimit',\n strokewidth: 'strokeWidth',\n 'stroke-width': 'strokeWidth',\n strokeopacity: 'strokeOpacity',\n 'stroke-opacity': 'strokeOpacity',\n suppresscontenteditablewarning: 'suppressContentEditableWarning',\n suppresshydrationwarning: 'suppressHydrationWarning',\n surfacescale: 'surfaceScale',\n systemlanguage: 'systemLanguage',\n tablevalues: 'tableValues',\n targetx: 'targetX',\n targety: 'targetY',\n textanchor: 'textAnchor',\n 'text-anchor': 'textAnchor',\n textdecoration: 'textDecoration',\n 'text-decoration': 'textDecoration',\n textlength: 'textLength',\n textrendering: 'textRendering',\n 'text-rendering': 'textRendering',\n to: 'to',\n transform: 'transform',\n typeof: 'typeof',\n u1: 'u1',\n u2: 'u2',\n underlineposition: 'underlinePosition',\n 'underline-position': 'underlinePosition',\n underlinethickness: 'underlineThickness',\n 'underline-thickness': 'underlineThickness',\n unicode: 'unicode',\n unicodebidi: 'unicodeBidi',\n 'unicode-bidi': 'unicodeBidi',\n unicoderange: 'unicodeRange',\n 'unicode-range': 'unicodeRange',\n unitsperem: 'unitsPerEm',\n 'units-per-em': 'unitsPerEm',\n unselectable: 'unselectable',\n valphabetic: 'vAlphabetic',\n 'v-alphabetic': 'vAlphabetic',\n values: 'values',\n vectoreffect: 'vectorEffect',\n 'vector-effect': 'vectorEffect',\n version: 'version',\n vertadvy: 'vertAdvY',\n 'vert-adv-y': 'vertAdvY',\n vertoriginx: 'vertOriginX',\n 'vert-origin-x': 'vertOriginX',\n vertoriginy: 'vertOriginY',\n 'vert-origin-y': 'vertOriginY',\n vhanging: 'vHanging',\n 'v-hanging': 'vHanging',\n videographic: 'vIdeographic',\n 'v-ideographic': 'vIdeographic',\n viewbox: 'viewBox',\n viewtarget: 'viewTarget',\n visibility: 'visibility',\n vmathematical: 'vMathematical',\n 'v-mathematical': 'vMathematical',\n vocab: 'vocab',\n widths: 'widths',\n wordspacing: 'wordSpacing',\n 'word-spacing': 'wordSpacing',\n writingmode: 'writingMode',\n 'writing-mode': 'writingMode',\n x1: 'x1',\n x2: 'x2',\n x: 'x',\n xchannelselector: 'xChannelSelector',\n xheight: 'xHeight',\n 'x-height': 'xHeight',\n xlinkactuate: 'xlinkActuate',\n 'xlink:actuate': 'xlinkActuate',\n xlinkarcrole: 'xlinkArcrole',\n 'xlink:arcrole': 'xlinkArcrole',\n xlinkhref: 'xlinkHref',\n 'xlink:href': 'xlinkHref',\n xlinkrole: 'xlinkRole',\n 'xlink:role': 'xlinkRole',\n xlinkshow: 'xlinkShow',\n 'xlink:show': 'xlinkShow',\n xlinktitle: 'xlinkTitle',\n 'xlink:title': 'xlinkTitle',\n xlinktype: 'xlinkType',\n 'xlink:type': 'xlinkType',\n xmlbase: 'xmlBase',\n 'xml:base': 'xmlBase',\n xmllang: 'xmlLang',\n 'xml:lang': 'xmlLang',\n xmlns: 'xmlns',\n 'xml:space': 'xmlSpace',\n xmlnsxlink: 'xmlnsXlink',\n 'xmlns:xlink': 'xmlnsXlink',\n xmlspace: 'xmlSpace',\n y1: 'y1',\n y2: 'y2',\n y: 'y',\n ychannelselector: 'yChannelSelector',\n z: 'z',\n zoomandpan: 'zoomAndPan'\n};\n\nvar validateProperty$1 = function () {};\n\n{\n var warnedProperties$1 = {};\n var EVENT_NAME_REGEX = /^on./;\n var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;\n var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');\n var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');\n\n validateProperty$1 = function (tagName, name, value, eventRegistry) {\n if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {\n return true;\n }\n\n var lowerCasedName = name.toLowerCase();\n\n if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {\n error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');\n\n warnedProperties$1[name] = true;\n return true;\n } // We can't rely on the event system being injected on the server.\n\n\n if (eventRegistry != null) {\n var registrationNameDependencies = eventRegistry.registrationNameDependencies,\n possibleRegistrationNames = eventRegistry.possibleRegistrationNames;\n\n if (registrationNameDependencies.hasOwnProperty(name)) {\n return true;\n }\n\n var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;\n\n if (registrationName != null) {\n error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (EVENT_NAME_REGEX.test(name)) {\n error('Unknown event handler property `%s`. It will be ignored.', name);\n\n warnedProperties$1[name] = true;\n return true;\n }\n } else if (EVENT_NAME_REGEX.test(name)) {\n // If no event plugins have been injected, we are in a server environment.\n // So we can't tell if the event name is correct for sure, but we can filter\n // out known bad ones like `onclick`. We can't suggest a specific replacement though.\n if (INVALID_EVENT_NAME_REGEX.test(name)) {\n error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);\n }\n\n warnedProperties$1[name] = true;\n return true;\n } // Let the ARIA attribute hook validate ARIA attributes\n\n\n if (rARIA$1.test(name) || rARIACamel$1.test(name)) {\n return true;\n }\n\n if (lowerCasedName === 'innerhtml') {\n error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (lowerCasedName === 'aria') {\n error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {\n error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (typeof value === 'number' && isNaN(value)) {\n error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n var propertyInfo = getPropertyInfo(name);\n var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.\n\n if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {\n var standardName = possibleStandardNames[lowerCasedName];\n\n if (standardName !== name) {\n error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);\n\n warnedProperties$1[name] = true;\n return true;\n }\n } else if (!isReserved && name !== lowerCasedName) {\n // Unknown attributes should have lowercase casing since that's how they\n // will be cased anyway with server rendering.\n error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {\n if (value) {\n error('Received `%s` for a non-boolean attribute `%s`.\\n\\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s=\"%s\" or %s={value.toString()}.', value, name, name, value, name);\n } else {\n error('Received `%s` for a non-boolean attribute `%s`.\\n\\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s=\"%s\" or %s={value.toString()}.\\n\\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);\n }\n\n warnedProperties$1[name] = true;\n return true;\n } // Now that we've validated casing, do not validate\n // data types for reserved props\n\n\n if (isReserved) {\n return true;\n } // Warn when a known attribute is a bad type\n\n\n if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {\n warnedProperties$1[name] = true;\n return false;\n } // Warn when passing the strings 'false' or 'true' into a boolean prop\n\n\n if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {\n error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string \"false\".', name, value);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n return true;\n };\n}\n\nvar warnUnknownProperties = function (type, props, eventRegistry) {\n {\n var unknownProps = [];\n\n for (var key in props) {\n var isValid = validateProperty$1(type, key, props[key], eventRegistry);\n\n if (!isValid) {\n unknownProps.push(key);\n }\n }\n\n var unknownPropString = unknownProps.map(function (prop) {\n return '`' + prop + '`';\n }).join(', ');\n\n if (unknownProps.length === 1) {\n error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);\n } else if (unknownProps.length > 1) {\n error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type);\n }\n }\n};\n\nfunction validateProperties$2(type, props, eventRegistry) {\n if (isCustomComponent(type, props)) {\n return;\n }\n\n warnUnknownProperties(type, props, eventRegistry);\n}\n\nvar warnValidStyle = function () {};\n\n{\n // 'msTransform' is correct, but the other prefixes should be capitalized\n var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;\n var msPattern = /^-ms-/;\n var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon\n\n var badStyleValueWithSemicolonPattern = /;\\s*$/;\n var warnedStyleNames = {};\n var warnedStyleValues = {};\n var warnedForNaNValue = false;\n var warnedForInfinityValue = false;\n\n var camelize = function (string) {\n return string.replace(hyphenPattern, function (_, character) {\n return character.toUpperCase();\n });\n };\n\n var warnHyphenatedStyleName = function (name) {\n if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {\n return;\n }\n\n warnedStyleNames[name] = true;\n\n error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests\n // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix\n // is converted to lowercase `ms`.\n camelize(name.replace(msPattern, 'ms-')));\n };\n\n var warnBadVendoredStyleName = function (name) {\n if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {\n return;\n }\n\n warnedStyleNames[name] = true;\n\n error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));\n };\n\n var warnStyleValueWithSemicolon = function (name, value) {\n if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {\n return;\n }\n\n warnedStyleValues[value] = true;\n\n error(\"Style property values shouldn't contain a semicolon. \" + 'Try \"%s: %s\" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));\n };\n\n var warnStyleValueIsNaN = function (name, value) {\n if (warnedForNaNValue) {\n return;\n }\n\n warnedForNaNValue = true;\n\n error('`NaN` is an invalid value for the `%s` css style property.', name);\n };\n\n var warnStyleValueIsInfinity = function (name, value) {\n if (warnedForInfinityValue) {\n return;\n }\n\n warnedForInfinityValue = true;\n\n error('`Infinity` is an invalid value for the `%s` css style property.', name);\n };\n\n warnValidStyle = function (name, value) {\n if (name.indexOf('-') > -1) {\n warnHyphenatedStyleName(name);\n } else if (badVendoredStyleNamePattern.test(name)) {\n warnBadVendoredStyleName(name);\n } else if (badStyleValueWithSemicolonPattern.test(value)) {\n warnStyleValueWithSemicolon(name, value);\n }\n\n if (typeof value === 'number') {\n if (isNaN(value)) {\n warnStyleValueIsNaN(name, value);\n } else if (!isFinite(value)) {\n warnStyleValueIsInfinity(name, value);\n }\n }\n };\n}\n\nvar warnValidStyle$1 = warnValidStyle;\n\n// code copied and modified from escape-html\nvar matchHtmlRegExp = /[\"'&<>]/;\n/**\n * Escapes special characters and HTML entities in a given html string.\n *\n * @param {string} string HTML string to escape for later insertion\n * @return {string}\n * @public\n */\n\nfunction escapeHtml(string) {\n {\n checkHtmlStringCoercion(string);\n }\n\n var str = '' + string;\n var match = matchHtmlRegExp.exec(str);\n\n if (!match) {\n return str;\n }\n\n var escape;\n var html = '';\n var index;\n var lastIndex = 0;\n\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n // \"\n escape = '"';\n break;\n\n case 38:\n // &\n escape = '&';\n break;\n\n case 39:\n // '\n escape = '''; // modified from escape-html; used to be '''\n\n break;\n\n case 60:\n // <\n escape = '<';\n break;\n\n case 62:\n // >\n escape = '>';\n break;\n\n default:\n continue;\n }\n\n if (lastIndex !== index) {\n html += str.substring(lastIndex, index);\n }\n\n lastIndex = index + 1;\n html += escape;\n }\n\n return lastIndex !== index ? html + str.substring(lastIndex, index) : html;\n} // end code copied and modified from escape-html\n\n/**\n * Escapes text to prevent scripting attacks.\n *\n * @param {*} text Text value to escape.\n * @return {string} An escaped string.\n */\n\n\nfunction escapeTextForBrowser(text) {\n if (typeof text === 'boolean' || typeof text === 'number') {\n // this shortcircuit helps perf for types that we know will never have\n // special characters, especially given that this function is used often\n // for numeric dom ids.\n return '' + text;\n }\n\n return escapeHtml(text);\n}\n\nvar uppercasePattern = /([A-Z])/g;\nvar msPattern$1 = /^ms-/;\n/**\n * Hyphenates a camelcased CSS property name, for example:\n *\n * > hyphenateStyleName('backgroundColor')\n * < \"background-color\"\n * > hyphenateStyleName('MozTransition')\n * < \"-moz-transition\"\n * > hyphenateStyleName('msTransition')\n * < \"-ms-transition\"\n *\n * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix\n * is converted to `-ms-`.\n */\n\nfunction hyphenateStyleName(name) {\n return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-');\n}\n\n// and any newline or tab are filtered out as if they're not part of the URL.\n// https://url.spec.whatwg.org/#url-parsing\n// Tab or newline are defined as \\r\\n\\t:\n// https://infra.spec.whatwg.org/#ascii-tab-or-newline\n// A C0 control is a code point in the range \\u0000 NULL to \\u001F\n// INFORMATION SEPARATOR ONE, inclusive:\n// https://infra.spec.whatwg.org/#c0-control-or-space\n\n/* eslint-disable max-len */\n\nvar isJavaScriptProtocol = /^[\\u0000-\\u001F ]*j[\\r\\n\\t]*a[\\r\\n\\t]*v[\\r\\n\\t]*a[\\r\\n\\t]*s[\\r\\n\\t]*c[\\r\\n\\t]*r[\\r\\n\\t]*i[\\r\\n\\t]*p[\\r\\n\\t]*t[\\r\\n\\t]*\\:/i;\nvar didWarn = false;\n\nfunction sanitizeURL(url) {\n {\n if (!didWarn && isJavaScriptProtocol.test(url)) {\n didWarn = true;\n\n error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));\n }\n }\n}\n\nvar isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare\n\nfunction isArray(a) {\n return isArrayImpl(a);\n}\n\nvar startInlineScript = stringToPrecomputedChunk('');\nvar startScriptSrc = stringToPrecomputedChunk('');\n/**\n * This escaping function is designed to work with bootstrapScriptContent only.\n * because we know we are escaping the entire script. We can avoid for instance\n * escaping html comment string sequences that are valid javascript as well because\n * if there are no sebsequent ');\nfunction writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) {\n writeChunk(destination, responseState.startInlineScript);\n\n if (!responseState.sentCompleteSegmentFunction) {\n // The first time we write this, we'll need to include the full implementation.\n responseState.sentCompleteSegmentFunction = true;\n writeChunk(destination, completeSegmentScript1Full);\n } else {\n // Future calls can just reuse the same function.\n writeChunk(destination, completeSegmentScript1Partial);\n }\n\n writeChunk(destination, responseState.segmentPrefix);\n var formattedID = stringToChunk(contentSegmentID.toString(16));\n writeChunk(destination, formattedID);\n writeChunk(destination, completeSegmentScript2);\n writeChunk(destination, responseState.placeholderPrefix);\n writeChunk(destination, formattedID);\n return writeChunkAndReturn(destination, completeSegmentScript3);\n}\nvar completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC(\"');\nvar completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC(\"');\nvar completeBoundaryScript2 = stringToPrecomputedChunk('\",\"');\nvar completeBoundaryScript3 = stringToPrecomputedChunk('\")');\nfunction writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) {\n writeChunk(destination, responseState.startInlineScript);\n\n if (!responseState.sentCompleteBoundaryFunction) {\n // The first time we write this, we'll need to include the full implementation.\n responseState.sentCompleteBoundaryFunction = true;\n writeChunk(destination, completeBoundaryScript1Full);\n } else {\n // Future calls can just reuse the same function.\n writeChunk(destination, completeBoundaryScript1Partial);\n }\n\n if (boundaryID === null) {\n throw new Error('An ID must have been assigned before we can complete the boundary.');\n }\n\n var formattedContentID = stringToChunk(contentSegmentID.toString(16));\n writeChunk(destination, boundaryID);\n writeChunk(destination, completeBoundaryScript2);\n writeChunk(destination, responseState.segmentPrefix);\n writeChunk(destination, formattedContentID);\n return writeChunkAndReturn(destination, completeBoundaryScript3);\n}\nvar clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX(\"');\nvar clientRenderScript1Partial = stringToPrecomputedChunk('$RX(\"');\nvar clientRenderScript1A = stringToPrecomputedChunk('\"');\nvar clientRenderScript2 = stringToPrecomputedChunk(')');\nvar clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(',');\nfunction writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) {\n writeChunk(destination, responseState.startInlineScript);\n\n if (!responseState.sentClientRenderFunction) {\n // The first time we write this, we'll need to include the full implementation.\n responseState.sentClientRenderFunction = true;\n writeChunk(destination, clientRenderScript1Full);\n } else {\n // Future calls can just reuse the same function.\n writeChunk(destination, clientRenderScript1Partial);\n }\n\n if (boundaryID === null) {\n throw new Error('An ID must have been assigned before we can complete the boundary.');\n }\n\n writeChunk(destination, boundaryID);\n writeChunk(destination, clientRenderScript1A);\n\n if (errorDigest || errorMessage || errorComponentStack) {\n writeChunk(destination, clientRenderErrorScriptArgInterstitial);\n writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || '')));\n }\n\n if (errorMessage || errorComponentStack) {\n writeChunk(destination, clientRenderErrorScriptArgInterstitial);\n writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || '')));\n }\n\n if (errorComponentStack) {\n writeChunk(destination, clientRenderErrorScriptArgInterstitial);\n writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack)));\n }\n\n return writeChunkAndReturn(destination, clientRenderScript2);\n}\nvar regexForJSStringsInScripts = /[<\\u2028\\u2029]/g;\n\nfunction escapeJSStringsForInstructionScripts(input) {\n var escaped = JSON.stringify(input);\n return escaped.replace(regexForJSStringsInScripts, function (match) {\n switch (match) {\n // santizing breaking out of strings and script tags\n case '<':\n return \"\\\\u003c\";\n\n case \"\\u2028\":\n return \"\\\\u2028\";\n\n case \"\\u2029\":\n return \"\\\\u2029\";\n\n default:\n {\n // eslint-disable-next-line react-internal/prod-error-codes\n throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React');\n }\n }\n });\n}\n\nvar assign = Object.assign;\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_SCOPE_TYPE = Symbol.for('react.scope');\nvar REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode');\nvar REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden');\nvar REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var displayName = outerType.displayName;\n\n if (displayName) {\n return displayName;\n }\n\n var functionName = innerType.displayName || innerType.name || '';\n return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return 'Profiler';\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n var context = type;\n return getContextName(context) + '.Consumer';\n\n case REACT_PROVIDER_TYPE:\n var provider = type;\n return getContextName(provider._context) + '.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n var outerName = type.displayName || null;\n\n if (outerName !== null) {\n return outerName;\n }\n\n return getComponentNameFromType(type.type) || 'Memo';\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n return getComponentNameFromType(init(payload));\n } catch (x) {\n return null;\n }\n }\n\n // eslint-disable-next-line no-fallthrough\n }\n }\n\n return null;\n}\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n {\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n prevLog = console.log;\n prevInfo = console.info;\n prevWarn = console.warn;\n prevError = console.error;\n prevGroup = console.group;\n prevGroupCollapsed = console.groupCollapsed;\n prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n var props = {\n configurable: true,\n enumerable: true,\n value: disabledLog,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n info: props,\n log: props,\n warn: props,\n error: props,\n group: props,\n groupCollapsed: props,\n groupEnd: props\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n disabledDepth++;\n }\n}\nfunction reenableLogs() {\n {\n disabledDepth--;\n\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n var props = {\n configurable: true,\n enumerable: true,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n log: assign({}, props, {\n value: prevLog\n }),\n info: assign({}, props, {\n value: prevInfo\n }),\n warn: assign({}, props, {\n value: prevWarn\n }),\n error: assign({}, props, {\n value: prevError\n }),\n group: assign({}, props, {\n value: prevGroup\n }),\n groupCollapsed: assign({}, props, {\n value: prevGroupCollapsed\n }),\n groupEnd: assign({}, props, {\n value: prevGroupEnd\n })\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n if (disabledDepth < 0) {\n error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n }\n }\n}\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n {\n if (prefix === undefined) {\n // Extract the VM specific prefix used by each line.\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = match && match[1] || '';\n }\n } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n return '\\n' + prefix + name;\n }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n // If something asked for a stack inside a fake render, it should get ignored.\n if ( !fn || reentry) {\n return '';\n }\n\n {\n var frame = componentFrameCache.get(fn);\n\n if (frame !== undefined) {\n return frame;\n }\n }\n\n var control;\n reentry = true;\n var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n Error.prepareStackTrace = undefined;\n var previousDispatcher;\n\n {\n previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function\n // for warnings.\n\n ReactCurrentDispatcher.current = null;\n disableLogs();\n }\n\n try {\n // This should throw.\n if (construct) {\n // Something should be setting the props in the constructor.\n var Fake = function () {\n throw Error();\n }; // $FlowFixMe\n\n\n Object.defineProperty(Fake.prototype, 'props', {\n set: function () {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n }\n });\n\n if (typeof Reflect === 'object' && Reflect.construct) {\n // We construct a different control for this case to include any extra\n // frames added by the construct call.\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n control = x;\n }\n\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x) {\n control = x;\n }\n\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x) {\n control = x;\n }\n\n fn();\n }\n } catch (sample) {\n // This is inlined manually because closure doesn't do it for us.\n if (sample && control && typeof sample.stack === 'string') {\n // This extracts the first frame from the sample that isn't also in the control.\n // Skipping one frame that we assume is the frame that calls the two.\n var sampleLines = sample.stack.split('\\n');\n var controlLines = control.stack.split('\\n');\n var s = sampleLines.length - 1;\n var c = controlLines.length - 1;\n\n while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n // We expect at least one stack frame to be shared.\n // Typically this will be the root most one. However, stack frames may be\n // cut off due to maximum stack limits. In this case, one maybe cut off\n // earlier than the other. We assume that the sample is longer or the same\n // and there for cut off earlier. So we should find the root most frame in\n // the sample somewhere in the control.\n c--;\n }\n\n for (; s >= 1 && c >= 0; s--, c--) {\n // Next we find the first one that isn't the same which should be the\n // frame that called our sample function and the control.\n if (sampleLines[s] !== controlLines[c]) {\n // In V8, the first line is describing the message but other VMs don't.\n // If we're about to return the first line, and the control is also on the same\n // line, that's a pretty good indicator that our sample threw at same line as\n // the control. I.e. before we entered the sample frame. So we ignore this result.\n // This can happen if you passed a class to function component, or non-function.\n if (s !== 1 || c !== 1) {\n do {\n s--;\n c--; // We may still have similar intermediate frames from the construct call.\n // The next one that isn't the same should be our match though.\n\n if (c < 0 || sampleLines[s] !== controlLines[c]) {\n // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"\"\n // but we have a user-provided \"displayName\"\n // splice it in to make the stack more readable.\n\n\n if (fn.displayName && _frame.includes('')) {\n _frame = _frame.replace('', fn.displayName);\n }\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, _frame);\n }\n } // Return the line we found.\n\n\n return _frame;\n }\n } while (s >= 1 && c >= 0);\n }\n\n break;\n }\n }\n }\n } finally {\n reentry = false;\n\n {\n ReactCurrentDispatcher.current = previousDispatcher;\n reenableLogs();\n }\n\n Error.prepareStackTrace = previousPrepareStackTrace;\n } // Fallback to just using the name if we couldn't make it throw.\n\n\n var name = fn ? fn.displayName || fn.name : '';\n var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, syntheticFrame);\n }\n }\n\n return syntheticFrame;\n}\n\nfunction describeClassComponentFrame(ctor, source, ownerFn) {\n {\n return describeNativeComponentFrame(ctor, true);\n }\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n {\n return describeNativeComponentFrame(fn, false);\n }\n}\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n if (type == null) {\n return '';\n }\n\n if (typeof type === 'function') {\n {\n return describeNativeComponentFrame(type, shouldConstruct(type));\n }\n }\n\n if (typeof type === 'string') {\n return describeBuiltInComponentFrame(type);\n }\n\n switch (type) {\n case REACT_SUSPENSE_TYPE:\n return describeBuiltInComponentFrame('Suspense');\n\n case REACT_SUSPENSE_LIST_TYPE:\n return describeBuiltInComponentFrame('SuspenseList');\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n return describeFunctionComponentFrame(type.render);\n\n case REACT_MEMO_TYPE:\n // Memo may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n // Lazy may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n } catch (x) {}\n }\n }\n }\n\n return '';\n}\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame.setExtraStackFrame(null);\n }\n }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n {\n // $FlowFixMe This is okay but Flow doesn't know it.\n var has = Function.call.bind(hasOwnProperty);\n\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n // eslint-disable-next-line react-internal/prod-error-codes\n var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');\n err.name = 'Invariant Violation';\n throw err;\n }\n\n error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n } catch (ex) {\n error$1 = ex;\n }\n\n if (error$1 && !(error$1 instanceof Error)) {\n setCurrentlyValidatingElement(element);\n\n error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);\n\n setCurrentlyValidatingElement(null);\n }\n\n if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error$1.message] = true;\n setCurrentlyValidatingElement(element);\n\n error('Failed %s type: %s', location, error$1.message);\n\n setCurrentlyValidatingElement(null);\n }\n }\n }\n }\n}\n\nvar warnedAboutMissingGetChildContext;\n\n{\n warnedAboutMissingGetChildContext = {};\n}\n\nvar emptyContextObject = {};\n\n{\n Object.freeze(emptyContextObject);\n}\n\nfunction getMaskedContext(type, unmaskedContext) {\n {\n var contextTypes = type.contextTypes;\n\n if (!contextTypes) {\n return emptyContextObject;\n }\n\n var context = {};\n\n for (var key in contextTypes) {\n context[key] = unmaskedContext[key];\n }\n\n {\n var name = getComponentNameFromType(type) || 'Unknown';\n checkPropTypes(contextTypes, context, 'context', name);\n }\n\n return context;\n }\n}\nfunction processChildContext(instance, type, parentContext, childContextTypes) {\n {\n // TODO (bvaughn) Replace this behavior with an invariant() in the future.\n // It has only been added in Fiber to match the (unintentional) behavior in Stack.\n if (typeof instance.getChildContext !== 'function') {\n {\n var componentName = getComponentNameFromType(type) || 'Unknown';\n\n if (!warnedAboutMissingGetChildContext[componentName]) {\n warnedAboutMissingGetChildContext[componentName] = true;\n\n error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);\n }\n }\n\n return parentContext;\n }\n\n var childContext = instance.getChildContext();\n\n for (var contextKey in childContext) {\n if (!(contextKey in childContextTypes)) {\n throw new Error((getComponentNameFromType(type) || 'Unknown') + \".getChildContext(): key \\\"\" + contextKey + \"\\\" is not defined in childContextTypes.\");\n }\n }\n\n {\n var name = getComponentNameFromType(type) || 'Unknown';\n checkPropTypes(childContextTypes, childContext, 'child context', name);\n }\n\n return assign({}, parentContext, childContext);\n }\n}\n\nvar rendererSigil;\n\n{\n // Use this to detect multiple renderers using the same context\n rendererSigil = {};\n} // Used to store the parent path of all context overrides in a shared linked list.\n// Forming a reverse tree.\n\n\nvar rootContextSnapshot = null; // We assume that this runtime owns the \"current\" field on all ReactContext instances.\n// This global (actually thread local) state represents what state all those \"current\",\n// fields are currently in.\n\nvar currentActiveSnapshot = null;\n\nfunction popNode(prev) {\n {\n prev.context._currentValue = prev.parentValue;\n }\n}\n\nfunction pushNode(next) {\n {\n next.context._currentValue = next.value;\n }\n}\n\nfunction popToNearestCommonAncestor(prev, next) {\n if (prev === next) ; else {\n popNode(prev);\n var parentPrev = prev.parent;\n var parentNext = next.parent;\n\n if (parentPrev === null) {\n if (parentNext !== null) {\n throw new Error('The stacks must reach the root at the same time. This is a bug in React.');\n }\n } else {\n if (parentNext === null) {\n throw new Error('The stacks must reach the root at the same time. This is a bug in React.');\n }\n\n popToNearestCommonAncestor(parentPrev, parentNext);\n } // On the way back, we push the new ones that weren't common.\n\n\n pushNode(next);\n }\n}\n\nfunction popAllPrevious(prev) {\n popNode(prev);\n var parentPrev = prev.parent;\n\n if (parentPrev !== null) {\n popAllPrevious(parentPrev);\n }\n}\n\nfunction pushAllNext(next) {\n var parentNext = next.parent;\n\n if (parentNext !== null) {\n pushAllNext(parentNext);\n }\n\n pushNode(next);\n}\n\nfunction popPreviousToCommonLevel(prev, next) {\n popNode(prev);\n var parentPrev = prev.parent;\n\n if (parentPrev === null) {\n throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');\n }\n\n if (parentPrev.depth === next.depth) {\n // We found the same level. Now we just need to find a shared ancestor.\n popToNearestCommonAncestor(parentPrev, next);\n } else {\n // We must still be deeper.\n popPreviousToCommonLevel(parentPrev, next);\n }\n}\n\nfunction popNextToCommonLevel(prev, next) {\n var parentNext = next.parent;\n\n if (parentNext === null) {\n throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.');\n }\n\n if (prev.depth === parentNext.depth) {\n // We found the same level. Now we just need to find a shared ancestor.\n popToNearestCommonAncestor(prev, parentNext);\n } else {\n // We must still be deeper.\n popNextToCommonLevel(prev, parentNext);\n }\n\n pushNode(next);\n} // Perform context switching to the new snapshot.\n// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by\n// updating all the context's current values. That way reads, always just read the current value.\n// At the cost of updating contexts even if they're never read by this subtree.\n\n\nfunction switchContext(newSnapshot) {\n // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack.\n // We also need to update any new contexts that are now on the stack with the deepest value.\n // The easiest way to update new contexts is to just reapply them in reverse order from the\n // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack\n // for that. Therefore this algorithm is recursive.\n // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go.\n // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go.\n // 3) Then we reapply new contexts on the way back up the stack.\n var prev = currentActiveSnapshot;\n var next = newSnapshot;\n\n if (prev !== next) {\n if (prev === null) {\n // $FlowFixMe: This has to be non-null since it's not equal to prev.\n pushAllNext(next);\n } else if (next === null) {\n popAllPrevious(prev);\n } else if (prev.depth === next.depth) {\n popToNearestCommonAncestor(prev, next);\n } else if (prev.depth > next.depth) {\n popPreviousToCommonLevel(prev, next);\n } else {\n popNextToCommonLevel(prev, next);\n }\n\n currentActiveSnapshot = next;\n }\n}\nfunction pushProvider(context, nextValue) {\n var prevValue;\n\n {\n prevValue = context._currentValue;\n context._currentValue = nextValue;\n\n {\n if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {\n error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');\n }\n\n context._currentRenderer = rendererSigil;\n }\n }\n\n var prevNode = currentActiveSnapshot;\n var newNode = {\n parent: prevNode,\n depth: prevNode === null ? 0 : prevNode.depth + 1,\n context: context,\n parentValue: prevValue,\n value: nextValue\n };\n currentActiveSnapshot = newNode;\n return newNode;\n}\nfunction popProvider(context) {\n var prevSnapshot = currentActiveSnapshot;\n\n if (prevSnapshot === null) {\n throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.');\n }\n\n {\n if (prevSnapshot.context !== context) {\n error('The parent context is not the expected context. This is probably a bug in React.');\n }\n }\n\n {\n var value = prevSnapshot.parentValue;\n\n if (value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) {\n prevSnapshot.context._currentValue = prevSnapshot.context._defaultValue;\n } else {\n prevSnapshot.context._currentValue = value;\n }\n\n {\n if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {\n error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');\n }\n\n context._currentRenderer = rendererSigil;\n }\n }\n\n return currentActiveSnapshot = prevSnapshot.parent;\n}\nfunction getActiveContext() {\n return currentActiveSnapshot;\n}\nfunction readContext(context) {\n var value = context._currentValue ;\n return value;\n}\n\n/**\n * `ReactInstanceMap` maintains a mapping from a public facing stateful\n * instance (key) and the internal representation (value). This allows public\n * methods to accept the user facing instance as an argument and map them back\n * to internal methods.\n *\n * Note that this module is currently shared and assumed to be stateless.\n * If this becomes an actual Map, that will break.\n */\nfunction get(key) {\n return key._reactInternals;\n}\nfunction set(key, value) {\n key._reactInternals = value;\n}\n\nvar didWarnAboutNoopUpdateForComponent = {};\nvar didWarnAboutDeprecatedWillMount = {};\nvar didWarnAboutUninitializedState;\nvar didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;\nvar didWarnAboutLegacyLifecyclesAndDerivedState;\nvar didWarnAboutUndefinedDerivedState;\nvar warnOnUndefinedDerivedState;\nvar warnOnInvalidCallback;\nvar didWarnAboutDirectlyAssigningPropsToState;\nvar didWarnAboutContextTypeAndContextTypes;\nvar didWarnAboutInvalidateContextType;\n\n{\n didWarnAboutUninitializedState = new Set();\n didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();\n didWarnAboutLegacyLifecyclesAndDerivedState = new Set();\n didWarnAboutDirectlyAssigningPropsToState = new Set();\n didWarnAboutUndefinedDerivedState = new Set();\n didWarnAboutContextTypeAndContextTypes = new Set();\n didWarnAboutInvalidateContextType = new Set();\n var didWarnOnInvalidCallback = new Set();\n\n warnOnInvalidCallback = function (callback, callerName) {\n if (callback === null || typeof callback === 'function') {\n return;\n }\n\n var key = callerName + '_' + callback;\n\n if (!didWarnOnInvalidCallback.has(key)) {\n didWarnOnInvalidCallback.add(key);\n\n error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);\n }\n };\n\n warnOnUndefinedDerivedState = function (type, partialState) {\n if (partialState === undefined) {\n var componentName = getComponentNameFromType(type) || 'Component';\n\n if (!didWarnAboutUndefinedDerivedState.has(componentName)) {\n didWarnAboutUndefinedDerivedState.add(componentName);\n\n error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);\n }\n }\n };\n}\n\nfunction warnNoop(publicInstance, callerName) {\n {\n var _constructor = publicInstance.constructor;\n var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass';\n var warningKey = componentName + '.' + callerName;\n\n if (didWarnAboutNoopUpdateForComponent[warningKey]) {\n return;\n }\n\n error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\\n\\nPlease check the code for the %s component.', callerName, callerName, componentName);\n\n didWarnAboutNoopUpdateForComponent[warningKey] = true;\n }\n}\n\nvar classComponentUpdater = {\n isMounted: function (inst) {\n return false;\n },\n enqueueSetState: function (inst, payload, callback) {\n var internals = get(inst);\n\n if (internals.queue === null) {\n warnNoop(inst, 'setState');\n } else {\n internals.queue.push(payload);\n\n {\n if (callback !== undefined && callback !== null) {\n warnOnInvalidCallback(callback, 'setState');\n }\n }\n }\n },\n enqueueReplaceState: function (inst, payload, callback) {\n var internals = get(inst);\n internals.replace = true;\n internals.queue = [payload];\n\n {\n if (callback !== undefined && callback !== null) {\n warnOnInvalidCallback(callback, 'setState');\n }\n }\n },\n enqueueForceUpdate: function (inst, callback) {\n var internals = get(inst);\n\n if (internals.queue === null) {\n warnNoop(inst, 'forceUpdate');\n } else {\n {\n if (callback !== undefined && callback !== null) {\n warnOnInvalidCallback(callback, 'setState');\n }\n }\n }\n }\n};\n\nfunction applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) {\n var partialState = getDerivedStateFromProps(nextProps, prevState);\n\n {\n warnOnUndefinedDerivedState(ctor, partialState);\n } // Merge the partial state and the previous state.\n\n\n var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState);\n return newState;\n}\n\nfunction constructClassInstance(ctor, props, maskedLegacyContext) {\n var context = emptyContextObject;\n var contextType = ctor.contextType;\n\n {\n if ('contextType' in ctor) {\n var isValid = // Allow null for conditional declaration\n contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a \n\n if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {\n didWarnAboutInvalidateContextType.add(ctor);\n var addendum = '';\n\n if (contextType === undefined) {\n addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';\n } else if (typeof contextType !== 'object') {\n addendum = ' However, it is set to a ' + typeof contextType + '.';\n } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {\n addendum = ' Did you accidentally pass the Context.Provider instead?';\n } else if (contextType._context !== undefined) {\n // \n addendum = ' Did you accidentally pass the Context.Consumer instead?';\n } else {\n addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';\n }\n\n error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum);\n }\n }\n }\n\n if (typeof contextType === 'object' && contextType !== null) {\n context = readContext(contextType);\n } else {\n context = maskedLegacyContext;\n }\n\n var instance = new ctor(props, context);\n\n {\n if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) {\n var componentName = getComponentNameFromType(ctor) || 'Component';\n\n if (!didWarnAboutUninitializedState.has(componentName)) {\n didWarnAboutUninitializedState.add(componentName);\n\n error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);\n }\n } // If new component APIs are defined, \"unsafe\" lifecycles won't be called.\n // Warn about these lifecycles if they are present.\n // Don't warn about react-lifecycles-compat polyfilled methods though.\n\n\n if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {\n var foundWillMountName = null;\n var foundWillReceivePropsName = null;\n var foundWillUpdateName = null;\n\n if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {\n foundWillMountName = 'componentWillMount';\n } else if (typeof instance.UNSAFE_componentWillMount === 'function') {\n foundWillMountName = 'UNSAFE_componentWillMount';\n }\n\n if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {\n foundWillReceivePropsName = 'componentWillReceiveProps';\n } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';\n }\n\n if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {\n foundWillUpdateName = 'componentWillUpdate';\n } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {\n foundWillUpdateName = 'UNSAFE_componentWillUpdate';\n }\n\n if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {\n var _componentName = getComponentNameFromType(ctor) || 'Component';\n\n var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';\n\n if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {\n didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);\n\n error('Unsafe legacy lifecycles will not be called for components using new component APIs.\\n\\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\\n\\n' + 'The above lifecycles should be removed. Learn more about this warning here:\\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? \"\\n \" + foundWillMountName : '', foundWillReceivePropsName !== null ? \"\\n \" + foundWillReceivePropsName : '', foundWillUpdateName !== null ? \"\\n \" + foundWillUpdateName : '');\n }\n }\n }\n }\n\n return instance;\n}\n\nfunction checkClassInstance(instance, ctor, newProps) {\n {\n var name = getComponentNameFromType(ctor) || 'Component';\n var renderPresent = instance.render;\n\n if (!renderPresent) {\n if (ctor.prototype && typeof ctor.prototype.render === 'function') {\n error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);\n } else {\n error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);\n }\n }\n\n if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {\n error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);\n }\n\n if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);\n }\n\n if (instance.propTypes) {\n error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);\n }\n\n if (instance.contextType) {\n error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);\n }\n\n {\n if (instance.contextTypes) {\n error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);\n }\n\n if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {\n didWarnAboutContextTypeAndContextTypes.add(ctor);\n\n error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);\n }\n }\n\n if (typeof instance.componentShouldUpdate === 'function') {\n error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);\n }\n\n if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {\n error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component');\n }\n\n if (typeof instance.componentDidUnmount === 'function') {\n error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);\n }\n\n if (typeof instance.componentDidReceiveProps === 'function') {\n error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);\n }\n\n if (typeof instance.componentWillRecieveProps === 'function') {\n error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);\n }\n\n if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {\n error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);\n }\n\n var hasMutatedProps = instance.props !== newProps;\n\n if (instance.props !== undefined && hasMutatedProps) {\n error('%s(...): When calling super() in `%s`, make sure to pass ' + \"up the same props that your component's constructor was passed.\", name, name);\n }\n\n if (instance.defaultProps) {\n error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {\n didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);\n\n error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor));\n }\n\n if (typeof instance.getDerivedStateFromProps === 'function') {\n error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);\n }\n\n if (typeof instance.getDerivedStateFromError === 'function') {\n error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);\n }\n\n if (typeof ctor.getSnapshotBeforeUpdate === 'function') {\n error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);\n }\n\n var _state = instance.state;\n\n if (_state && (typeof _state !== 'object' || isArray(_state))) {\n error('%s.state: must be set to an object or null', name);\n }\n\n if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {\n error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);\n }\n }\n}\n\nfunction callComponentWillMount(type, instance) {\n var oldState = instance.state;\n\n if (typeof instance.componentWillMount === 'function') {\n {\n if ( instance.componentWillMount.__suppressDeprecationWarning !== true) {\n var componentName = getComponentNameFromType(type) || 'Unknown';\n\n if (!didWarnAboutDeprecatedWillMount[componentName]) {\n warn( // keep this warning in sync with ReactStrictModeWarning.js\n 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\\n\\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\\n' + '\\nPlease update the following components: %s', componentName);\n\n didWarnAboutDeprecatedWillMount[componentName] = true;\n }\n }\n }\n\n instance.componentWillMount();\n }\n\n if (typeof instance.UNSAFE_componentWillMount === 'function') {\n instance.UNSAFE_componentWillMount();\n }\n\n if (oldState !== instance.state) {\n {\n error('%s.componentWillMount(): Assigning directly to this.state is ' + \"deprecated (except inside a component's \" + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component');\n }\n\n classComponentUpdater.enqueueReplaceState(instance, instance.state, null);\n }\n}\n\nfunction processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) {\n if (internalInstance.queue !== null && internalInstance.queue.length > 0) {\n var oldQueue = internalInstance.queue;\n var oldReplace = internalInstance.replace;\n internalInstance.queue = null;\n internalInstance.replace = false;\n\n if (oldReplace && oldQueue.length === 1) {\n inst.state = oldQueue[0];\n } else {\n var nextState = oldReplace ? oldQueue[0] : inst.state;\n var dontMutate = true;\n\n for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {\n var partial = oldQueue[i];\n var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial;\n\n if (partialState != null) {\n if (dontMutate) {\n dontMutate = false;\n nextState = assign({}, nextState, partialState);\n } else {\n assign(nextState, partialState);\n }\n }\n }\n\n inst.state = nextState;\n }\n } else {\n internalInstance.queue = null;\n }\n} // Invokes the mount life-cycles on a previously never rendered instance.\n\n\nfunction mountClassInstance(instance, ctor, newProps, maskedLegacyContext) {\n {\n checkClassInstance(instance, ctor, newProps);\n }\n\n var initialState = instance.state !== undefined ? instance.state : null;\n instance.updater = classComponentUpdater;\n instance.props = newProps;\n instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway.\n // The internal instance will be used to manage updates that happen during this mount.\n\n var internalInstance = {\n queue: [],\n replace: false\n };\n set(instance, internalInstance);\n var contextType = ctor.contextType;\n\n if (typeof contextType === 'object' && contextType !== null) {\n instance.context = readContext(contextType);\n } else {\n instance.context = maskedLegacyContext;\n }\n\n {\n if (instance.state === newProps) {\n var componentName = getComponentNameFromType(ctor) || 'Component';\n\n if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {\n didWarnAboutDirectlyAssigningPropsToState.add(componentName);\n\n error('%s: It is not recommended to assign props directly to state ' + \"because updates to props won't be reflected in state. \" + 'In most cases, it is better to use props directly.', componentName);\n }\n }\n }\n\n var getDerivedStateFromProps = ctor.getDerivedStateFromProps;\n\n if (typeof getDerivedStateFromProps === 'function') {\n instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps);\n } // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n\n\n if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {\n callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's\n // process them now.\n\n processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext);\n }\n}\n\n// Ids are base 32 strings whose binary representation corresponds to the\n// position of a node in a tree.\n// Every time the tree forks into multiple children, we add additional bits to\n// the left of the sequence that represent the position of the child within the\n// current level of children.\n//\n// 00101 00010001011010101\n// \u2570\u2500\u252C\u2500\u256F \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F\n// Fork 5 of 20 Parent id\n//\n// The leading 0s are important. In the above example, you only need 3 bits to\n// represent slot 5. However, you need 5 bits to represent all the forks at\n// the current level, so we must account for the empty bits at the end.\n//\n// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise,\n// the zeroth id at a level would be indistinguishable from its parent.\n//\n// If a node has only one child, and does not materialize an id (i.e. does not\n// contain a useId hook), then we don't need to allocate any space in the\n// sequence. It's treated as a transparent indirection. For example, these two\n// trees produce the same ids:\n//\n// <> <>\n// \n// \n// \n// \n// \n//\n// However, we cannot skip any node that materializes an id. Otherwise, a parent\n// id that does not fork would be indistinguishable from its child id. For\n// example, this tree does not fork, but the parent and child must have\n// different ids.\n//\n// \n// \n// \n//\n// To handle this scenario, every time we materialize an id, we allocate a\n// new level with a single slot. You can think of this as a fork with only one\n// prong, or an array of children with length 1.\n//\n// It's possible for the size of the sequence to exceed 32 bits, the max\n// size for bitwise operations. When this happens, we make more room by\n// converting the right part of the id to a string and storing it in an overflow\n// variable. We use a base 32 string representation, because 32 is the largest\n// power of 2 that is supported by toString(). We want the base to be large so\n// that the resulting ids are compact, and we want the base to be a power of 2\n// because every log2(base) bits corresponds to a single character, i.e. every\n// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without\n// affecting the final result.\nvar emptyTreeContext = {\n id: 1,\n overflow: ''\n};\nfunction getTreeId(context) {\n var overflow = context.overflow;\n var idWithLeadingBit = context.id;\n var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);\n return id.toString(32) + overflow;\n}\nfunction pushTreeContext(baseContext, totalChildren, index) {\n var baseIdWithLeadingBit = baseContext.id;\n var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part\n // of the id; we use it to account for leading 0s.\n\n var baseLength = getBitLength(baseIdWithLeadingBit) - 1;\n var baseId = baseIdWithLeadingBit & ~(1 << baseLength);\n var slot = index + 1;\n var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into\n // consideration the leading 1 we use to mark the end of the sequence.\n\n if (length > 30) {\n // We overflowed the bitwise-safe range. Fall back to slower algorithm.\n // This branch assumes the length of the base id is greater than 5; it won't\n // work for smaller ids, because you need 5 bits per character.\n //\n // We encode the id in multiple steps: first the base id, then the\n // remaining digits.\n //\n // Each 5 bit sequence corresponds to a single base 32 character. So for\n // example, if the current id is 23 bits long, we can convert 20 of those\n // bits into a string of 4 characters, with 3 bits left over.\n //\n // First calculate how many bits in the base id represent a complete\n // sequence of characters.\n var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits.\n\n var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string.\n\n var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id.\n\n var restOfBaseId = baseId >> numberOfOverflowBits;\n var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because\n // we made more room, this time it won't overflow.\n\n var restOfLength = getBitLength(totalChildren) + restOfBaseLength;\n var restOfNewBits = slot << restOfBaseLength;\n var id = restOfNewBits | restOfBaseId;\n var overflow = newOverflow + baseOverflow;\n return {\n id: 1 << restOfLength | id,\n overflow: overflow\n };\n } else {\n // Normal path\n var newBits = slot << baseLength;\n\n var _id = newBits | baseId;\n\n var _overflow = baseOverflow;\n return {\n id: 1 << length | _id,\n overflow: _overflow\n };\n }\n}\n\nfunction getBitLength(number) {\n return 32 - clz32(number);\n}\n\nfunction getLeadingBit(id) {\n return 1 << getBitLength(id) - 1;\n} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback.\n\n\nvar clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros.\n// Based on:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32\n\nvar log = Math.log;\nvar LN2 = Math.LN2;\n\nfunction clz32Fallback(x) {\n var asUint = x >>> 0;\n\n if (asUint === 0) {\n return 32;\n }\n\n return 31 - (log(asUint) / LN2 | 0) | 0;\n}\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar currentlyRenderingComponent = null;\nvar currentlyRenderingTask = null;\nvar firstWorkInProgressHook = null;\nvar workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook\n\nvar isReRender = false; // Whether an update was scheduled during the currently executing render pass.\n\nvar didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component\n\nvar localIdCounter = 0; // Lazily created map of render-phase updates\n\nvar renderPhaseUpdates = null; // Counter to prevent infinite loops.\n\nvar numberOfReRenders = 0;\nvar RE_RENDER_LIMIT = 25;\nvar isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook\n\nvar currentHookNameInDev;\n\nfunction resolveCurrentlyRenderingComponent() {\n if (currentlyRenderingComponent === null) {\n throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\\n' + '2. You might be breaking the Rules of Hooks\\n' + '3. You might have more than one copy of React in the same app\\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');\n }\n\n {\n if (isInHookUserCodeInDev) {\n error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks');\n }\n }\n\n return currentlyRenderingComponent;\n}\n\nfunction areHookInputsEqual(nextDeps, prevDeps) {\n if (prevDeps === null) {\n {\n error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);\n }\n\n return false;\n }\n\n {\n // Don't bother comparing lengths in prod because these arrays should be\n // passed inline.\n if (nextDeps.length !== prevDeps.length) {\n error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\\n\\n' + 'Previous: %s\\n' + 'Incoming: %s', currentHookNameInDev, \"[\" + nextDeps.join(', ') + \"]\", \"[\" + prevDeps.join(', ') + \"]\");\n }\n }\n\n for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {\n if (objectIs(nextDeps[i], prevDeps[i])) {\n continue;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction createHook() {\n if (numberOfReRenders > 0) {\n throw new Error('Rendered more hooks than during the previous render');\n }\n\n return {\n memoizedState: null,\n queue: null,\n next: null\n };\n}\n\nfunction createWorkInProgressHook() {\n if (workInProgressHook === null) {\n // This is the first hook in the list\n if (firstWorkInProgressHook === null) {\n isReRender = false;\n firstWorkInProgressHook = workInProgressHook = createHook();\n } else {\n // There's already a work-in-progress. Reuse it.\n isReRender = true;\n workInProgressHook = firstWorkInProgressHook;\n }\n } else {\n if (workInProgressHook.next === null) {\n isReRender = false; // Append to the end of the list\n\n workInProgressHook = workInProgressHook.next = createHook();\n } else {\n // There's already a work-in-progress. Reuse it.\n isReRender = true;\n workInProgressHook = workInProgressHook.next;\n }\n }\n\n return workInProgressHook;\n}\n\nfunction prepareToUseHooks(task, componentIdentity) {\n currentlyRenderingComponent = componentIdentity;\n currentlyRenderingTask = task;\n\n {\n isInHookUserCodeInDev = false;\n } // The following should have already been reset\n // didScheduleRenderPhaseUpdate = false;\n // localIdCounter = 0;\n // firstWorkInProgressHook = null;\n // numberOfReRenders = 0;\n // renderPhaseUpdates = null;\n // workInProgressHook = null;\n\n\n localIdCounter = 0;\n}\nfunction finishHooks(Component, props, children, refOrContext) {\n // This must be called after every function component to prevent hooks from\n // being used in classes.\n while (didScheduleRenderPhaseUpdate) {\n // Updates were scheduled during the render phase. They are stored in\n // the `renderPhaseUpdates` map. Call the component again, reusing the\n // work-in-progress hooks and applying the additional updates on top. Keep\n // restarting until no more updates are scheduled.\n didScheduleRenderPhaseUpdate = false;\n localIdCounter = 0;\n numberOfReRenders += 1; // Start over from the beginning of the list\n\n workInProgressHook = null;\n children = Component(props, refOrContext);\n }\n\n resetHooksState();\n return children;\n}\nfunction checkDidRenderIdHook() {\n // This should be called immediately after every finishHooks call.\n // Conceptually, it's part of the return value of finishHooks; it's only a\n // separate function to avoid using an array tuple.\n var didRenderIdHook = localIdCounter !== 0;\n return didRenderIdHook;\n} // Reset the internal hooks state if an error occurs while rendering a component\n\nfunction resetHooksState() {\n {\n isInHookUserCodeInDev = false;\n }\n\n currentlyRenderingComponent = null;\n currentlyRenderingTask = null;\n didScheduleRenderPhaseUpdate = false;\n firstWorkInProgressHook = null;\n numberOfReRenders = 0;\n renderPhaseUpdates = null;\n workInProgressHook = null;\n}\n\nfunction readContext$1(context) {\n {\n if (isInHookUserCodeInDev) {\n error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');\n }\n }\n\n return readContext(context);\n}\n\nfunction useContext(context) {\n {\n currentHookNameInDev = 'useContext';\n }\n\n resolveCurrentlyRenderingComponent();\n return readContext(context);\n}\n\nfunction basicStateReducer(state, action) {\n // $FlowFixMe: Flow doesn't like mixed types\n return typeof action === 'function' ? action(state) : action;\n}\n\nfunction useState(initialState) {\n {\n currentHookNameInDev = 'useState';\n }\n\n return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers\n initialState);\n}\nfunction useReducer(reducer, initialArg, init) {\n {\n if (reducer !== basicStateReducer) {\n currentHookNameInDev = 'useReducer';\n }\n }\n\n currentlyRenderingComponent = resolveCurrentlyRenderingComponent();\n workInProgressHook = createWorkInProgressHook();\n\n if (isReRender) {\n // This is a re-render. Apply the new render phase updates to the previous\n // current hook.\n var queue = workInProgressHook.queue;\n var dispatch = queue.dispatch;\n\n if (renderPhaseUpdates !== null) {\n // Render phase updates are stored in a map of queue -> linked list\n var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);\n\n if (firstRenderPhaseUpdate !== undefined) {\n renderPhaseUpdates.delete(queue);\n var newState = workInProgressHook.memoizedState;\n var update = firstRenderPhaseUpdate;\n\n do {\n // Process this render phase update. We don't have to check the\n // priority because it will always be the same as the current\n // render's.\n var action = update.action;\n\n {\n isInHookUserCodeInDev = true;\n }\n\n newState = reducer(newState, action);\n\n {\n isInHookUserCodeInDev = false;\n }\n\n update = update.next;\n } while (update !== null);\n\n workInProgressHook.memoizedState = newState;\n return [newState, dispatch];\n }\n }\n\n return [workInProgressHook.memoizedState, dispatch];\n } else {\n {\n isInHookUserCodeInDev = true;\n }\n\n var initialState;\n\n if (reducer === basicStateReducer) {\n // Special case for `useState`.\n initialState = typeof initialArg === 'function' ? initialArg() : initialArg;\n } else {\n initialState = init !== undefined ? init(initialArg) : initialArg;\n }\n\n {\n isInHookUserCodeInDev = false;\n }\n\n workInProgressHook.memoizedState = initialState;\n\n var _queue = workInProgressHook.queue = {\n last: null,\n dispatch: null\n };\n\n var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue);\n\n return [workInProgressHook.memoizedState, _dispatch];\n }\n}\n\nfunction useMemo(nextCreate, deps) {\n currentlyRenderingComponent = resolveCurrentlyRenderingComponent();\n workInProgressHook = createWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n\n if (workInProgressHook !== null) {\n var prevState = workInProgressHook.memoizedState;\n\n if (prevState !== null) {\n if (nextDeps !== null) {\n var prevDeps = prevState[1];\n\n if (areHookInputsEqual(nextDeps, prevDeps)) {\n return prevState[0];\n }\n }\n }\n }\n\n {\n isInHookUserCodeInDev = true;\n }\n\n var nextValue = nextCreate();\n\n {\n isInHookUserCodeInDev = false;\n }\n\n workInProgressHook.memoizedState = [nextValue, nextDeps];\n return nextValue;\n}\n\nfunction useRef(initialValue) {\n currentlyRenderingComponent = resolveCurrentlyRenderingComponent();\n workInProgressHook = createWorkInProgressHook();\n var previousRef = workInProgressHook.memoizedState;\n\n if (previousRef === null) {\n var ref = {\n current: initialValue\n };\n\n {\n Object.seal(ref);\n }\n\n workInProgressHook.memoizedState = ref;\n return ref;\n } else {\n return previousRef;\n }\n}\n\nfunction useLayoutEffect(create, inputs) {\n {\n currentHookNameInDev = 'useLayoutEffect';\n\n error('useLayoutEffect does nothing on the server, because its effect cannot ' + \"be encoded into the server renderer's output format. This will lead \" + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.');\n }\n}\n\nfunction dispatchAction(componentIdentity, queue, action) {\n if (numberOfReRenders >= RE_RENDER_LIMIT) {\n throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.');\n }\n\n if (componentIdentity === currentlyRenderingComponent) {\n // This is a render phase update. Stash it in a lazily-created map of\n // queue -> linked list of updates. After this render pass, we'll restart\n // and apply the stashed updates on top of the work-in-progress hook.\n didScheduleRenderPhaseUpdate = true;\n var update = {\n action: action,\n next: null\n };\n\n if (renderPhaseUpdates === null) {\n renderPhaseUpdates = new Map();\n }\n\n var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);\n\n if (firstRenderPhaseUpdate === undefined) {\n renderPhaseUpdates.set(queue, update);\n } else {\n // Append the update to the end of the list.\n var lastRenderPhaseUpdate = firstRenderPhaseUpdate;\n\n while (lastRenderPhaseUpdate.next !== null) {\n lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;\n }\n\n lastRenderPhaseUpdate.next = update;\n }\n }\n}\n\nfunction useCallback(callback, deps) {\n return useMemo(function () {\n return callback;\n }, deps);\n} // TODO Decide on how to implement this hook for server rendering.\n// If a mutation occurs during render, consider triggering a Suspense boundary\n// and falling back to client rendering.\n\nfunction useMutableSource(source, getSnapshot, subscribe) {\n resolveCurrentlyRenderingComponent();\n return getSnapshot(source._source);\n}\n\nfunction useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {\n if (getServerSnapshot === undefined) {\n throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.');\n }\n\n return getServerSnapshot();\n}\n\nfunction useDeferredValue(value) {\n resolveCurrentlyRenderingComponent();\n return value;\n}\n\nfunction unsupportedStartTransition() {\n throw new Error('startTransition cannot be called during server rendering.');\n}\n\nfunction useTransition() {\n resolveCurrentlyRenderingComponent();\n return [false, unsupportedStartTransition];\n}\n\nfunction useId() {\n var task = currentlyRenderingTask;\n var treeId = getTreeId(task.treeContext);\n var responseState = currentResponseState;\n\n if (responseState === null) {\n throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.');\n }\n\n var localId = localIdCounter++;\n return makeId(responseState, treeId, localId);\n}\n\nfunction noop() {}\n\nvar Dispatcher = {\n readContext: readContext$1,\n useContext: useContext,\n useMemo: useMemo,\n useReducer: useReducer,\n useRef: useRef,\n useState: useState,\n useInsertionEffect: noop,\n useLayoutEffect: useLayoutEffect,\n useCallback: useCallback,\n // useImperativeHandle is not run in the server environment\n useImperativeHandle: noop,\n // Effects are not run in the server environment.\n useEffect: noop,\n // Debugging effect\n useDebugValue: noop,\n useDeferredValue: useDeferredValue,\n useTransition: useTransition,\n useId: useId,\n // Subscriptions are not setup in a server environment.\n useMutableSource: useMutableSource,\n useSyncExternalStore: useSyncExternalStore\n};\n\nvar currentResponseState = null;\nfunction setCurrentResponseState(responseState) {\n currentResponseState = responseState;\n}\n\nfunction getStackByComponentStackNode(componentStack) {\n try {\n var info = '';\n var node = componentStack;\n\n do {\n switch (node.tag) {\n case 0:\n info += describeBuiltInComponentFrame(node.type, null, null);\n break;\n\n case 1:\n info += describeFunctionComponentFrame(node.type, null, null);\n break;\n\n case 2:\n info += describeClassComponentFrame(node.type, null, null);\n break;\n }\n\n node = node.parent;\n } while (node);\n\n return info;\n } catch (x) {\n return '\\nError generating stack: ' + x.message + '\\n' + x.stack;\n }\n}\n\nvar ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\nvar PENDING = 0;\nvar COMPLETED = 1;\nvar FLUSHED = 2;\nvar ABORTED = 3;\nvar ERRORED = 4;\nvar OPEN = 0;\nvar CLOSING = 1;\nvar CLOSED = 2;\n// This is a default heuristic for how to split up the HTML content into progressive\n// loading. Our goal is to be able to display additional new content about every 500ms.\n// Faster than that is unnecessary and should be throttled on the client. It also\n// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower\n// end device but higher end suffer less from the overhead than lower end does from\n// not getting small enough pieces. We error on the side of low end.\n// We base this on low end 3G speeds which is about 500kbits per second. We assume\n// that there can be a reasonable drop off from max bandwidth which leaves you with\n// as little as 80%. We can receive half of that each 500ms - at best. In practice,\n// a little bandwidth is lost to processing and contention - e.g. CSS and images that\n// are downloaded along with the main content. So we estimate about half of that to be\n// the lower end throughput. In other words, we expect that you can at least show\n// about 12.5kb of content per 500ms. Not counting starting latency for the first\n// paint.\n// 500 * 1024 / 8 * .8 * 0.5 / 2\nvar DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800;\n\nfunction defaultErrorHandler(error) {\n console['error'](error); // Don't transform to our wrapper\n\n return null;\n}\n\nfunction noop$1() {}\n\nfunction createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) {\n var pingedTasks = [];\n var abortSet = new Set();\n var request = {\n destination: null,\n responseState: responseState,\n progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize,\n status: OPEN,\n fatalError: null,\n nextSegmentId: 0,\n allPendingTasks: 0,\n pendingRootTasks: 0,\n completedRootSegment: null,\n abortableTasks: abortSet,\n pingedTasks: pingedTasks,\n clientRenderedBoundaries: [],\n completedBoundaries: [],\n partialBoundaries: [],\n onError: onError === undefined ? defaultErrorHandler : onError,\n onAllReady: onAllReady === undefined ? noop$1 : onAllReady,\n onShellReady: onShellReady === undefined ? noop$1 : onShellReady,\n onShellError: onShellError === undefined ? noop$1 : onShellError,\n onFatalError: onFatalError === undefined ? noop$1 : onFatalError\n }; // This segment represents the root fallback.\n\n var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge\n false, false); // There is no parent so conceptually, we're unblocked to flush this segment.\n\n rootSegment.parentFlushed = true;\n var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext);\n pingedTasks.push(rootTask);\n return request;\n}\n\nfunction pingTask(request, task) {\n var pingedTasks = request.pingedTasks;\n pingedTasks.push(task);\n\n if (pingedTasks.length === 1) {\n scheduleWork(function () {\n return performWork(request);\n });\n }\n}\n\nfunction createSuspenseBoundary(request, fallbackAbortableTasks) {\n return {\n id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID,\n rootSegmentID: -1,\n parentFlushed: false,\n pendingTasks: 0,\n forceClientRender: false,\n completedSegments: [],\n byteSize: 0,\n fallbackAbortableTasks: fallbackAbortableTasks,\n errorDigest: null\n };\n}\n\nfunction createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) {\n request.allPendingTasks++;\n\n if (blockedBoundary === null) {\n request.pendingRootTasks++;\n } else {\n blockedBoundary.pendingTasks++;\n }\n\n var task = {\n node: node,\n ping: function () {\n return pingTask(request, task);\n },\n blockedBoundary: blockedBoundary,\n blockedSegment: blockedSegment,\n abortSet: abortSet,\n legacyContext: legacyContext,\n context: context,\n treeContext: treeContext\n };\n\n {\n task.componentStack = null;\n }\n\n abortSet.add(task);\n return task;\n}\n\nfunction createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) {\n return {\n status: PENDING,\n id: -1,\n // lazily assigned later\n index: index,\n parentFlushed: false,\n chunks: [],\n children: [],\n formatContext: formatContext,\n boundary: boundary,\n lastPushedText: lastPushedText,\n textEmbedded: textEmbedded\n };\n} // DEV-only global reference to the currently executing task\n\n\nvar currentTaskInDEV = null;\n\nfunction getCurrentStackInDEV() {\n {\n if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) {\n return '';\n }\n\n return getStackByComponentStackNode(currentTaskInDEV.componentStack);\n }\n}\n\nfunction pushBuiltInComponentStackInDEV(task, type) {\n {\n task.componentStack = {\n tag: 0,\n parent: task.componentStack,\n type: type\n };\n }\n}\n\nfunction pushFunctionComponentStackInDEV(task, type) {\n {\n task.componentStack = {\n tag: 1,\n parent: task.componentStack,\n type: type\n };\n }\n}\n\nfunction pushClassComponentStackInDEV(task, type) {\n {\n task.componentStack = {\n tag: 2,\n parent: task.componentStack,\n type: type\n };\n }\n}\n\nfunction popComponentStackInDEV(task) {\n {\n if (task.componentStack === null) {\n error('Unexpectedly popped too many stack frames. This is a bug in React.');\n } else {\n task.componentStack = task.componentStack.parent;\n }\n }\n} // stash the component stack of an unwinding error until it is processed\n\n\nvar lastBoundaryErrorComponentStackDev = null;\n\nfunction captureBoundaryErrorDetailsDev(boundary, error) {\n {\n var errorMessage;\n\n if (typeof error === 'string') {\n errorMessage = error;\n } else if (error && typeof error.message === 'string') {\n errorMessage = error.message;\n } else {\n // eslint-disable-next-line react-internal/safe-string-coercion\n errorMessage = String(error);\n }\n\n var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV();\n lastBoundaryErrorComponentStackDev = null;\n boundary.errorMessage = errorMessage;\n boundary.errorComponentStack = errorComponentStack;\n }\n}\n\nfunction logRecoverableError(request, error) {\n // If this callback errors, we intentionally let that error bubble up to become a fatal error\n // so that someone fixes the error reporting instead of hiding it.\n var errorDigest = request.onError(error);\n\n if (errorDigest != null && typeof errorDigest !== 'string') {\n // eslint-disable-next-line react-internal/prod-error-codes\n throw new Error(\"onError returned something with a type other than \\\"string\\\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \\\"\" + typeof errorDigest + \"\\\" instead\");\n }\n\n return errorDigest;\n}\n\nfunction fatalError(request, error) {\n // This is called outside error handling code such as if the root errors outside\n // a suspense boundary or if the root suspense boundary's fallback errors.\n // It's also called if React itself or its host configs errors.\n var onShellError = request.onShellError;\n onShellError(error);\n var onFatalError = request.onFatalError;\n onFatalError(error);\n\n if (request.destination !== null) {\n request.status = CLOSED;\n closeWithError(request.destination, error);\n } else {\n request.status = CLOSING;\n request.fatalError = error;\n }\n}\n\nfunction renderSuspenseBoundary(request, task, props) {\n pushBuiltInComponentStackInDEV(task, 'Suspense');\n var parentBoundary = task.blockedBoundary;\n var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for\n // the fallback so that we can later replace that segment with the content.\n // This also lets us split out the main content even if it doesn't suspend,\n // in case it ends up generating a large subtree of content.\n\n var fallback = props.fallback;\n var content = props.children;\n var fallbackAbortSet = new Set();\n var newBoundary = createSuspenseBoundary(request, fallbackAbortSet);\n var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback.\n\n var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them\n false, false);\n parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent\n\n parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately.\n\n var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them\n false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is\n // no parent segment so there's nothing to wait on.\n\n contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks.\n // I suspect that there might be some efficiency benefits from not creating the suspended task\n // and instead just using the stack if possible.\n // TODO: Call this directly instead of messing with saving and restoring contexts.\n // We can reuse the current context and task to render the content immediately without\n // context switching. We just need to temporarily switch which boundary and which segment\n // we're writing to. If something suspends, it'll spawn new suspended task with that context.\n\n task.blockedBoundary = newBoundary;\n task.blockedSegment = contentRootSegment;\n\n try {\n // We use the safe form because we don't handle suspending here. Only error handling.\n renderNode(request, task, content);\n pushSegmentFinale(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded);\n contentRootSegment.status = COMPLETED;\n queueCompletedSegment(newBoundary, contentRootSegment);\n\n if (newBoundary.pendingTasks === 0) {\n // This must have been the last segment we were waiting on. This boundary is now complete.\n // Therefore we won't need the fallback. We early return so that we don't have to create\n // the fallback.\n popComponentStackInDEV(task);\n return;\n }\n } catch (error) {\n contentRootSegment.status = ERRORED;\n newBoundary.forceClientRender = true;\n newBoundary.errorDigest = logRecoverableError(request, error);\n\n {\n captureBoundaryErrorDetailsDev(newBoundary, error);\n } // We don't need to decrement any task numbers because we didn't spawn any new task.\n // We don't need to schedule any task because we know the parent has written yet.\n // We do need to fallthrough to create the fallback though.\n\n } finally {\n task.blockedBoundary = parentBoundary;\n task.blockedSegment = parentSegment;\n } // We create suspended task for the fallback because we don't want to actually work\n // on it yet in case we finish the main content, so we queue for later.\n\n\n var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext);\n\n {\n suspendedFallbackTask.componentStack = task.componentStack;\n } // TODO: This should be queued at a separate lower priority queue so that we only work\n // on preparing fallbacks if we don't have any more main content to task on.\n\n\n request.pingedTasks.push(suspendedFallbackTask);\n popComponentStackInDEV(task);\n}\n\nfunction renderHostElement(request, task, type, props) {\n pushBuiltInComponentStackInDEV(task, type);\n var segment = task.blockedSegment;\n var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext);\n segment.lastPushedText = false;\n var prevContext = segment.formatContext;\n segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still\n // need to pop back up and finish this subtree of HTML.\n\n renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need\n // the correct context. Therefore this is not in a finally.\n\n segment.formatContext = prevContext;\n pushEndInstance(segment.chunks, type);\n segment.lastPushedText = false;\n popComponentStackInDEV(task);\n}\n\nfunction shouldConstruct$1(Component) {\n return Component.prototype && Component.prototype.isReactComponent;\n}\n\nfunction renderWithHooks(request, task, Component, props, secondArg) {\n var componentIdentity = {};\n prepareToUseHooks(task, componentIdentity);\n var result = Component(props, secondArg);\n return finishHooks(Component, props, result, secondArg);\n}\n\nfunction finishClassComponent(request, task, instance, Component, props) {\n var nextChildren = instance.render();\n\n {\n if (instance.props !== props) {\n if (!didWarnAboutReassigningProps) {\n error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component');\n }\n\n didWarnAboutReassigningProps = true;\n }\n }\n\n {\n var childContextTypes = Component.childContextTypes;\n\n if (childContextTypes !== null && childContextTypes !== undefined) {\n var previousContext = task.legacyContext;\n var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes);\n task.legacyContext = mergedContext;\n renderNodeDestructive(request, task, nextChildren);\n task.legacyContext = previousContext;\n return;\n }\n }\n\n renderNodeDestructive(request, task, nextChildren);\n}\n\nfunction renderClassComponent(request, task, Component, props) {\n pushClassComponentStackInDEV(task, Component);\n var maskedContext = getMaskedContext(Component, task.legacyContext) ;\n var instance = constructClassInstance(Component, props, maskedContext);\n mountClassInstance(instance, Component, props, maskedContext);\n finishClassComponent(request, task, instance, Component, props);\n popComponentStackInDEV(task);\n}\n\nvar didWarnAboutBadClass = {};\nvar didWarnAboutModulePatternComponent = {};\nvar didWarnAboutContextTypeOnFunctionComponent = {};\nvar didWarnAboutGetDerivedStateOnFunctionComponent = {};\nvar didWarnAboutReassigningProps = false;\nvar didWarnAboutDefaultPropsOnFunctionComponent = {};\nvar didWarnAboutGenerators = false;\nvar didWarnAboutMaps = false;\nvar hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern\n// components for some reason.\n\nfunction renderIndeterminateComponent(request, task, Component, props) {\n var legacyContext;\n\n {\n legacyContext = getMaskedContext(Component, task.legacyContext);\n }\n\n pushFunctionComponentStackInDEV(task, Component);\n\n {\n if (Component.prototype && typeof Component.prototype.render === 'function') {\n var componentName = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutBadClass[componentName]) {\n error(\"The <%s /> component appears to have a render method, but doesn't extend React.Component. \" + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);\n\n didWarnAboutBadClass[componentName] = true;\n }\n }\n }\n\n var value = renderWithHooks(request, task, Component, props, legacyContext);\n var hasId = checkDidRenderIdHook();\n\n {\n // Support for module components is deprecated and is removed behind a flag.\n // Whether or not it would crash later, we want to show a good message in DEV first.\n if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {\n var _componentName = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutModulePatternComponent[_componentName]) {\n error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + \"If you can't use a class try assigning the prototype on the function as a workaround. \" + \"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it \" + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);\n\n didWarnAboutModulePatternComponent[_componentName] = true;\n }\n }\n }\n\n if ( // Run these checks in production only if the flag is off.\n // Eventually we'll delete this branch altogether.\n typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {\n {\n var _componentName2 = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutModulePatternComponent[_componentName2]) {\n error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + \"If you can't use a class try assigning the prototype on the function as a workaround. \" + \"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it \" + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2);\n\n didWarnAboutModulePatternComponent[_componentName2] = true;\n }\n }\n\n mountClassInstance(value, Component, props, legacyContext);\n finishClassComponent(request, task, value, Component, props);\n } else {\n\n {\n validateFunctionComponentInDev(Component);\n } // We're now successfully past this task, and we don't have to pop back to\n // the previous task every again, so we can use the destructive recursive form.\n\n\n if (hasId) {\n // This component materialized an id. We treat this as its own level, with\n // a single \"child\" slot.\n var prevTreeContext = task.treeContext;\n var totalChildren = 1;\n var index = 0;\n task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);\n\n try {\n renderNodeDestructive(request, task, value);\n } finally {\n task.treeContext = prevTreeContext;\n }\n } else {\n renderNodeDestructive(request, task, value);\n }\n }\n\n popComponentStackInDEV(task);\n}\n\nfunction validateFunctionComponentInDev(Component) {\n {\n if (Component) {\n if (Component.childContextTypes) {\n error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');\n }\n }\n\n if ( Component.defaultProps !== undefined) {\n var componentName = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {\n error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName);\n\n didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;\n }\n }\n\n if (typeof Component.getDerivedStateFromProps === 'function') {\n var _componentName3 = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {\n error('%s: Function components do not support getDerivedStateFromProps.', _componentName3);\n\n didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;\n }\n }\n\n if (typeof Component.contextType === 'object' && Component.contextType !== null) {\n var _componentName4 = getComponentNameFromType(Component) || 'Unknown';\n\n if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {\n error('%s: Function components do not support contextType.', _componentName4);\n\n didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;\n }\n }\n }\n}\n\nfunction resolveDefaultProps(Component, baseProps) {\n if (Component && Component.defaultProps) {\n // Resolve default props. Taken from ReactElement\n var props = assign({}, baseProps);\n var defaultProps = Component.defaultProps;\n\n for (var propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n\n return props;\n }\n\n return baseProps;\n}\n\nfunction renderForwardRef(request, task, type, props, ref) {\n pushFunctionComponentStackInDEV(task, type.render);\n var children = renderWithHooks(request, task, type.render, props, ref);\n var hasId = checkDidRenderIdHook();\n\n if (hasId) {\n // This component materialized an id. We treat this as its own level, with\n // a single \"child\" slot.\n var prevTreeContext = task.treeContext;\n var totalChildren = 1;\n var index = 0;\n task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index);\n\n try {\n renderNodeDestructive(request, task, children);\n } finally {\n task.treeContext = prevTreeContext;\n }\n } else {\n renderNodeDestructive(request, task, children);\n }\n\n popComponentStackInDEV(task);\n}\n\nfunction renderMemo(request, task, type, props, ref) {\n var innerType = type.type;\n var resolvedProps = resolveDefaultProps(innerType, props);\n renderElement(request, task, innerType, resolvedProps, ref);\n}\n\nfunction renderContextConsumer(request, task, context, props) {\n // The logic below for Context differs depending on PROD or DEV mode. In\n // DEV mode, we create a separate object for Context.Consumer that acts\n // like a proxy to Context. This proxy object adds unnecessary code in PROD\n // so we use the old behaviour (Context.Consumer references Context) to\n // reduce size and overhead. The separate object references context via\n // a property called \"_context\", which also gives us the ability to check\n // in DEV mode if this property exists or not and warn if it does not.\n {\n if (context._context === undefined) {\n // This may be because it's a Context (rather than a Consumer).\n // Or it may be because it's older React where they're the same thing.\n // We only want to warn if we're sure it's a new React.\n if (context !== context.Consumer) {\n if (!hasWarnedAboutUsingContextAsConsumer) {\n hasWarnedAboutUsingContextAsConsumer = true;\n\n error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?');\n }\n }\n } else {\n context = context._context;\n }\n }\n\n var render = props.children;\n\n {\n if (typeof render !== 'function') {\n error('A context consumer was rendered with multiple children, or a child ' + \"that isn't a function. A context consumer expects a single child \" + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');\n }\n }\n\n var newValue = readContext(context);\n var newChildren = render(newValue);\n renderNodeDestructive(request, task, newChildren);\n}\n\nfunction renderContextProvider(request, task, type, props) {\n var context = type._context;\n var value = props.value;\n var children = props.children;\n var prevSnapshot;\n\n {\n prevSnapshot = task.context;\n }\n\n task.context = pushProvider(context, value);\n renderNodeDestructive(request, task, children);\n task.context = popProvider(context);\n\n {\n if (prevSnapshot !== task.context) {\n error('Popping the context provider did not return back to the original snapshot. This is a bug in React.');\n }\n }\n}\n\nfunction renderLazyComponent(request, task, lazyComponent, props, ref) {\n pushBuiltInComponentStackInDEV(task, 'Lazy');\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n var Component = init(payload);\n var resolvedProps = resolveDefaultProps(Component, props);\n renderElement(request, task, Component, resolvedProps, ref);\n popComponentStackInDEV(task);\n}\n\nfunction renderElement(request, task, type, props, ref) {\n if (typeof type === 'function') {\n if (shouldConstruct$1(type)) {\n renderClassComponent(request, task, type, props);\n return;\n } else {\n renderIndeterminateComponent(request, task, type, props);\n return;\n }\n }\n\n if (typeof type === 'string') {\n renderHostElement(request, task, type, props);\n return;\n }\n\n switch (type) {\n // TODO: LegacyHidden acts the same as a fragment. This only works\n // because we currently assume that every instance of LegacyHidden is\n // accompanied by a host component wrapper. In the hidden mode, the host\n // component is given a `hidden` attribute, which ensures that the\n // initial HTML is not visible. To support the use of LegacyHidden as a\n // true fragment, without an extra DOM node, we would have to hide the\n // initial HTML in some other way.\n // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability.\n case REACT_LEGACY_HIDDEN_TYPE:\n case REACT_DEBUG_TRACING_MODE_TYPE:\n case REACT_STRICT_MODE_TYPE:\n case REACT_PROFILER_TYPE:\n case REACT_FRAGMENT_TYPE:\n {\n renderNodeDestructive(request, task, props.children);\n return;\n }\n\n case REACT_SUSPENSE_LIST_TYPE:\n {\n pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries.\n\n renderNodeDestructive(request, task, props.children);\n popComponentStackInDEV(task);\n return;\n }\n\n case REACT_SCOPE_TYPE:\n {\n\n throw new Error('ReactDOMServer does not yet support scope components.');\n }\n // eslint-disable-next-line-no-fallthrough\n\n case REACT_SUSPENSE_TYPE:\n {\n {\n renderSuspenseBoundary(request, task, props);\n }\n\n return;\n }\n }\n\n if (typeof type === 'object' && type !== null) {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n {\n renderForwardRef(request, task, type, props, ref);\n return;\n }\n\n case REACT_MEMO_TYPE:\n {\n renderMemo(request, task, type, props, ref);\n return;\n }\n\n case REACT_PROVIDER_TYPE:\n {\n renderContextProvider(request, task, type, props);\n return;\n }\n\n case REACT_CONTEXT_TYPE:\n {\n renderContextConsumer(request, task, type, props);\n return;\n }\n\n case REACT_LAZY_TYPE:\n {\n renderLazyComponent(request, task, type, props);\n return;\n }\n }\n }\n\n var info = '';\n\n {\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and \" + 'named imports.';\n }\n }\n\n throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + (\"but got: \" + (type == null ? type : typeof type) + \".\" + info));\n}\n\nfunction validateIterable(iterable, iteratorFn) {\n {\n // We don't support rendering Generators because it's a mutation.\n // See https://github.com/facebook/react/issues/12995\n if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag\n iterable[Symbol.toStringTag] === 'Generator') {\n if (!didWarnAboutGenerators) {\n error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');\n }\n\n didWarnAboutGenerators = true;\n } // Warn about using Maps as children\n\n\n if (iterable.entries === iteratorFn) {\n if (!didWarnAboutMaps) {\n error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');\n }\n\n didWarnAboutMaps = true;\n }\n }\n}\n\nfunction renderNodeDestructive(request, task, node) {\n {\n // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture\n // a component stack at the right place in the tree. We don't do this in renderNode\n // becuase it is not called at every layer of the tree and we may lose frames\n try {\n return renderNodeDestructiveImpl(request, task, node);\n } catch (x) {\n if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else {\n // This is an error, stash the component stack if it is null.\n lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV();\n } // rethrow so normal suspense logic can handle thrown value accordingly\n\n\n throw x;\n }\n }\n} // This function by it self renders a node and consumes the task by mutating it\n// to update the current execution state.\n\n\nfunction renderNodeDestructiveImpl(request, task, node) {\n // Stash the node we're working on. We'll pick up from this task in case\n // something suspends.\n task.node = node; // Handle object types\n\n if (typeof node === 'object' && node !== null) {\n switch (node.$$typeof) {\n case REACT_ELEMENT_TYPE:\n {\n var element = node;\n var type = element.type;\n var props = element.props;\n var ref = element.ref;\n renderElement(request, task, type, props, ref);\n return;\n }\n\n case REACT_PORTAL_TYPE:\n throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.');\n // eslint-disable-next-line-no-fallthrough\n\n case REACT_LAZY_TYPE:\n {\n var lazyNode = node;\n var payload = lazyNode._payload;\n var init = lazyNode._init;\n var resolvedNode;\n\n {\n try {\n resolvedNode = init(payload);\n } catch (x) {\n if (typeof x === 'object' && x !== null && typeof x.then === 'function') {\n // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be\n // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position\n // vs Component position. We do not want the frame for Errors so we exclusively do this in\n // the wakeable branch\n pushBuiltInComponentStackInDEV(task, 'Lazy');\n }\n\n throw x;\n }\n }\n\n renderNodeDestructive(request, task, resolvedNode);\n return;\n }\n }\n\n if (isArray(node)) {\n renderChildrenArray(request, task, node);\n return;\n }\n\n var iteratorFn = getIteratorFn(node);\n\n if (iteratorFn) {\n {\n validateIterable(node, iteratorFn);\n }\n\n var iterator = iteratorFn.call(node);\n\n if (iterator) {\n // We need to know how many total children are in this set, so that we\n // can allocate enough id slots to acommodate them. So we must exhaust\n // the iterator before we start recursively rendering the children.\n // TODO: This is not great but I think it's inherent to the id\n // generation algorithm.\n var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that.\n\n if (!step.done) {\n var children = [];\n\n do {\n children.push(step.value);\n step = iterator.next();\n } while (!step.done);\n\n renderChildrenArray(request, task, children);\n return;\n }\n\n return;\n }\n }\n\n var childString = Object.prototype.toString.call(node);\n throw new Error(\"Objects are not valid as a React child (found: \" + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + \"). \" + 'If you meant to render a collection of children, use an array ' + 'instead.');\n }\n\n if (typeof node === 'string') {\n var segment = task.blockedSegment;\n segment.lastPushedText = pushTextInstance(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText);\n return;\n }\n\n if (typeof node === 'number') {\n var _segment = task.blockedSegment;\n _segment.lastPushedText = pushTextInstance(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText);\n return;\n }\n\n {\n if (typeof node === 'function') {\n error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.');\n }\n }\n}\n\nfunction renderChildrenArray(request, task, children) {\n var totalChildren = children.length;\n\n for (var i = 0; i < totalChildren; i++) {\n var prevTreeContext = task.treeContext;\n task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i);\n\n try {\n // We need to use the non-destructive form so that we can safely pop back\n // up and render the sibling if something suspends.\n renderNode(request, task, children[i]);\n } finally {\n task.treeContext = prevTreeContext;\n }\n }\n}\n\nfunction spawnNewSuspendedTask(request, task, x) {\n // Something suspended, we'll need to create a new segment and resolve it later.\n var segment = task.blockedSegment;\n var insertionIndex = segment.chunks.length;\n var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed\n segment.lastPushedText, // Assume we are text embedded at the trailing edge\n true);\n segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment \"consumed\" it\n\n segment.lastPushedText = false;\n var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext);\n\n {\n if (task.componentStack !== null) {\n // We pop one task off the stack because the node that suspended will be tried again,\n // which will add it back onto the stack.\n newTask.componentStack = task.componentStack.parent;\n }\n }\n\n var ping = newTask.ping;\n x.then(ping, ping);\n} // This is a non-destructive form of rendering a node. If it suspends it spawns\n// a new task and restores the context of this task to what it was before.\n\n\nfunction renderNode(request, task, node) {\n // TODO: Store segment.children.length here and reset it in case something\n // suspended partially through writing something.\n // Snapshot the current context in case something throws to interrupt the\n // process.\n var previousFormatContext = task.blockedSegment.formatContext;\n var previousLegacyContext = task.legacyContext;\n var previousContext = task.context;\n var previousComponentStack = null;\n\n {\n previousComponentStack = task.componentStack;\n }\n\n try {\n return renderNodeDestructive(request, task, node);\n } catch (x) {\n resetHooksState();\n\n if (typeof x === 'object' && x !== null && typeof x.then === 'function') {\n spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner\n // functions in case nothing throws so we don't use \"finally\" here.\n\n task.blockedSegment.formatContext = previousFormatContext;\n task.legacyContext = previousLegacyContext;\n task.context = previousContext; // Restore all active ReactContexts to what they were before.\n\n switchContext(previousContext);\n\n {\n task.componentStack = previousComponentStack;\n }\n\n return;\n } else {\n // Restore the context. We assume that this will be restored by the inner\n // functions in case nothing throws so we don't use \"finally\" here.\n task.blockedSegment.formatContext = previousFormatContext;\n task.legacyContext = previousLegacyContext;\n task.context = previousContext; // Restore all active ReactContexts to what they were before.\n\n switchContext(previousContext);\n\n {\n task.componentStack = previousComponentStack;\n } // We assume that we don't need the correct context.\n // Let's terminate the rest of the tree and don't render any siblings.\n\n\n throw x;\n }\n }\n}\n\nfunction erroredTask(request, boundary, segment, error) {\n // Report the error to a global handler.\n var errorDigest = logRecoverableError(request, error);\n\n if (boundary === null) {\n fatalError(request, error);\n } else {\n boundary.pendingTasks--;\n\n if (!boundary.forceClientRender) {\n boundary.forceClientRender = true;\n boundary.errorDigest = errorDigest;\n\n {\n captureBoundaryErrorDetailsDev(boundary, error);\n } // Regardless of what happens next, this boundary won't be displayed,\n // so we can flush it, if the parent already flushed.\n\n\n if (boundary.parentFlushed) {\n // We don't have a preference where in the queue this goes since it's likely\n // to error on the client anyway. However, intentionally client-rendered\n // boundaries should be flushed earlier so that they can start on the client.\n // We reuse the same queue for errors.\n request.clientRenderedBoundaries.push(boundary);\n }\n }\n }\n\n request.allPendingTasks--;\n\n if (request.allPendingTasks === 0) {\n var onAllReady = request.onAllReady;\n onAllReady();\n }\n}\n\nfunction abortTaskSoft(task) {\n // This aborts task without aborting the parent boundary that it blocks.\n // It's used for when we didn't need this task to complete the tree.\n // If task was needed, then it should use abortTask instead.\n var request = this;\n var boundary = task.blockedBoundary;\n var segment = task.blockedSegment;\n segment.status = ABORTED;\n finishedTask(request, boundary, segment);\n}\n\nfunction abortTask(task, request, reason) {\n // This aborts the task and aborts the parent that it blocks, putting it into\n // client rendered mode.\n var boundary = task.blockedBoundary;\n var segment = task.blockedSegment;\n segment.status = ABORTED;\n\n if (boundary === null) {\n request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close\n // the request;\n\n if (request.status !== CLOSED) {\n request.status = CLOSED;\n\n if (request.destination !== null) {\n close(request.destination);\n }\n }\n } else {\n boundary.pendingTasks--;\n\n if (!boundary.forceClientRender) {\n boundary.forceClientRender = true;\n\n var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason;\n\n boundary.errorDigest = request.onError(_error);\n\n {\n var errorPrefix = 'The server did not finish this Suspense boundary: ';\n\n if (_error && typeof _error.message === 'string') {\n _error = errorPrefix + _error.message;\n } else {\n // eslint-disable-next-line react-internal/safe-string-coercion\n _error = errorPrefix + String(_error);\n }\n\n var previousTaskInDev = currentTaskInDEV;\n currentTaskInDEV = task;\n\n try {\n captureBoundaryErrorDetailsDev(boundary, _error);\n } finally {\n currentTaskInDEV = previousTaskInDev;\n }\n }\n\n if (boundary.parentFlushed) {\n request.clientRenderedBoundaries.push(boundary);\n }\n } // If this boundary was still pending then we haven't already cancelled its fallbacks.\n // We'll need to abort the fallbacks, which will also error that parent boundary.\n\n\n boundary.fallbackAbortableTasks.forEach(function (fallbackTask) {\n return abortTask(fallbackTask, request, reason);\n });\n boundary.fallbackAbortableTasks.clear();\n request.allPendingTasks--;\n\n if (request.allPendingTasks === 0) {\n var onAllReady = request.onAllReady;\n onAllReady();\n }\n }\n}\n\nfunction queueCompletedSegment(boundary, segment) {\n if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) {\n // This is an empty segment. There's nothing to write, so we can instead transfer the ID\n // to the child. That way any existing references point to the child.\n var childSegment = segment.children[0];\n childSegment.id = segment.id;\n childSegment.parentFlushed = true;\n\n if (childSegment.status === COMPLETED) {\n queueCompletedSegment(boundary, childSegment);\n }\n } else {\n var completedSegments = boundary.completedSegments;\n completedSegments.push(segment);\n }\n}\n\nfunction finishedTask(request, boundary, segment) {\n if (boundary === null) {\n if (segment.parentFlushed) {\n if (request.completedRootSegment !== null) {\n throw new Error('There can only be one root segment. This is a bug in React.');\n }\n\n request.completedRootSegment = segment;\n }\n\n request.pendingRootTasks--;\n\n if (request.pendingRootTasks === 0) {\n // We have completed the shell so the shell can't error anymore.\n request.onShellError = noop$1;\n var onShellReady = request.onShellReady;\n onShellReady();\n }\n } else {\n boundary.pendingTasks--;\n\n if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) {\n // This must have been the last segment we were waiting on. This boundary is now complete.\n if (segment.parentFlushed) {\n // Our parent segment already flushed, so we need to schedule this segment to be emitted.\n // If it is a segment that was aborted, we'll write other content instead so we don't need\n // to emit it.\n if (segment.status === COMPLETED) {\n queueCompletedSegment(boundary, segment);\n }\n }\n\n if (boundary.parentFlushed) {\n // The segment might be part of a segment that didn't flush yet, but if the boundary's\n // parent flushed, we need to schedule the boundary to be emitted.\n request.completedBoundaries.push(boundary);\n } // We can now cancel any pending task on the fallback since we won't need to show it anymore.\n // This needs to happen after we read the parentFlushed flags because aborting can finish\n // work which can trigger user code, which can start flushing, which can change those flags.\n\n\n boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request);\n boundary.fallbackAbortableTasks.clear();\n } else {\n if (segment.parentFlushed) {\n // Our parent already flushed, so we need to schedule this segment to be emitted.\n // If it is a segment that was aborted, we'll write other content instead so we don't need\n // to emit it.\n if (segment.status === COMPLETED) {\n queueCompletedSegment(boundary, segment);\n var completedSegments = boundary.completedSegments;\n\n if (completedSegments.length === 1) {\n // This is the first time since we last flushed that we completed anything.\n // We can schedule this boundary to emit its partially completed segments early\n // in case the parent has already been flushed.\n if (boundary.parentFlushed) {\n request.partialBoundaries.push(boundary);\n }\n }\n }\n }\n }\n }\n\n request.allPendingTasks--;\n\n if (request.allPendingTasks === 0) {\n // This needs to be called at the very end so that we can synchronously write the result\n // in the callback if needed.\n var onAllReady = request.onAllReady;\n onAllReady();\n }\n}\n\nfunction retryTask(request, task) {\n var segment = task.blockedSegment;\n\n if (segment.status !== PENDING) {\n // We completed this by other means before we had a chance to retry it.\n return;\n } // We restore the context to what it was when we suspended.\n // We don't restore it after we leave because it's likely that we'll end up\n // needing a very similar context soon again.\n\n\n switchContext(task.context);\n var prevTaskInDEV = null;\n\n {\n prevTaskInDEV = currentTaskInDEV;\n currentTaskInDEV = task;\n }\n\n try {\n // We call the destructive form that mutates this task. That way if something\n // suspends again, we can reuse the same task instead of spawning a new one.\n renderNodeDestructive(request, task, task.node);\n pushSegmentFinale(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded);\n task.abortSet.delete(task);\n segment.status = COMPLETED;\n finishedTask(request, task.blockedBoundary, segment);\n } catch (x) {\n resetHooksState();\n\n if (typeof x === 'object' && x !== null && typeof x.then === 'function') {\n // Something suspended again, let's pick it back up later.\n var ping = task.ping;\n x.then(ping, ping);\n } else {\n task.abortSet.delete(task);\n segment.status = ERRORED;\n erroredTask(request, task.blockedBoundary, segment, x);\n }\n } finally {\n {\n currentTaskInDEV = prevTaskInDEV;\n }\n }\n}\n\nfunction performWork(request) {\n if (request.status === CLOSED) {\n return;\n }\n\n var prevContext = getActiveContext();\n var prevDispatcher = ReactCurrentDispatcher$1.current;\n ReactCurrentDispatcher$1.current = Dispatcher;\n var prevGetCurrentStackImpl;\n\n {\n prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack;\n ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV;\n }\n\n var prevResponseState = currentResponseState;\n setCurrentResponseState(request.responseState);\n\n try {\n var pingedTasks = request.pingedTasks;\n var i;\n\n for (i = 0; i < pingedTasks.length; i++) {\n var task = pingedTasks[i];\n retryTask(request, task);\n }\n\n pingedTasks.splice(0, i);\n\n if (request.destination !== null) {\n flushCompletedQueues(request, request.destination);\n }\n } catch (error) {\n logRecoverableError(request, error);\n fatalError(request, error);\n } finally {\n setCurrentResponseState(prevResponseState);\n ReactCurrentDispatcher$1.current = prevDispatcher;\n\n {\n ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl;\n }\n\n if (prevDispatcher === Dispatcher) {\n // This means that we were in a reentrant work loop. This could happen\n // in a renderer that supports synchronous work like renderToString,\n // when it's called from within another renderer.\n // Normally we don't bother switching the contexts to their root/default\n // values when leaving because we'll likely need the same or similar\n // context again. However, when we're inside a synchronous loop like this\n // we'll to restore the context to what it was before returning.\n switchContext(prevContext);\n }\n }\n}\n\nfunction flushSubtree(request, destination, segment) {\n segment.parentFlushed = true;\n\n switch (segment.status) {\n case PENDING:\n {\n // We're emitting a placeholder for this segment to be filled in later.\n // Therefore we'll need to assign it an ID - to refer to it by.\n var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately\n\n segment.lastPushedText = false;\n segment.textEmbedded = false;\n return writePlaceholder(destination, request.responseState, segmentID);\n }\n\n case COMPLETED:\n {\n segment.status = FLUSHED;\n var r = true;\n var chunks = segment.chunks;\n var chunkIdx = 0;\n var children = segment.children;\n\n for (var childIdx = 0; childIdx < children.length; childIdx++) {\n var nextChild = children[childIdx]; // Write all the chunks up until the next child.\n\n for (; chunkIdx < nextChild.index; chunkIdx++) {\n writeChunk(destination, chunks[chunkIdx]);\n }\n\n r = flushSegment(request, destination, nextChild);\n } // Finally just write all the remaining chunks\n\n\n for (; chunkIdx < chunks.length - 1; chunkIdx++) {\n writeChunk(destination, chunks[chunkIdx]);\n }\n\n if (chunkIdx < chunks.length) {\n r = writeChunkAndReturn(destination, chunks[chunkIdx]);\n }\n\n return r;\n }\n\n default:\n {\n throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.');\n }\n }\n}\n\nfunction flushSegment(request, destination, segment) {\n var boundary = segment.boundary;\n\n if (boundary === null) {\n // Not a suspense boundary.\n return flushSubtree(request, destination, segment);\n }\n\n boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to\n // emit the content or the fallback now.\n\n if (boundary.forceClientRender) {\n // Emit a client rendered suspense boundary wrapper.\n // We never queue the inner boundary so we'll never emit its content or partial segments.\n writeStartClientRenderedSuspenseBoundary(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback.\n\n flushSubtree(request, destination, segment);\n return writeEndClientRenderedSuspenseBoundary(destination, request.responseState);\n } else if (boundary.pendingTasks > 0) {\n // This boundary is still loading. Emit a pending suspense boundary wrapper.\n // Assign an ID to refer to the future content by.\n boundary.rootSegmentID = request.nextSegmentId++;\n\n if (boundary.completedSegments.length > 0) {\n // If this is at least partially complete, we can queue it to be partially emitted early.\n request.partialBoundaries.push(boundary);\n } /// This is the first time we should have referenced this ID.\n\n\n var id = boundary.id = assignSuspenseBoundaryID(request.responseState);\n writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback.\n\n flushSubtree(request, destination, segment);\n return writeEndPendingSuspenseBoundary(destination, request.responseState);\n } else if (boundary.byteSize > request.progressiveChunkSize) {\n // This boundary is large and will be emitted separately so that we can progressively show\n // other content. We add it to the queue during the flush because we have to ensure that\n // the parent flushes first so that there's something to inject it into.\n // We also have to make sure that it's emitted into the queue in a deterministic slot.\n // I.e. we can't insert it here when it completes.\n // Assign an ID to refer to the future content by.\n boundary.rootSegmentID = request.nextSegmentId++;\n request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper.\n\n writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback.\n\n flushSubtree(request, destination, segment);\n return writeEndPendingSuspenseBoundary(destination, request.responseState);\n } else {\n // We can inline this boundary's content as a complete boundary.\n writeStartCompletedSuspenseBoundary(destination, request.responseState);\n var completedSegments = boundary.completedSegments;\n\n if (completedSegments.length !== 1) {\n throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.');\n }\n\n var contentSegment = completedSegments[0];\n flushSegment(request, destination, contentSegment);\n return writeEndCompletedSuspenseBoundary(destination, request.responseState);\n }\n}\n\nfunction flushClientRenderedBoundary(request, destination, boundary) {\n return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack);\n}\n\nfunction flushSegmentContainer(request, destination, segment) {\n writeStartSegment(destination, request.responseState, segment.formatContext, segment.id);\n flushSegment(request, destination, segment);\n return writeEndSegment(destination, segment.formatContext);\n}\n\nfunction flushCompletedBoundary(request, destination, boundary) {\n var completedSegments = boundary.completedSegments;\n var i = 0;\n\n for (; i < completedSegments.length; i++) {\n var segment = completedSegments[i];\n flushPartiallyCompletedSegment(request, destination, boundary, segment);\n }\n\n completedSegments.length = 0;\n return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID);\n}\n\nfunction flushPartialBoundary(request, destination, boundary) {\n var completedSegments = boundary.completedSegments;\n var i = 0;\n\n for (; i < completedSegments.length; i++) {\n var segment = completedSegments[i];\n\n if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) {\n i++;\n completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority\n // might want to write later.\n\n return false;\n }\n }\n\n completedSegments.splice(0, i);\n return true;\n}\n\nfunction flushPartiallyCompletedSegment(request, destination, boundary, segment) {\n if (segment.status === FLUSHED) {\n // We've already flushed this inline.\n return true;\n }\n\n var segmentID = segment.id;\n\n if (segmentID === -1) {\n // This segment wasn't previously referred to. This happens at the root of\n // a boundary. We make kind of a leap here and assume this is the root.\n var rootSegmentID = segment.id = boundary.rootSegmentID;\n\n if (rootSegmentID === -1) {\n throw new Error('A root segment ID must have been assigned by now. This is a bug in React.');\n }\n\n return flushSegmentContainer(request, destination, segment);\n } else {\n flushSegmentContainer(request, destination, segment);\n return writeCompletedSegmentInstruction(destination, request.responseState, segmentID);\n }\n}\n\nfunction flushCompletedQueues(request, destination) {\n beginWriting();\n\n try {\n // The structure of this is to go through each queue one by one and write\n // until the sink tells us to stop. When we should stop, we still finish writing\n // that item fully and then yield. At that point we remove the already completed\n // items up until the point we completed them.\n // TODO: Emit preloading.\n // TODO: It's kind of unfortunate to keep checking this array after we've already\n // emitted the root.\n var completedRootSegment = request.completedRootSegment;\n\n if (completedRootSegment !== null && request.pendingRootTasks === 0) {\n flushSegment(request, destination, completedRootSegment);\n request.completedRootSegment = null;\n writeCompletedRoot(destination, request.responseState);\n } // We emit client rendering instructions for already emitted boundaries first.\n // This is so that we can signal to the client to start client rendering them as\n // soon as possible.\n\n\n var clientRenderedBoundaries = request.clientRenderedBoundaries;\n var i;\n\n for (i = 0; i < clientRenderedBoundaries.length; i++) {\n var boundary = clientRenderedBoundaries[i];\n\n if (!flushClientRenderedBoundary(request, destination, boundary)) {\n request.destination = null;\n i++;\n clientRenderedBoundaries.splice(0, i);\n return;\n }\n }\n\n clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries\n // that are completely done since we can actually show them, than it is to emit\n // any individual segments from a partially complete boundary.\n\n var completedBoundaries = request.completedBoundaries;\n\n for (i = 0; i < completedBoundaries.length; i++) {\n var _boundary = completedBoundaries[i];\n\n if (!flushCompletedBoundary(request, destination, _boundary)) {\n request.destination = null;\n i++;\n completedBoundaries.splice(0, i);\n return;\n }\n }\n\n completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before\n // we continue with lower priorities.\n\n completeWriting(destination);\n beginWriting(destination); // TODO: Here we'll emit data used by hydration.\n // Next we emit any segments of any boundaries that are partially complete\n // but not deeply complete.\n\n var partialBoundaries = request.partialBoundaries;\n\n for (i = 0; i < partialBoundaries.length; i++) {\n var _boundary2 = partialBoundaries[i];\n\n if (!flushPartialBoundary(request, destination, _boundary2)) {\n request.destination = null;\n i++;\n partialBoundaries.splice(0, i);\n return;\n }\n }\n\n partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had\n // boundaries added to it in case they were too larged to be inlined.\n // New ones might be added in this loop.\n\n var largeBoundaries = request.completedBoundaries;\n\n for (i = 0; i < largeBoundaries.length; i++) {\n var _boundary3 = largeBoundaries[i];\n\n if (!flushCompletedBoundary(request, destination, _boundary3)) {\n request.destination = null;\n i++;\n largeBoundaries.splice(0, i);\n return;\n }\n }\n\n largeBoundaries.splice(0, i);\n } finally {\n completeWriting(destination);\n\n if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because\n // either they have pending task or they're complete.\n ) {\n {\n if (request.abortableTasks.size !== 0) {\n error('There was still abortable task at the root when we closed. This is a bug in React.');\n }\n } // We're done.\n\n\n close(destination);\n }\n }\n}\n\nfunction startWork(request) {\n scheduleWork(function () {\n return performWork(request);\n });\n}\nfunction startFlowing(request, destination) {\n if (request.status === CLOSING) {\n request.status = CLOSED;\n closeWithError(destination, request.fatalError);\n return;\n }\n\n if (request.status === CLOSED) {\n return;\n }\n\n if (request.destination !== null) {\n // We're already flowing.\n return;\n }\n\n request.destination = destination;\n\n try {\n flushCompletedQueues(request, destination);\n } catch (error) {\n logRecoverableError(request, error);\n fatalError(request, error);\n }\n} // This is called to early terminate a request. It puts all pending boundaries in client rendered state.\n\nfunction abort(request, reason) {\n try {\n var abortableTasks = request.abortableTasks;\n abortableTasks.forEach(function (task) {\n return abortTask(task, request, reason);\n });\n abortableTasks.clear();\n\n if (request.destination !== null) {\n flushCompletedQueues(request, request.destination);\n }\n } catch (error) {\n logRecoverableError(request, error);\n fatalError(request, error);\n }\n}\n\nfunction renderToReadableStream(children, options) {\n return new Promise(function (resolve, reject) {\n var onFatalError;\n var onAllReady;\n var allReady = new Promise(function (res, rej) {\n onAllReady = res;\n onFatalError = rej;\n });\n\n function onShellReady() {\n var stream = new ReadableStream({\n type: 'bytes',\n pull: function (controller) {\n startFlowing(request, controller);\n },\n cancel: function (reason) {\n abort(request);\n }\n }, // $FlowFixMe size() methods are not allowed on byte streams.\n {\n highWaterMark: 0\n }); // TODO: Move to sub-classing ReadableStream.\n\n stream.allReady = allReady;\n resolve(stream);\n }\n\n function onShellError(error) {\n // If the shell errors the caller of `renderToReadableStream` won't have access to `allReady`.\n // However, `allReady` will be rejected by `onFatalError` as well.\n // So we need to catch the duplicate, uncatchable fatal error in `allReady` to prevent a `UnhandledPromiseRejection`.\n allReady.catch(function () {});\n reject(error);\n }\n\n var request = createRequest(children, createResponseState(options ? options.identifierPrefix : undefined, options ? options.nonce : undefined, options ? options.bootstrapScriptContent : undefined, options ? options.bootstrapScripts : undefined, options ? options.bootstrapModules : undefined), createRootFormatContext(options ? options.namespaceURI : undefined), options ? options.progressiveChunkSize : undefined, options ? options.onError : undefined, onAllReady, onShellReady, onShellError, onFatalError);\n\n if (options && options.signal) {\n var signal = options.signal;\n\n var listener = function () {\n abort(request, signal.reason);\n signal.removeEventListener('abort', listener);\n };\n\n signal.addEventListener('abort', listener);\n }\n\n startWork(request);\n });\n}\n\nexports.renderToReadableStream = renderToReadableStream;\nexports.version = ReactVersion;\n })();\n}\n", "'use strict';\n\nvar l, s;\nif (process.env.NODE_ENV === 'production') {\n l = require('./cjs/react-dom-server-legacy.browser.production.min.js');\n s = require('./cjs/react-dom-server.browser.production.min.js');\n} else {\n l = require('./cjs/react-dom-server-legacy.browser.development.js');\n s = require('./cjs/react-dom-server.browser.development.js');\n}\n\nexports.version = l.version;\nexports.renderToString = l.renderToString;\nexports.renderToStaticMarkup = l.renderToStaticMarkup;\nexports.renderToNodeStream = l.renderToNodeStream;\nexports.renderToStaticNodeStream = l.renderToStaticNodeStream;\nexports.renderToReadableStream = s.renderToReadableStream;\n", "/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n'use strict';\n\nvar React = require('react');\n\n// ATTENTION\n// When adding new symbols to this file,\n// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'\n// The Symbol used to tag the ReactElement-like types.\nvar REACT_ELEMENT_TYPE = Symbol.for('react.element');\nvar REACT_PORTAL_TYPE = Symbol.for('react.portal');\nvar REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');\nvar REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');\nvar REACT_PROFILER_TYPE = Symbol.for('react.profiler');\nvar REACT_PROVIDER_TYPE = Symbol.for('react.provider');\nvar REACT_CONTEXT_TYPE = Symbol.for('react.context');\nvar REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');\nvar REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');\nvar REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');\nvar REACT_MEMO_TYPE = Symbol.for('react.memo');\nvar REACT_LAZY_TYPE = Symbol.for('react.lazy');\nvar REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');\nvar MAYBE_ITERATOR_SYMBOL = Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;\n\nfunction error(format) {\n {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n } // eslint-disable-next-line react-internal/safe-string-coercion\n\n\n var argsWithFormat = args.map(function (item) {\n return String(item);\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\n }\n}\n\n// -----------------------------------------------------------------------------\n\nvar enableScopeAPI = false; // Experimental Create Event Handle API.\nvar enableCacheElement = false;\nvar enableTransitionTracing = false; // No known bugs, but needs performance testing\n\nvar enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber\n// stuff. Intended to enable React core members to more easily debug scheduling\n// issues in DEV builds.\n\nvar enableDebugTracing = false; // Track which Fiber(s) schedule render work.\n\nvar REACT_MODULE_REFERENCE;\n\n{\n REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');\n}\n\nfunction isValidElementType(type) {\n if (typeof type === 'string' || typeof type === 'function') {\n return true;\n } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).\n\n\n if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {\n return true;\n }\n\n if (typeof type === 'object' && type !== null) {\n if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object\n // types supported by any Flight configuration anywhere since\n // we don't know which Flight build this will end up being used\n // with.\n type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var displayName = outerType.displayName;\n\n if (displayName) {\n return displayName;\n }\n\n var functionName = innerType.displayName || innerType.name || '';\n return functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName;\n} // Keep in sync with react-reconciler/getComponentNameFromFiber\n\n\nfunction getContextName(type) {\n return type.displayName || 'Context';\n} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.\n\n\nfunction getComponentNameFromType(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return 'Profiler';\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n var context = type;\n return getContextName(context) + '.Consumer';\n\n case REACT_PROVIDER_TYPE:\n var provider = type;\n return getContextName(provider._context) + '.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n var outerName = type.displayName || null;\n\n if (outerName !== null) {\n return outerName;\n }\n\n return getComponentNameFromType(type.type) || 'Memo';\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n return getComponentNameFromType(init(payload));\n } catch (x) {\n return null;\n }\n }\n\n // eslint-disable-next-line no-fallthrough\n }\n }\n\n return null;\n}\n\nvar assign = Object.assign;\n\n// Helpers to patch console.logs to avoid logging during side-effect free\n// replaying on render function. This currently only patches the object\n// lazily which won't cover if the log function was extracted eagerly.\n// We could also eagerly patch the method.\nvar disabledDepth = 0;\nvar prevLog;\nvar prevInfo;\nvar prevWarn;\nvar prevError;\nvar prevGroup;\nvar prevGroupCollapsed;\nvar prevGroupEnd;\n\nfunction disabledLog() {}\n\ndisabledLog.__reactDisabledLog = true;\nfunction disableLogs() {\n {\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n prevLog = console.log;\n prevInfo = console.info;\n prevWarn = console.warn;\n prevError = console.error;\n prevGroup = console.group;\n prevGroupCollapsed = console.groupCollapsed;\n prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099\n\n var props = {\n configurable: true,\n enumerable: true,\n value: disabledLog,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n info: props,\n log: props,\n warn: props,\n error: props,\n group: props,\n groupCollapsed: props,\n groupEnd: props\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n disabledDepth++;\n }\n}\nfunction reenableLogs() {\n {\n disabledDepth--;\n\n if (disabledDepth === 0) {\n /* eslint-disable react-internal/no-production-logging */\n var props = {\n configurable: true,\n enumerable: true,\n writable: true\n }; // $FlowFixMe Flow thinks console is immutable.\n\n Object.defineProperties(console, {\n log: assign({}, props, {\n value: prevLog\n }),\n info: assign({}, props, {\n value: prevInfo\n }),\n warn: assign({}, props, {\n value: prevWarn\n }),\n error: assign({}, props, {\n value: prevError\n }),\n group: assign({}, props, {\n value: prevGroup\n }),\n groupCollapsed: assign({}, props, {\n value: prevGroupCollapsed\n }),\n groupEnd: assign({}, props, {\n value: prevGroupEnd\n })\n });\n /* eslint-enable react-internal/no-production-logging */\n }\n\n if (disabledDepth < 0) {\n error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');\n }\n }\n}\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\nvar prefix;\nfunction describeBuiltInComponentFrame(name, source, ownerFn) {\n {\n if (prefix === undefined) {\n // Extract the VM specific prefix used by each line.\n try {\n throw Error();\n } catch (x) {\n var match = x.stack.trim().match(/\\n( *(at )?)/);\n prefix = match && match[1] || '';\n }\n } // We use the prefix to ensure our stacks line up with native stack frames.\n\n\n return '\\n' + prefix + name;\n }\n}\nvar reentry = false;\nvar componentFrameCache;\n\n{\n var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;\n componentFrameCache = new PossiblyWeakMap();\n}\n\nfunction describeNativeComponentFrame(fn, construct) {\n // If something asked for a stack inside a fake render, it should get ignored.\n if ( !fn || reentry) {\n return '';\n }\n\n {\n var frame = componentFrameCache.get(fn);\n\n if (frame !== undefined) {\n return frame;\n }\n }\n\n var control;\n reentry = true;\n var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.\n\n Error.prepareStackTrace = undefined;\n var previousDispatcher;\n\n {\n previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function\n // for warnings.\n\n ReactCurrentDispatcher.current = null;\n disableLogs();\n }\n\n try {\n // This should throw.\n if (construct) {\n // Something should be setting the props in the constructor.\n var Fake = function () {\n throw Error();\n }; // $FlowFixMe\n\n\n Object.defineProperty(Fake.prototype, 'props', {\n set: function () {\n // We use a throwing setter instead of frozen or non-writable props\n // because that won't throw in a non-strict mode function.\n throw Error();\n }\n });\n\n if (typeof Reflect === 'object' && Reflect.construct) {\n // We construct a different control for this case to include any extra\n // frames added by the construct call.\n try {\n Reflect.construct(Fake, []);\n } catch (x) {\n control = x;\n }\n\n Reflect.construct(fn, [], Fake);\n } else {\n try {\n Fake.call();\n } catch (x) {\n control = x;\n }\n\n fn.call(Fake.prototype);\n }\n } else {\n try {\n throw Error();\n } catch (x) {\n control = x;\n }\n\n fn();\n }\n } catch (sample) {\n // This is inlined manually because closure doesn't do it for us.\n if (sample && control && typeof sample.stack === 'string') {\n // This extracts the first frame from the sample that isn't also in the control.\n // Skipping one frame that we assume is the frame that calls the two.\n var sampleLines = sample.stack.split('\\n');\n var controlLines = control.stack.split('\\n');\n var s = sampleLines.length - 1;\n var c = controlLines.length - 1;\n\n while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {\n // We expect at least one stack frame to be shared.\n // Typically this will be the root most one. However, stack frames may be\n // cut off due to maximum stack limits. In this case, one maybe cut off\n // earlier than the other. We assume that the sample is longer or the same\n // and there for cut off earlier. So we should find the root most frame in\n // the sample somewhere in the control.\n c--;\n }\n\n for (; s >= 1 && c >= 0; s--, c--) {\n // Next we find the first one that isn't the same which should be the\n // frame that called our sample function and the control.\n if (sampleLines[s] !== controlLines[c]) {\n // In V8, the first line is describing the message but other VMs don't.\n // If we're about to return the first line, and the control is also on the same\n // line, that's a pretty good indicator that our sample threw at same line as\n // the control. I.e. before we entered the sample frame. So we ignore this result.\n // This can happen if you passed a class to function component, or non-function.\n if (s !== 1 || c !== 1) {\n do {\n s--;\n c--; // We may still have similar intermediate frames from the construct call.\n // The next one that isn't the same should be our match though.\n\n if (c < 0 || sampleLines[s] !== controlLines[c]) {\n // V8 adds a \"new\" prefix for native classes. Let's remove it to make it prettier.\n var _frame = '\\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled \"\"\n // but we have a user-provided \"displayName\"\n // splice it in to make the stack more readable.\n\n\n if (fn.displayName && _frame.includes('')) {\n _frame = _frame.replace('', fn.displayName);\n }\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, _frame);\n }\n } // Return the line we found.\n\n\n return _frame;\n }\n } while (s >= 1 && c >= 0);\n }\n\n break;\n }\n }\n }\n } finally {\n reentry = false;\n\n {\n ReactCurrentDispatcher.current = previousDispatcher;\n reenableLogs();\n }\n\n Error.prepareStackTrace = previousPrepareStackTrace;\n } // Fallback to just using the name if we couldn't make it throw.\n\n\n var name = fn ? fn.displayName || fn.name : '';\n var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';\n\n {\n if (typeof fn === 'function') {\n componentFrameCache.set(fn, syntheticFrame);\n }\n }\n\n return syntheticFrame;\n}\nfunction describeFunctionComponentFrame(fn, source, ownerFn) {\n {\n return describeNativeComponentFrame(fn, false);\n }\n}\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {\n\n if (type == null) {\n return '';\n }\n\n if (typeof type === 'function') {\n {\n return describeNativeComponentFrame(type, shouldConstruct(type));\n }\n }\n\n if (typeof type === 'string') {\n return describeBuiltInComponentFrame(type);\n }\n\n switch (type) {\n case REACT_SUSPENSE_TYPE:\n return describeBuiltInComponentFrame('Suspense');\n\n case REACT_SUSPENSE_LIST_TYPE:\n return describeBuiltInComponentFrame('SuspenseList');\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_FORWARD_REF_TYPE:\n return describeFunctionComponentFrame(type.render);\n\n case REACT_MEMO_TYPE:\n // Memo may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);\n\n case REACT_LAZY_TYPE:\n {\n var lazyComponent = type;\n var payload = lazyComponent._payload;\n var init = lazyComponent._init;\n\n try {\n // Lazy may contain any component type so we recursively resolve it.\n return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);\n } catch (x) {}\n }\n }\n }\n\n return '';\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar loggedTypeFailures = {};\nvar ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame.setExtraStackFrame(null);\n }\n }\n}\n\nfunction checkPropTypes(typeSpecs, values, location, componentName, element) {\n {\n // $FlowFixMe This is okay but Flow doesn't know it.\n var has = Function.call.bind(hasOwnProperty);\n\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n // eslint-disable-next-line react-internal/prod-error-codes\n var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');\n err.name = 'Invariant Violation';\n throw err;\n }\n\n error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');\n } catch (ex) {\n error$1 = ex;\n }\n\n if (error$1 && !(error$1 instanceof Error)) {\n setCurrentlyValidatingElement(element);\n\n error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);\n\n setCurrentlyValidatingElement(null);\n }\n\n if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error$1.message] = true;\n setCurrentlyValidatingElement(element);\n\n error('Failed %s type: %s', location, error$1.message);\n\n setCurrentlyValidatingElement(null);\n }\n }\n }\n }\n}\n\nvar isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare\n\nfunction isArray(a) {\n return isArrayImpl(a);\n}\n\n/*\n * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol\n * and Temporal.* types. See https://github.com/facebook/react/pull/22064.\n *\n * The functions in this module will throw an easier-to-understand,\n * easier-to-debug exception with a clear errors message message explaining the\n * problem. (Instead of a confusing exception thrown inside the implementation\n * of the `value` object).\n */\n// $FlowFixMe only called in DEV, so void return is not possible.\nfunction typeName(value) {\n {\n // toStringTag is needed for namespaced types like Temporal.Instant\n var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;\n var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';\n return type;\n }\n} // $FlowFixMe only called in DEV, so void return is not possible.\n\n\nfunction willCoercionThrow(value) {\n {\n try {\n testStringCoercion(value);\n return false;\n } catch (e) {\n return true;\n }\n }\n}\n\nfunction testStringCoercion(value) {\n // If you ended up here by following an exception call stack, here's what's\n // happened: you supplied an object or symbol value to React (as a prop, key,\n // DOM attribute, CSS property, string ref, etc.) and when React tried to\n // coerce it to a string using `'' + value`, an exception was thrown.\n //\n // The most common types that will cause this exception are `Symbol` instances\n // and Temporal objects like `Temporal.Instant`. But any object that has a\n // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this\n // exception. (Library authors do this to prevent users from using built-in\n // numeric operators like `+` or comparison operators like `>=` because custom\n // methods are needed to perform accurate arithmetic or comparison.)\n //\n // To fix the problem, coerce this object or symbol value to a string before\n // passing it to React. The most reliable way is usually `String(value)`.\n //\n // To find which value is throwing, check the browser or debugger console.\n // Before this exception was thrown, there should be `console.error` output\n // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the\n // problem and how that type was used: key, atrribute, input value prop, etc.\n // In most cases, this console output also shows the component and its\n // ancestor components where the exception happened.\n //\n // eslint-disable-next-line react-internal/safe-string-coercion\n return '' + value;\n}\nfunction checkKeyStringCoercion(value) {\n {\n if (willCoercionThrow(value)) {\n error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));\n\n return testStringCoercion(value); // throw (to help callers find troubleshooting comments)\n }\n }\n}\n\nvar ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\nvar specialPropKeyWarningShown;\nvar specialPropRefWarningShown;\nvar didWarnAboutStringRefs;\n\n{\n didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.key !== undefined;\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config, self) {\n {\n if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {\n var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);\n\n if (!didWarnAboutStringRefs[componentName]) {\n error('Component \"%s\" contains the string ref \"%s\". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingKey = function () {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n\n error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n }\n };\n\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n }\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n {\n var warnAboutAccessingRef = function () {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n\n error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);\n }\n };\n\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allows us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n }); // self and source are DEV only properties.\n\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n }); // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n/**\n * https://github.com/reactjs/rfcs/pull/107\n * @param {*} type\n * @param {object} props\n * @param {string} key\n */\n\nfunction jsxDEV(type, config, maybeKey, source, self) {\n {\n var propName; // Reserved names are extracted\n\n var props = {};\n var key = null;\n var ref = null; // Currently, key can be spread in as a prop. This causes a potential\n // issue if key is also explicitly declared (ie.
\n // or
). We want to deprecate key spread,\n // but as an intermediary step, we will use jsxDEV for everything except\n //
, because we aren't currently able to tell if\n // key is explicitly declared to be undefined or not.\n\n if (maybeKey !== undefined) {\n {\n checkKeyStringCoercion(maybeKey);\n }\n\n key = '' + maybeKey;\n }\n\n if (hasValidKey(config)) {\n {\n checkKeyStringCoercion(config.key);\n }\n\n key = '' + config.key;\n }\n\n if (hasValidRef(config)) {\n ref = config.ref;\n warnIfStringRefCannotBeAutoConverted(config, self);\n } // Remaining properties are added to a new props object\n\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n } // Resolve default props\n\n\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n\n if (key || ref) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n }\n}\n\nvar ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction setCurrentlyValidatingElement$1(element) {\n {\n if (element) {\n var owner = element._owner;\n var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);\n ReactDebugCurrentFrame$1.setExtraStackFrame(stack);\n } else {\n ReactDebugCurrentFrame$1.setExtraStackFrame(null);\n }\n }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n propTypesMisspellWarningShown = false;\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\n\nfunction isValidElement(object) {\n {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n }\n}\n\nfunction getDeclarationErrorAddendum() {\n {\n if (ReactCurrentOwner$1.current) {\n var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);\n\n if (name) {\n return '\\n\\nCheck the render method of `' + name + '`.';\n }\n }\n\n return '';\n }\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n {\n if (source !== undefined) {\n var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n var lineNumber = source.lineNumber;\n return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n }\n\n return '';\n }\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n {\n var info = getDeclarationErrorAddendum();\n\n if (!info) {\n var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n if (parentName) {\n info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n }\n }\n\n return info;\n }\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n {\n if (!element._store || element._store.validated || element.key != null) {\n return;\n }\n\n element._store.validated = true;\n var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n // property, it may be the creator of the child that's responsible for\n // assigning it a key.\n\n var childOwner = '';\n\n if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {\n // Give the component that originally created this child.\n childOwner = \" It was passed a child from \" + getComponentNameFromType(element._owner.type) + \".\";\n }\n\n setCurrentlyValidatingElement$1(element);\n\n error('Each child in a list should have a unique \"key\" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);\n\n setCurrentlyValidatingElement$1(null);\n }\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n {\n if (typeof node !== 'object') {\n return;\n }\n\n if (isArray(node)) {\n for (var i = 0; i < node.length; i++) {\n var child = node[i];\n\n if (isValidElement(child)) {\n validateExplicitKey(child, parentType);\n }\n }\n } else if (isValidElement(node)) {\n // This element was passed in a valid location.\n if (node._store) {\n node._store.validated = true;\n }\n } else if (node) {\n var iteratorFn = getIteratorFn(node);\n\n if (typeof iteratorFn === 'function') {\n // Entry iterators used to provide implicit keys,\n // but now we print a separate warning for them later.\n if (iteratorFn !== node.entries) {\n var iterator = iteratorFn.call(node);\n var step;\n\n while (!(step = iterator.next()).done) {\n if (isValidElement(step.value)) {\n validateExplicitKey(step.value, parentType);\n }\n }\n }\n }\n }\n }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n {\n var type = element.type;\n\n if (type === null || type === undefined || typeof type === 'string') {\n return;\n }\n\n var propTypes;\n\n if (typeof type === 'function') {\n propTypes = type.propTypes;\n } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n // Inner props are checked in the reconciler.\n type.$$typeof === REACT_MEMO_TYPE)) {\n propTypes = type.propTypes;\n } else {\n return;\n }\n\n if (propTypes) {\n // Intentionally inside to avoid triggering lazy initializers:\n var name = getComponentNameFromType(type);\n checkPropTypes(propTypes, element.props, 'prop', name, element);\n } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:\n\n var _name = getComponentNameFromType(type);\n\n error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');\n }\n\n if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n }\n }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n {\n var keys = Object.keys(fragment.props);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (key !== 'children' && key !== 'key') {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n setCurrentlyValidatingElement$1(null);\n break;\n }\n }\n\n if (fragment.ref !== null) {\n setCurrentlyValidatingElement$1(fragment);\n\n error('Invalid attribute `ref` supplied to `React.Fragment`.');\n\n setCurrentlyValidatingElement$1(null);\n }\n }\n}\n\nvar didWarnAboutKeySpread = {};\nfunction jsxWithValidation(type, props, key, isStaticChildren, source, self) {\n {\n var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n // succeed and there will likely be errors in render.\n\n if (!validType) {\n var info = '';\n\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and named imports.\";\n }\n\n var sourceInfo = getSourceInfoErrorAddendum(source);\n\n if (sourceInfo) {\n info += sourceInfo;\n } else {\n info += getDeclarationErrorAddendum();\n }\n\n var typeString;\n\n if (type === null) {\n typeString = 'null';\n } else if (isArray(type)) {\n typeString = 'array';\n } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n typeString = \"<\" + (getComponentNameFromType(type.type) || 'Unknown') + \" />\";\n info = ' Did you accidentally export a JSX literal instead of a component?';\n } else {\n typeString = typeof type;\n }\n\n error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n }\n\n var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.\n // TODO: Drop this when these are no longer allowed as the type argument.\n\n if (element == null) {\n return element;\n } // Skip key warning if the type isn't valid since our key validation logic\n // doesn't expect a non-string/function type and can throw confusing errors.\n // We don't want exception behavior to differ between dev and prod.\n // (Rendering will throw with a helpful message and as soon as the type is\n // fixed, the key warnings will appear.)\n\n\n if (validType) {\n var children = props.children;\n\n if (children !== undefined) {\n if (isStaticChildren) {\n if (isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n validateChildKeys(children[i], type);\n }\n\n if (Object.freeze) {\n Object.freeze(children);\n }\n } else {\n error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');\n }\n } else {\n validateChildKeys(children, type);\n }\n }\n }\n\n {\n if (hasOwnProperty.call(props, 'key')) {\n var componentName = getComponentNameFromType(type);\n var keys = Object.keys(props).filter(function (k) {\n return k !== 'key';\n });\n var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';\n\n if (!didWarnAboutKeySpread[componentName + beforeExample]) {\n var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';\n\n error('A props object containing a \"key\" prop is being spread into JSX:\\n' + ' let props = %s;\\n' + ' <%s {...props} />\\n' + 'React keys must be passed directly to JSX without using spread:\\n' + ' let props = %s;\\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);\n\n didWarnAboutKeySpread[componentName + beforeExample] = true;\n }\n }\n }\n\n if (type === REACT_FRAGMENT_TYPE) {\n validateFragmentProps(element);\n } else {\n validatePropTypes(element);\n }\n\n return element;\n }\n} // These two functions exist to still get child warnings in dev\n// even with the prod transform. This means that jsxDEV is purely\n// opt-in behavior for better messages but that we won't stop\n// giving you warnings if you use production apis.\n\nfunction jsxWithValidationStatic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, true);\n }\n}\nfunction jsxWithValidationDynamic(type, props, key) {\n {\n return jsxWithValidation(type, props, key, false);\n }\n}\n\nvar jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.\n// for now we can ship identical prod functions\n\nvar jsxs = jsxWithValidationStatic ;\n\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsx;\nexports.jsxs = jsxs;\n })();\n}\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n", "// This loads all middlewares exposed on the middleware object and then starts\n// the invocation chain. The big idea is that we can add these to the middleware\n// export dynamically through wrangler, or we can potentially let users directly\n// add them as a sort of \"plugin\" system.\n\nimport ENTRY, { __INTERNAL_WRANGLER_MIDDLEWARE__ } from \"/Users/brettbeutell/fiber/hono-github-tracker/.wrangler/tmp/bundle-m4kIpi/middleware-insertion-facade.js\";\nimport { __facade_invoke__, __facade_register__, Dispatcher } from \"/Users/brettbeutell/fiber/hono-github-tracker/node_modules/.pnpm/wrangler@3.79.0_@cloudflare+workers-types@4.20240925.0/node_modules/wrangler/templates/middleware/common.ts\";\nimport type { WorkerEntrypointConstructor } from \"/Users/brettbeutell/fiber/hono-github-tracker/.wrangler/tmp/bundle-m4kIpi/middleware-insertion-facade.js\";\n\n// Preserve all the exports from the worker\nexport * from \"/Users/brettbeutell/fiber/hono-github-tracker/.wrangler/tmp/bundle-m4kIpi/middleware-insertion-facade.js\";\n\nclass __Facade_ScheduledController__ implements ScheduledController {\n\treadonly #noRetry: ScheduledController[\"noRetry\"];\n\n\tconstructor(\n\t\treadonly scheduledTime: number,\n\t\treadonly cron: string,\n\t\tnoRetry: ScheduledController[\"noRetry\"]\n\t) {\n\t\tthis.#noRetry = noRetry;\n\t}\n\n\tnoRetry() {\n\t\tif (!(this instanceof __Facade_ScheduledController__)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\t// Need to call native method immediately in case uncaught error thrown\n\t\tthis.#noRetry();\n\t}\n}\n\nfunction wrapExportedHandler(worker: ExportedHandler): ExportedHandler {\n\t// If we don't have any middleware defined, just return the handler as is\n\tif (\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__ === undefined ||\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__.length === 0\n\t) {\n\t\treturn worker;\n\t}\n\t// Otherwise, register all middleware once\n\tfor (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) {\n\t\t__facade_register__(middleware);\n\t}\n\n\tconst fetchDispatcher: ExportedHandlerFetchHandler = function (\n\t\trequest,\n\t\tenv,\n\t\tctx\n\t) {\n\t\tif (worker.fetch === undefined) {\n\t\t\tthrow new Error(\"Handler does not export a fetch() function.\");\n\t\t}\n\t\treturn worker.fetch(request, env, ctx);\n\t};\n\n\treturn {\n\t\t...worker,\n\t\tfetch(request, env, ctx) {\n\t\t\tconst dispatcher: Dispatcher = function (type, init) {\n\t\t\t\tif (type === \"scheduled\" && worker.scheduled !== undefined) {\n\t\t\t\t\tconst controller = new __Facade_ScheduledController__(\n\t\t\t\t\t\tDate.now(),\n\t\t\t\t\t\tinit.cron ?? \"\",\n\t\t\t\t\t\t() => {}\n\t\t\t\t\t);\n\t\t\t\t\treturn worker.scheduled(controller, env, ctx);\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn __facade_invoke__(request, env, ctx, dispatcher, fetchDispatcher);\n\t\t},\n\t};\n}\n\nfunction wrapWorkerEntrypoint(\n\tklass: WorkerEntrypointConstructor\n): WorkerEntrypointConstructor {\n\t// If we don't have any middleware defined, just return the handler as is\n\tif (\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__ === undefined ||\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__.length === 0\n\t) {\n\t\treturn klass;\n\t}\n\t// Otherwise, register all middleware once\n\tfor (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) {\n\t\t__facade_register__(middleware);\n\t}\n\n\t// `extend`ing `klass` here so other RPC methods remain callable\n\treturn class extends klass {\n\t\t#fetchDispatcher: ExportedHandlerFetchHandler> = (\n\t\t\trequest,\n\t\t\tenv,\n\t\t\tctx\n\t\t) => {\n\t\t\tthis.env = env;\n\t\t\tthis.ctx = ctx;\n\t\t\tif (super.fetch === undefined) {\n\t\t\t\tthrow new Error(\"Entrypoint class does not define a fetch() function.\");\n\t\t\t}\n\t\t\treturn super.fetch(request);\n\t\t};\n\n\t\t#dispatcher: Dispatcher = (type, init) => {\n\t\t\tif (type === \"scheduled\" && super.scheduled !== undefined) {\n\t\t\t\tconst controller = new __Facade_ScheduledController__(\n\t\t\t\t\tDate.now(),\n\t\t\t\t\tinit.cron ?? \"\",\n\t\t\t\t\t() => {}\n\t\t\t\t);\n\t\t\t\treturn super.scheduled(controller);\n\t\t\t}\n\t\t};\n\n\t\tfetch(request: Request) {\n\t\t\treturn __facade_invoke__(\n\t\t\t\trequest,\n\t\t\t\tthis.env,\n\t\t\t\tthis.ctx,\n\t\t\t\tthis.#dispatcher,\n\t\t\t\tthis.#fetchDispatcher\n\t\t\t);\n\t\t}\n\t};\n}\n\nlet WRAPPED_ENTRY: ExportedHandler | WorkerEntrypointConstructor | undefined;\nif (typeof ENTRY === \"object\") {\n\tWRAPPED_ENTRY = wrapExportedHandler(ENTRY);\n} else if (typeof ENTRY === \"function\") {\n\tWRAPPED_ENTRY = wrapWorkerEntrypoint(ENTRY);\n}\nexport default WRAPPED_ENTRY;\n", "\t\t\t\timport worker, * as OTHER_EXPORTS from \"/Users/brettbeutell/fiber/hono-github-tracker/src/index.ts\";\n\t\t\t\timport * as __MIDDLEWARE_0__ from \"/Users/brettbeutell/fiber/hono-github-tracker/node_modules/.pnpm/wrangler@3.79.0_@cloudflare+workers-types@4.20240925.0/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts\";\nimport * as __MIDDLEWARE_1__ from \"/Users/brettbeutell/fiber/hono-github-tracker/node_modules/.pnpm/wrangler@3.79.0_@cloudflare+workers-types@4.20240925.0/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts\";\n\n\t\t\t\texport * from \"/Users/brettbeutell/fiber/hono-github-tracker/src/index.ts\";\n\n\t\t\t\texport const __INTERNAL_WRANGLER_MIDDLEWARE__ = [\n\t\t\t\t\t\n\t\t\t\t\t__MIDDLEWARE_0__.default,__MIDDLEWARE_1__.default\n\t\t\t\t]\n\t\t\t\texport default worker;", "import { instrument } from \"@fiberplane/hono-otel\";\nimport { Hono } from \"hono\";\n\nimport api from \"./api\";\nimport { dbMiddleware } from \"./middleware\";\nimport type { HonoEnv } from \"./types\";\nimport web from \"./web\";\n\nconst app = new Hono();\n\napp.use(dbMiddleware);\n\napp.route(\"/\", web);\napp.route(\"/api\", api);\n\nexport default instrument(app);\n", "export { instrument } from \"./instrumentation\";\nexport { measure } from \"./measure\";\n", "import { SpanKind, context } from \"@opentelemetry/api\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\";\nimport { Resource } from \"@opentelemetry/resources\";\nimport {\n BasicTracerProvider,\n SimpleSpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { SEMRESATTRS_SERVICE_NAME } from \"@opentelemetry/semantic-conventions\";\nimport type { ExecutionContext } from \"hono\";\n// TODO figure out we can use something else\nimport { AsyncLocalStorageContextManager } from \"./async-hooks\";\nimport { measure } from \"./measure\";\nimport {\n patchCloudflareBindings,\n patchConsole,\n patchFetch,\n patchWaitUntil,\n} from \"./patch\";\nimport { propagateFpxTraceId } from \"./propagation\";\nimport { isRouteInspectorRequest, respondWithRoutes } from \"./routes\";\nimport type { HonoLikeApp, HonoLikeEnv, HonoLikeFetch } from \"./types\";\nimport {\n getRequestAttributes,\n getResponseAttributes,\n getRootRequestAttributes,\n} from \"./utils\";\n\n/**\n * The type for the configuration object we use to configure the instrumentation\n * Different from @FpxConfigOptions because all properties are required\n *\n * @internal\n */\ntype FpxConfig = {\n monitor: {\n /** Send data to FPX about each `fetch` call made during a handler's lifetime */\n fetch: boolean;\n /** Send data to FPX about each `console.*` call made during a handler's lifetime */\n logging: boolean;\n /** Proxy Cloudflare bindings to add instrumentation */\n cfBindings: boolean;\n };\n};\n\n/**\n * The type for the configuration object the user might pass to `instrument`\n * Different from @FpxConfig because all properties are optional\n *\n * @public\n */\ntype FpxConfigOptions = Partial<\n FpxConfig & {\n monitor: Partial;\n }\n>;\n\nconst defaultConfig = {\n // TODO - Implement library debug logging\n // libraryDebugMode: false,\n monitor: {\n fetch: true,\n logging: true,\n // NOTE - We don't proxy Cloudflare bindings by default yet because it's still experimental, and we don't have fancy UI for it yet in the Studio\n cfBindings: false,\n },\n};\n\nexport function instrument(app: HonoLikeApp, config?: FpxConfigOptions) {\n // Freeze the web standard fetch function so that we can use it below to report registered routes back to fpx studio\n const webStandardFetch = fetch;\n\n return new Proxy(app, {\n // Intercept the `fetch` function on the Hono app instance\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === \"fetch\" && typeof value === \"function\") {\n const originalFetch = value as HonoLikeFetch;\n return async function fetch(\n request: Request,\n // Name this \"rawEnv\" because we coerce it below into something that's easier to work with\n rawEnv: HonoLikeEnv,\n executionContext: ExecutionContext | undefined,\n ) {\n const env = rawEnv as\n | undefined\n | null\n | Record;\n\n // NOTE - We do *not* want to have a default for the FPX_ENDPOINT,\n // so that people won't accidentally deploy to production with our middleware and\n // start sending data to the default url.\n const endpoint =\n typeof env === \"object\" && env !== null ? env.FPX_ENDPOINT : null;\n const isEnabled = !!endpoint && typeof endpoint === \"string\";\n\n if (!isEnabled) {\n return await originalFetch(request, rawEnv, executionContext);\n }\n\n // If the request is from the route inspector, respond with the routes\n if (isRouteInspectorRequest(request)) {\n return respondWithRoutes(webStandardFetch, endpoint, app);\n }\n\n const serviceName = env?.FPX_SERVICE_NAME ?? \"unknown\";\n\n // Patch the related functions to monitor\n const {\n monitor: {\n fetch: monitorFetch,\n logging: monitorLogging,\n cfBindings: monitorCfBindings,\n },\n } = mergeConfigs(defaultConfig, config);\n if (monitorCfBindings) {\n patchCloudflareBindings(env);\n }\n if (monitorLogging) {\n patchConsole();\n }\n if (monitorFetch) {\n patchFetch();\n }\n\n const provider = setupTracerProvider({\n serviceName,\n endpoint,\n });\n\n // Enable tracing for waitUntil\n const patched = executionContext && patchWaitUntil(executionContext);\n const promises = patched?.promises ?? [];\n const proxyExecutionCtx = patched?.proxyContext ?? executionContext;\n\n const activeContext = propagateFpxTraceId(request);\n\n // HACK - Duplicate request to be able to read the body and other metadata\n // in the middleware without messing up the original request\n const clonedRequest = request.clone();\n const [body1, body2] = clonedRequest.body\n ? clonedRequest.body.tee()\n : [null, null];\n\n // In order to keep `onStart` synchronous (below), we construct\n // some necessary attributes here, using a cloned request\n const requestForAttributes = new Request(clonedRequest.url, {\n method: request.method,\n headers: new Headers(request.headers),\n body: body1,\n\n // NOTE - This is a workaround to support node environments\n // Which will throw errors when body is a stream but duplex is not set\n // https://github.com/nodejs/node/issues/46221\n duplex: body1 ? \"half\" : undefined,\n });\n\n // Replace the original request's body with the second stream\n const newRequest = new Request(clonedRequest, {\n body: body2,\n headers: new Headers(request.headers),\n method: request.method,\n // NOTE - This is a workaround to support node environments\n // Which will throw errors when body is a stream but duplex is not set\n // https://github.com/nodejs/node/issues/46221\n duplex: body2 ? \"half\" : undefined,\n });\n\n // Parse the body and headers for the root request.\n //\n // NOTE - This will add some latency, and it will serialize the env object.\n // We should not do this in production!\n const rootRequestAttributes = await getRootRequestAttributes(\n requestForAttributes,\n env,\n );\n\n const measuredFetch = measure(\n {\n name: \"request\",\n spanKind: SpanKind.SERVER,\n onStart: (span, [request]) => {\n const requestAttributes = {\n ...getRequestAttributes(request),\n ...rootRequestAttributes,\n };\n span.setAttributes(requestAttributes);\n },\n onSuccess: async (span, response) => {\n const attributes = await getResponseAttributes(\n (await response).clone(),\n );\n span.setAttributes(attributes);\n },\n checkResult: async (result) => {\n const r = await result;\n if (r.status >= 500) {\n throw new Error(r.statusText);\n }\n },\n },\n originalFetch,\n );\n\n try {\n return await context.with(activeContext, async () => {\n return await measuredFetch(\n newRequest,\n env as HonoLikeEnv,\n proxyExecutionCtx,\n );\n });\n } finally {\n // Make sure all promises are resolved before sending data to the server\n if (proxyExecutionCtx) {\n proxyExecutionCtx.waitUntil(\n Promise.allSettled(promises).finally(() => {\n return provider.forceFlush();\n }),\n );\n } else {\n // Otherwise just await flushing the provider\n await provider.forceFlush();\n }\n }\n };\n }\n\n // Keep all the other things accessible\n return value;\n },\n });\n}\n\nfunction setupTracerProvider(options: {\n serviceName: string;\n endpoint: string;\n}) {\n // We need to use async hooks to be able to propagate context\n const asyncHooksContextManager = new AsyncLocalStorageContextManager();\n asyncHooksContextManager.enable();\n context.setGlobalContextManager(asyncHooksContextManager);\n const provider = new BasicTracerProvider({\n resource: new Resource({\n [SEMRESATTRS_SERVICE_NAME]: options.serviceName,\n }),\n });\n\n const exporter = new OTLPTraceExporter({\n url: options.endpoint,\n });\n provider.addSpanProcessor(new SimpleSpanProcessor(exporter));\n provider.register();\n return provider;\n}\n\n/**\n * Last-in-wins deep merge for FpxConfig\n */\nfunction mergeConfigs(\n fallbackConfig: FpxConfig,\n userConfig?: FpxConfigOptions,\n): FpxConfig {\n return {\n monitor: Object.assign(fallbackConfig.monitor, userConfig?.monitor),\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport { getEnv, baggageUtils } from '@opentelemetry/core';\nimport {\n OTLPExporterConfigBase,\n appendResourcePathToUrl,\n appendRootPathToUrlIfNeeded,\n OTLPExporterBrowserBase,\n} from '@opentelemetry/otlp-exporter-base';\nimport {\n IExportTraceServiceResponse,\n JsonTraceSerializer,\n} from '@opentelemetry/otlp-transformer';\n\nconst DEFAULT_COLLECTOR_RESOURCE_PATH = 'v1/traces';\nconst DEFAULT_COLLECTOR_URL = `http://localhost:4318/${DEFAULT_COLLECTOR_RESOURCE_PATH}`;\n\n/**\n * Collector Trace Exporter for Web\n */\nexport class OTLPTraceExporter\n extends OTLPExporterBrowserBase\n implements SpanExporter\n{\n constructor(config: OTLPExporterConfigBase = {}) {\n super(config, JsonTraceSerializer, 'application/json');\n this._headers = Object.assign(\n this._headers,\n baggageUtils.parseKeyPairsIntoRecord(\n getEnv().OTEL_EXPORTER_OTLP_TRACES_HEADERS\n )\n );\n }\n\n getDefaultUrl(config: OTLPExporterConfigBase): string {\n return typeof config.url === 'string'\n ? config.url\n : getEnv().OTEL_EXPORTER_OTLP_TRACES_ENDPOINT.length > 0\n ? appendRootPathToUrlIfNeeded(getEnv().OTEL_EXPORTER_OTLP_TRACES_ENDPOINT)\n : getEnv().OTEL_EXPORTER_OTLP_ENDPOINT.length > 0\n ? appendResourcePathToUrl(\n getEnv().OTEL_EXPORTER_OTLP_ENDPOINT,\n DEFAULT_COLLECTOR_RESOURCE_PATH\n )\n : DEFAULT_COLLECTOR_URL;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './baggage/propagation/W3CBaggagePropagator';\nexport * from './common/anchored-clock';\nexport * from './common/attributes';\nexport * from './common/global-error-handler';\nexport * from './common/logging-error-handler';\nexport * from './common/time';\nexport * from './common/types';\nexport * from './common/hex-to-binary';\nexport * from './ExportResult';\nexport * as baggageUtils from './baggage/utils';\nexport * from './platform';\nexport * from './propagation/composite';\nexport * from './trace/W3CTraceContextPropagator';\nexport * from './trace/IdGenerator';\nexport * from './trace/rpc-metadata';\nexport * from './trace/sampler/AlwaysOffSampler';\nexport * from './trace/sampler/AlwaysOnSampler';\nexport * from './trace/sampler/ParentBasedSampler';\nexport * from './trace/sampler/TraceIdRatioBasedSampler';\nexport * from './trace/suppress-tracing';\nexport * from './trace/TraceState';\nexport * from './utils/environment';\nexport * from './utils/merge';\nexport * from './utils/sampling';\nexport * from './utils/timeout';\nexport * from './utils/url';\nexport * from './utils/wrap';\nexport * from './utils/callback';\nexport * from './version';\nimport { _export } from './internal/exporter';\nexport const internal = {\n _export,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Baggage,\n BaggageEntryMetadata,\n baggageEntryMetadataFromString,\n} from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n const valueProps = entry.split(BAGGAGE_PROPERTIES_SEPARATOR);\n if (valueProps.length <= 0) return;\n const keyPairPart = valueProps.shift();\n if (!keyPairPart) return;\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n const key = decodeURIComponent(\n keyPairPart.substring(0, separatorIndex).trim()\n );\n const value = decodeURIComponent(\n keyPairPart.substring(separatorIndex + 1).trim()\n );\n let metadata;\n if (valueProps.length > 0) {\n metadata = baggageEntryMetadataFromString(\n valueProps.join(BAGGAGE_PROPERTIES_SEPARATOR)\n );\n }\n return { key, value, metadata };\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record {\n if (typeof value !== 'string' || value.length === 0) return {};\n return value\n .split(BAGGAGE_ITEMS_SEPARATOR)\n .map(entry => {\n return parsePairKeyValue(entry);\n })\n .filter(keyPair => keyPair !== undefined && keyPair.value.length > 0)\n .reduce>((headers, keyPair) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers[keyPair!.key] = keyPair!.value;\n return headers;\n }, {});\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\nimport { TimeOriginLegacy } from './types';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\nexport function getTimeOrigin(): number {\n let timeOrigin = performance.timeOrigin;\n if (typeof timeOrigin !== 'number') {\n const perf: TimeOriginLegacy = performance as unknown as TimeOriginLegacy;\n timeOrigin = perf.timing && perf.timing.fetchStart;\n }\n return timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(getTimeOrigin());\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < getTimeOrigin()) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substr(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { getEnvWithoutDefaults, getEnv } from './environment';\nexport * from './globalThis';\nexport * from './hex-to-base64';\nexport * from './RandomIdGenerator';\nexport * from './performance';\nexport * from './sdk-info';\nexport * from './timer-util';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\nimport { _globalThis } from './globalThis';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required {\n const globalEnv = parseEnvironment(\n _globalThis as typeof globalThis & RAW_ENVIRONMENT\n );\n return Object.assign({}, DEFAULT_ENVIRONMENT, globalEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(_globalThis as typeof globalThis & RAW_ENVIRONMENT);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Updates to this file should also be replicated to @opentelemetry/api too.\n\n/**\n * - globalThis (New standard)\n * - self (Will return the current window instance for supported browsers)\n * - window (fallback for older browser implementations)\n * - global (NodeJS implementation)\n * - (When all else fails)\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef\nexport const _globalThis: typeof globalThis =\n typeof globalThis === 'object'\n ? globalThis\n : typeof self === 'object'\n ? self\n : typeof window === 'object'\n ? window\n : typeof global === 'object'\n ? global\n : ({} as typeof globalThis);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nfunction intValue(charCode: number): number {\n // 0-9\n if (charCode >= 48 && charCode <= 57) {\n return charCode - 48;\n }\n\n // a-f\n if (charCode >= 97 && charCode <= 102) {\n return charCode - 87;\n }\n\n // A-F\n return charCode - 55;\n}\n\nexport function hexToBinary(hexStr: string): Uint8Array {\n const buf = new Uint8Array(hexStr.length / 2);\n let offset = 0;\n\n for (let i = 0; i < hexStr.length; i += 2) {\n const hi = intValue(hexStr.charCodeAt(i));\n const lo = intValue(hexStr.charCodeAt(i + 1));\n buf[offset++] = (hi << 4) | lo;\n }\n\n return buf;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters): Promise {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred {\n private _promise: Promise;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport * from './platform';\nexport { OTLPExporterBase } from './OTLPExporterBase';\nexport {\n OTLPExporterError,\n OTLPExporterConfigBase,\n ExportServiceError,\n} from './types';\nexport {\n parseHeaders,\n appendResourcePathToUrl,\n appendRootPathToUrlIfNeeded,\n configureExporterTimeout,\n invalidTimeout,\n} from './util';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { OTLPExporterBrowserBase } from './OTLPExporterBrowserBase';\nexport { sendWithXhr } from './util';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { OTLPExporterBase } from '../../OTLPExporterBase';\nimport { OTLPExporterConfigBase } from '../../types';\nimport * as otlpTypes from '../../types';\nimport { parseHeaders } from '../../util';\nimport { sendWithBeacon, sendWithXhr } from './util';\nimport { diag } from '@opentelemetry/api';\nimport { getEnv, baggageUtils } from '@opentelemetry/core';\nimport { ISerializer } from '@opentelemetry/otlp-transformer';\n\n/**\n * Collector Metric Exporter abstract base class\n */\nexport abstract class OTLPExporterBrowserBase<\n ExportItem,\n ServiceResponse,\n> extends OTLPExporterBase {\n protected _headers: Record;\n private _useXHR: boolean = false;\n private _contentType: string;\n private _serializer: ISerializer;\n\n /**\n * @param config\n * @param serializer\n * @param contentType\n */\n constructor(\n config: OTLPExporterConfigBase = {},\n serializer: ISerializer,\n contentType: string\n ) {\n super(config);\n this._serializer = serializer;\n this._contentType = contentType;\n this._useXHR =\n !!config.headers || typeof navigator.sendBeacon !== 'function';\n if (this._useXHR) {\n this._headers = Object.assign(\n {},\n parseHeaders(config.headers),\n baggageUtils.parseKeyPairsIntoRecord(\n getEnv().OTEL_EXPORTER_OTLP_HEADERS\n )\n );\n } else {\n this._headers = {};\n }\n }\n\n onInit(): void {}\n\n onShutdown(): void {}\n\n send(\n items: ExportItem[],\n onSuccess: () => void,\n onError: (error: otlpTypes.OTLPExporterError) => void\n ): void {\n if (this._shutdownOnce.isCalled) {\n diag.debug('Shutdown already started. Cannot send objects');\n return;\n }\n const body = this._serializer.serializeRequest(items) ?? new Uint8Array();\n\n const promise = new Promise((resolve, reject) => {\n if (this._useXHR) {\n sendWithXhr(\n body,\n this.url,\n {\n ...this._headers,\n 'Content-Type': this._contentType,\n },\n this.timeoutMillis,\n resolve,\n reject\n );\n } else {\n sendWithBeacon(\n body,\n this.url,\n { type: this._contentType },\n resolve,\n reject\n );\n }\n }).then(onSuccess, onError);\n\n this._sendingPromises.push(promise);\n const popPromise = () => {\n const index = this._sendingPromises.indexOf(promise);\n this._sendingPromises.splice(index, 1);\n };\n promise.then(popPromise, popPromise);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\nimport {\n ExportResult,\n ExportResultCode,\n BindOnceFuture,\n} from '@opentelemetry/core';\nimport {\n OTLPExporterError,\n OTLPExporterConfigBase,\n ExportServiceError,\n} from './types';\nimport { configureExporterTimeout } from './util';\n\n/**\n * Collector Exporter abstract base class\n */\nexport abstract class OTLPExporterBase<\n T extends OTLPExporterConfigBase,\n ExportItem,\n> {\n public readonly url: string;\n public readonly hostname: string | undefined;\n public readonly timeoutMillis: number;\n protected _concurrencyLimit: number;\n protected _sendingPromises: Promise[] = [];\n protected _shutdownOnce: BindOnceFuture;\n\n /**\n * @param config\n */\n constructor(config: T = {} as T) {\n this.url = this.getDefaultUrl(config);\n if (typeof config.hostname === 'string') {\n this.hostname = config.hostname;\n }\n\n this.shutdown = this.shutdown.bind(this);\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n this._concurrencyLimit =\n typeof config.concurrencyLimit === 'number'\n ? config.concurrencyLimit\n : 30;\n\n this.timeoutMillis = configureExporterTimeout(config.timeoutMillis);\n\n // platform dependent\n this.onInit(config);\n }\n\n /**\n * Export items.\n * @param items\n * @param resultCallback\n */\n export(\n items: ExportItem[],\n resultCallback: (result: ExportResult) => void\n ): void {\n if (this._shutdownOnce.isCalled) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Exporter has been shutdown'),\n });\n return;\n }\n\n if (this._sendingPromises.length >= this._concurrencyLimit) {\n resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Concurrent export limit reached'),\n });\n return;\n }\n\n this._export(items)\n .then(() => {\n resultCallback({ code: ExportResultCode.SUCCESS });\n })\n .catch((error: ExportServiceError) => {\n resultCallback({ code: ExportResultCode.FAILED, error });\n });\n }\n\n private _export(items: ExportItem[]): Promise {\n return new Promise((resolve, reject) => {\n try {\n diag.debug('items to be sent', items);\n this.send(items, resolve, reject);\n } catch (e) {\n reject(e);\n }\n });\n }\n\n /**\n * Shutdown the exporter.\n */\n shutdown(): Promise {\n return this._shutdownOnce.call();\n }\n\n /**\n * Exports any pending spans in the exporter\n */\n forceFlush(): Promise {\n return Promise.all(this._sendingPromises).then(() => {\n /** ignore resolved values */\n });\n }\n\n /**\n * Called by _shutdownOnce with BindOnceFuture\n */\n private _shutdown(): Promise {\n diag.debug('shutdown started');\n this.onShutdown();\n return this.forceFlush();\n }\n\n abstract onShutdown(): void;\n abstract onInit(config: T): void;\n abstract send(\n items: ExportItem[],\n onSuccess: () => void,\n onError: (error: OTLPExporterError) => void\n ): void;\n abstract getDefaultUrl(config: T): string;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getEnv } from '@opentelemetry/core';\n\nconst DEFAULT_TRACE_TIMEOUT = 10000;\nexport const DEFAULT_EXPORT_MAX_ATTEMPTS = 5;\nexport const DEFAULT_EXPORT_INITIAL_BACKOFF = 1000;\nexport const DEFAULT_EXPORT_MAX_BACKOFF = 5000;\nexport const DEFAULT_EXPORT_BACKOFF_MULTIPLIER = 1.5;\n\n/**\n * Parses headers from config leaving only those that have defined values\n * @param partialHeaders\n */\nexport function parseHeaders(\n partialHeaders: Partial> = {}\n): Record {\n const headers: Record = {};\n Object.entries(partialHeaders).forEach(([key, value]) => {\n if (typeof value !== 'undefined') {\n headers[key] = String(value);\n } else {\n diag.warn(\n `Header \"${key}\" has invalid value (${value}) and will be ignored`\n );\n }\n });\n return headers;\n}\n\n/**\n * Adds path (version + signal) to a no per-signal endpoint\n * @param url\n * @param path\n * @returns url + path\n */\nexport function appendResourcePathToUrl(url: string, path: string): string {\n if (!url.endsWith('/')) {\n url = url + '/';\n }\n return url + path;\n}\n\n/**\n * Adds root path to signal specific endpoint when endpoint contains no path part and no root path\n * @param url\n * @returns url\n */\nexport function appendRootPathToUrlIfNeeded(url: string): string {\n try {\n const parsedUrl = new URL(url);\n if (parsedUrl.pathname === '') {\n parsedUrl.pathname = parsedUrl.pathname + '/';\n }\n return parsedUrl.toString();\n } catch {\n diag.warn(`Could not parse export URL: '${url}'`);\n return url;\n }\n}\n\n/**\n * Configure exporter trace timeout value from passed in value or environment variables\n * @param timeoutMillis\n * @returns timeout value in milliseconds\n */\nexport function configureExporterTimeout(\n timeoutMillis: number | undefined\n): number {\n if (typeof timeoutMillis === 'number') {\n if (timeoutMillis <= 0) {\n // OTLP exporter configured timeout - using default value of 10000ms\n return invalidTimeout(timeoutMillis, DEFAULT_TRACE_TIMEOUT);\n }\n return timeoutMillis;\n } else {\n return getExporterTimeoutFromEnv();\n }\n}\n\nfunction getExporterTimeoutFromEnv(): number {\n const definedTimeout = Number(\n getEnv().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT ??\n getEnv().OTEL_EXPORTER_OTLP_TIMEOUT\n );\n\n if (definedTimeout <= 0) {\n // OTLP exporter configured timeout - using default value of 10000ms\n return invalidTimeout(definedTimeout, DEFAULT_TRACE_TIMEOUT);\n } else {\n return definedTimeout;\n }\n}\n\n// OTLP exporter configured timeout - using default value of 10000ms\nexport function invalidTimeout(\n timeout: number,\n defaultTimeout: number\n): number {\n diag.warn('Timeout must be greater than 0', timeout);\n\n return defaultTimeout;\n}\n\nexport function isExportRetryable(statusCode: number): boolean {\n const retryCodes = [429, 502, 503, 504];\n\n return retryCodes.includes(statusCode);\n}\n\nexport function parseRetryAfterToMills(retryAfter?: string | null): number {\n if (retryAfter == null) {\n return -1;\n }\n const seconds = Number.parseInt(retryAfter, 10);\n if (Number.isInteger(seconds)) {\n return seconds > 0 ? seconds * 1000 : -1;\n }\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives\n const delay = new Date(retryAfter).getTime() - Date.now();\n\n if (delay >= 0) {\n return delay;\n }\n return 0;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { diag } from '@opentelemetry/api';\nimport { OTLPExporterError } from '../../types';\nimport {\n DEFAULT_EXPORT_MAX_ATTEMPTS,\n DEFAULT_EXPORT_INITIAL_BACKOFF,\n DEFAULT_EXPORT_BACKOFF_MULTIPLIER,\n DEFAULT_EXPORT_MAX_BACKOFF,\n isExportRetryable,\n parseRetryAfterToMills,\n} from '../../util';\n\n/**\n * Send metrics/spans using browser navigator.sendBeacon\n * @param body\n * @param url\n * @param blobPropertyBag\n * @param onSuccess\n * @param onError\n */\nexport function sendWithBeacon(\n body: Uint8Array,\n url: string,\n blobPropertyBag: BlobPropertyBag,\n onSuccess: () => void,\n onError: (error: OTLPExporterError) => void\n): void {\n if (navigator.sendBeacon(url, new Blob([body], blobPropertyBag))) {\n diag.debug('sendBeacon - can send', body);\n onSuccess();\n } else {\n const error = new OTLPExporterError(`sendBeacon - cannot send ${body}`);\n onError(error);\n }\n}\n\n/**\n * function to send metrics/spans using browser XMLHttpRequest\n * used when navigator.sendBeacon is not available\n * @param body\n * @param url\n * @param headers\n * @param onSuccess\n * @param onError\n */\nexport function sendWithXhr(\n body: Uint8Array,\n url: string,\n headers: Record,\n exporterTimeout: number,\n onSuccess: () => void,\n onError: (error: OTLPExporterError) => void\n): void {\n let retryTimer: ReturnType;\n let xhr: XMLHttpRequest;\n let reqIsDestroyed = false;\n\n const exporterTimer = setTimeout(() => {\n clearTimeout(retryTimer);\n reqIsDestroyed = true;\n\n if (xhr.readyState === XMLHttpRequest.DONE) {\n const err = new OTLPExporterError('Request Timeout');\n onError(err);\n } else {\n xhr.abort();\n }\n }, exporterTimeout);\n\n const sendWithRetry = (\n retries = DEFAULT_EXPORT_MAX_ATTEMPTS,\n minDelay = DEFAULT_EXPORT_INITIAL_BACKOFF\n ) => {\n xhr = new XMLHttpRequest();\n xhr.open('POST', url);\n\n const defaultHeaders = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n };\n\n Object.entries({\n ...defaultHeaders,\n ...headers,\n }).forEach(([k, v]) => {\n xhr.setRequestHeader(k, v);\n });\n\n xhr.send(body);\n\n xhr.onreadystatechange = () => {\n if (xhr.readyState === XMLHttpRequest.DONE && reqIsDestroyed === false) {\n if (xhr.status >= 200 && xhr.status <= 299) {\n diag.debug('xhr success', body);\n onSuccess();\n clearTimeout(exporterTimer);\n clearTimeout(retryTimer);\n } else if (xhr.status && isExportRetryable(xhr.status) && retries > 0) {\n let retryTime: number;\n minDelay = DEFAULT_EXPORT_BACKOFF_MULTIPLIER * minDelay;\n\n // retry after interval specified in Retry-After header\n if (xhr.getResponseHeader('Retry-After')) {\n retryTime = parseRetryAfterToMills(\n xhr.getResponseHeader('Retry-After')!\n );\n } else {\n // exponential backoff with jitter\n retryTime = Math.round(\n Math.random() * (DEFAULT_EXPORT_MAX_BACKOFF - minDelay) + minDelay\n );\n }\n\n retryTimer = setTimeout(() => {\n sendWithRetry(retries - 1, minDelay);\n }, retryTime);\n } else {\n const error = new OTLPExporterError(\n `Failed to export with XHR (status: ${xhr.status})`,\n xhr.status\n );\n onError(error);\n clearTimeout(exporterTimer);\n clearTimeout(retryTimer);\n }\n }\n };\n\n xhr.onabort = () => {\n if (reqIsDestroyed) {\n const err = new OTLPExporterError('Request Timeout');\n onError(err);\n }\n clearTimeout(exporterTimer);\n clearTimeout(retryTimer);\n };\n\n xhr.onerror = () => {\n if (reqIsDestroyed) {\n const err = new OTLPExporterError('Request Timeout');\n onError(err);\n }\n clearTimeout(exporterTimer);\n clearTimeout(retryTimer);\n };\n };\n\n sendWithRetry();\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for handling error\n */\nexport class OTLPExporterError extends Error {\n readonly code?: number;\n override readonly name: string = 'OTLPExporterError';\n readonly data?: string;\n\n constructor(message?: string, code?: number, data?: string) {\n super(message);\n this.data = data;\n this.code = code;\n }\n}\n\n/**\n * Interface for handling export service errors\n */\nexport interface ExportServiceError {\n name: string;\n code: number;\n details: string;\n metadata: { [key: string]: unknown };\n message: string;\n stack: string;\n}\n\n/**\n * Collector Exporter base config\n */\nexport interface OTLPExporterConfigBase {\n headers?: Partial>;\n hostname?: string;\n url?: string;\n concurrencyLimit?: number;\n /** Maximum time the OTLP exporter will wait for each batch export.\n * The default value is 10000ms. */\n timeoutMillis?: number;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport {\n OtlpEncodingOptions,\n IKeyValueList,\n IKeyValue,\n IInstrumentationScope,\n IArrayValue,\n LongBits,\n IAnyValue,\n Fixed64,\n} from './common/types';\nexport {\n SpanContextEncodeFunction,\n toLongBits,\n OptionalSpanContextEncodeFunction,\n getOtlpEncoder,\n Encoder,\n HrTimeEncodeFunction,\n encodeAsLongBits,\n encodeAsString,\n hrTimeToNanos,\n} from './common';\nexport {\n IExportMetricsPartialSuccess,\n IValueAtQuantile,\n ISummaryDataPoint,\n ISummary,\n ISum,\n IScopeMetrics,\n IResourceMetrics,\n INumberDataPoint,\n IHistogramDataPoint,\n IHistogram,\n IExponentialHistogramDataPoint,\n IExponentialHistogram,\n IMetric,\n IGauge,\n IExemplar,\n EAggregationTemporality,\n IExportMetricsServiceRequest,\n IExportMetricsServiceResponse,\n IBuckets,\n} from './metrics/types';\nexport { IResource } from './resource/types';\nexport {\n IExportTracePartialSuccess,\n IStatus,\n EStatusCode,\n ILink,\n IEvent,\n IScopeSpans,\n ISpan,\n IResourceSpans,\n ESpanKind,\n IExportTraceServiceResponse,\n IExportTraceServiceRequest,\n} from './trace/types';\nexport {\n IExportLogsServiceResponse,\n IScopeLogs,\n IExportLogsServiceRequest,\n IResourceLogs,\n ILogRecord,\n IExportLogsPartialSuccess,\n ESeverityNumber,\n} from './logs/types';\n\nexport { createExportTraceServiceRequest } from './trace';\nexport { createExportMetricsServiceRequest } from './metrics';\nexport { createExportLogsServiceRequest } from './logs';\n\nexport {\n ProtobufLogsSerializer,\n ProtobufMetricsSerializer,\n ProtobufTraceSerializer,\n} from './protobuf/serializers';\n\nexport {\n JsonTraceSerializer,\n JsonLogsSerializer,\n JsonMetricsSerializer,\n} from './json/serializers';\n\nexport { ISerializer } from './common/i-serializer';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { OtlpEncodingOptions, Fixed64, LongBits } from './types';\nimport { HrTime } from '@opentelemetry/api';\nimport { hexToBinary, hrTimeToNanoseconds } from '@opentelemetry/core';\n\nexport function hrTimeToNanos(hrTime: HrTime): bigint {\n const NANOSECONDS = BigInt(1_000_000_000);\n return BigInt(hrTime[0]) * NANOSECONDS + BigInt(hrTime[1]);\n}\n\nexport function toLongBits(value: bigint): LongBits {\n const low = Number(BigInt.asUintN(32, value));\n const high = Number(BigInt.asUintN(32, value >> BigInt(32)));\n return { low, high };\n}\n\nexport function encodeAsLongBits(hrTime: HrTime): LongBits {\n const nanos = hrTimeToNanos(hrTime);\n return toLongBits(nanos);\n}\n\nexport function encodeAsString(hrTime: HrTime): string {\n const nanos = hrTimeToNanos(hrTime);\n return nanos.toString();\n}\n\nconst encodeTimestamp =\n typeof BigInt !== 'undefined' ? encodeAsString : hrTimeToNanoseconds;\n\nexport type HrTimeEncodeFunction = (hrTime: HrTime) => Fixed64;\nexport type SpanContextEncodeFunction = (\n spanContext: string\n) => string | Uint8Array;\nexport type OptionalSpanContextEncodeFunction = (\n spanContext: string | undefined\n) => string | Uint8Array | undefined;\n\nexport interface Encoder {\n encodeHrTime: HrTimeEncodeFunction;\n encodeSpanContext: SpanContextEncodeFunction;\n encodeOptionalSpanContext: OptionalSpanContextEncodeFunction;\n}\n\nfunction identity(value: T): T {\n return value;\n}\n\nfunction optionalHexToBinary(str: string | undefined): Uint8Array | undefined {\n if (str === undefined) return undefined;\n return hexToBinary(str);\n}\n\nconst DEFAULT_ENCODER: Encoder = {\n encodeHrTime: encodeAsLongBits,\n encodeSpanContext: hexToBinary,\n encodeOptionalSpanContext: optionalHexToBinary,\n};\n\nexport function getOtlpEncoder(options?: OtlpEncodingOptions): Encoder {\n if (options === undefined) {\n return DEFAULT_ENCODER;\n }\n\n const useLongBits = options.useLongBits ?? true;\n const useHex = options.useHex ?? false;\n return {\n encodeHrTime: useLongBits ? encodeAsLongBits : encodeTimestamp,\n encodeSpanContext: useHex ? identity : hexToBinary,\n encodeOptionalSpanContext: useHex ? identity : optionalHexToBinary,\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type { Link } from '@opentelemetry/api';\nimport type { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';\nimport type { Encoder } from '../common';\nimport { toAttributes } from '../common/internal';\nimport { EStatusCode, IEvent, ILink, ISpan } from './types';\n\nexport function sdkSpanToOtlpSpan(span: ReadableSpan, encoder: Encoder): ISpan {\n const ctx = span.spanContext();\n const status = span.status;\n return {\n traceId: encoder.encodeSpanContext(ctx.traceId),\n spanId: encoder.encodeSpanContext(ctx.spanId),\n parentSpanId: encoder.encodeOptionalSpanContext(span.parentSpanId),\n traceState: ctx.traceState?.serialize(),\n name: span.name,\n // Span kind is offset by 1 because the API does not define a value for unset\n kind: span.kind == null ? 0 : span.kind + 1,\n startTimeUnixNano: encoder.encodeHrTime(span.startTime),\n endTimeUnixNano: encoder.encodeHrTime(span.endTime),\n attributes: toAttributes(span.attributes),\n droppedAttributesCount: span.droppedAttributesCount,\n events: span.events.map(event => toOtlpSpanEvent(event, encoder)),\n droppedEventsCount: span.droppedEventsCount,\n status: {\n // API and proto enums share the same values\n code: status.code as unknown as EStatusCode,\n message: status.message,\n },\n links: span.links.map(link => toOtlpLink(link, encoder)),\n droppedLinksCount: span.droppedLinksCount,\n };\n}\n\nexport function toOtlpLink(link: Link, encoder: Encoder): ILink {\n return {\n attributes: link.attributes ? toAttributes(link.attributes) : [],\n spanId: encoder.encodeSpanContext(link.context.spanId),\n traceId: encoder.encodeSpanContext(link.context.traceId),\n traceState: link.context.traceState?.serialize(),\n droppedAttributesCount: link.droppedAttributesCount || 0,\n };\n}\n\nexport function toOtlpSpanEvent(\n timedEvent: TimedEvent,\n encoder: Encoder\n): IEvent {\n return {\n attributes: timedEvent.attributes\n ? toAttributes(timedEvent.attributes)\n : [],\n name: timedEvent.name,\n timeUnixNano: encoder.encodeHrTime(timedEvent.time),\n droppedAttributesCount: timedEvent.droppedAttributesCount || 0,\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type { IAnyValue, IInstrumentationScope, IKeyValue } from './types';\nimport { Attributes } from '@opentelemetry/api';\nimport { InstrumentationScope } from '@opentelemetry/core';\n\nexport function createInstrumentationScope(\n scope: InstrumentationScope\n): IInstrumentationScope {\n return {\n name: scope.name,\n version: scope.version,\n };\n}\n\nexport function toAttributes(attributes: Attributes): IKeyValue[] {\n return Object.keys(attributes).map(key => toKeyValue(key, attributes[key]));\n}\n\nexport function toKeyValue(key: string, value: unknown): IKeyValue {\n return {\n key: key,\n value: toAnyValue(value),\n };\n}\n\nexport function toAnyValue(value: unknown): IAnyValue {\n const t = typeof value;\n if (t === 'string') return { stringValue: value as string };\n if (t === 'number') {\n if (!Number.isInteger(value)) return { doubleValue: value as number };\n return { intValue: value as number };\n }\n if (t === 'boolean') return { boolValue: value as boolean };\n if (value instanceof Uint8Array) return { bytesValue: value };\n if (Array.isArray(value))\n return { arrayValue: { values: value.map(toAnyValue) } };\n if (t === 'object' && value != null)\n return {\n kvlistValue: {\n values: Object.entries(value as object).map(([k, v]) =>\n toKeyValue(k, v)\n ),\n },\n };\n\n return {};\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { IResource as ISdkResource } from '@opentelemetry/resources';\nimport { toAttributes } from '../common/internal';\nimport { IResource } from './types';\n\nexport function createResource(resource: ISdkResource): IResource {\n return {\n attributes: toAttributes(resource.attributes),\n droppedAttributesCount: 0,\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type { IResource } from '@opentelemetry/resources';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport type { OtlpEncodingOptions } from '../common/types';\nimport { sdkSpanToOtlpSpan } from './internal';\nimport {\n IExportTraceServiceRequest,\n IResourceSpans,\n IScopeSpans,\n} from './types';\nimport { Encoder, getOtlpEncoder } from '../common';\nimport { createInstrumentationScope } from '../common/internal';\nimport { createResource } from '../resource/internal';\n\nexport function createExportTraceServiceRequest(\n spans: ReadableSpan[],\n options?: OtlpEncodingOptions\n): IExportTraceServiceRequest {\n const encoder = getOtlpEncoder(options);\n return {\n resourceSpans: spanRecordsToResourceSpans(spans, encoder),\n };\n}\n\nfunction createResourceMap(readableSpans: ReadableSpan[]) {\n const resourceMap: Map> = new Map();\n for (const record of readableSpans) {\n let ilmMap = resourceMap.get(record.resource);\n\n if (!ilmMap) {\n ilmMap = new Map();\n resourceMap.set(record.resource, ilmMap);\n }\n\n // TODO this is duplicated in basic tracer. Consolidate on a common helper in core\n const instrumentationLibraryKey = `${record.instrumentationLibrary.name}@${\n record.instrumentationLibrary.version || ''\n }:${record.instrumentationLibrary.schemaUrl || ''}`;\n let records = ilmMap.get(instrumentationLibraryKey);\n\n if (!records) {\n records = [];\n ilmMap.set(instrumentationLibraryKey, records);\n }\n\n records.push(record);\n }\n\n return resourceMap;\n}\n\nfunction spanRecordsToResourceSpans(\n readableSpans: ReadableSpan[],\n encoder: Encoder\n): IResourceSpans[] {\n const resourceMap = createResourceMap(readableSpans);\n const out: IResourceSpans[] = [];\n\n const entryIterator = resourceMap.entries();\n let entry = entryIterator.next();\n while (!entry.done) {\n const [resource, ilmMap] = entry.value;\n const scopeResourceSpans: IScopeSpans[] = [];\n const ilmIterator = ilmMap.values();\n let ilmEntry = ilmIterator.next();\n while (!ilmEntry.done) {\n const scopeSpans = ilmEntry.value;\n if (scopeSpans.length > 0) {\n const spans = scopeSpans.map(readableSpan =>\n sdkSpanToOtlpSpan(readableSpan, encoder)\n );\n\n scopeResourceSpans.push({\n scope: createInstrumentationScope(\n scopeSpans[0].instrumentationLibrary\n ),\n spans: spans,\n schemaUrl: scopeSpans[0].instrumentationLibrary.schemaUrl,\n });\n }\n ilmEntry = ilmIterator.next();\n }\n // TODO SDK types don't provide resource schema URL at this time\n const transformedSpans: IResourceSpans = {\n resource: createResource(resource),\n scopeSpans: scopeResourceSpans,\n schemaUrl: undefined,\n };\n\n out.push(transformedSpans);\n entry = entryIterator.next();\n }\n\n return out;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ISerializer } from '../common/i-serializer';\nimport { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { IExportTraceServiceResponse } from '../trace/types';\nimport { createExportTraceServiceRequest } from '../trace';\nimport { ResourceMetrics } from '@opentelemetry/sdk-metrics';\nimport { createExportMetricsServiceRequest } from '../metrics';\nimport { ReadableLogRecord } from '@opentelemetry/sdk-logs';\nimport { IExportMetricsServiceResponse } from '../metrics/types';\nimport { IExportLogsServiceResponse } from '../logs/types';\nimport { createExportLogsServiceRequest } from '../logs';\n\nexport const JsonTraceSerializer: ISerializer<\n ReadableSpan[],\n IExportTraceServiceResponse\n> = {\n serializeRequest: (arg: ReadableSpan[]) => {\n const request = createExportTraceServiceRequest(arg, {\n useHex: true,\n useLongBits: false,\n });\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportTraceServiceResponse;\n },\n};\n\nexport const JsonMetricsSerializer: ISerializer<\n ResourceMetrics[],\n IExportMetricsServiceResponse\n> = {\n serializeRequest: (arg: ResourceMetrics[]) => {\n const request = createExportMetricsServiceRequest(arg, {\n useLongBits: false,\n });\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportMetricsServiceResponse;\n },\n};\n\nexport const JsonLogsSerializer: ISerializer<\n ReadableLogRecord[],\n IExportLogsServiceResponse\n> = {\n serializeRequest: (arg: ReadableLogRecord[]) => {\n const request = createExportLogsServiceRequest(arg, {\n useHex: true,\n useLongBits: false,\n });\n const encoder = new TextEncoder();\n return encoder.encode(JSON.stringify(request));\n },\n deserializeResponse: (arg: Uint8Array) => {\n const decoder = new TextDecoder();\n return JSON.parse(decoder.decode(arg)) as IExportLogsServiceResponse;\n },\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { Resource } from './Resource';\nexport { IResource } from './IResource';\nexport { defaultServiceName } from './platform';\nexport { DetectorSync, ResourceAttributes, Detector } from './types';\nexport { ResourceDetectionConfig } from './config';\nexport {\n browserDetector,\n browserDetectorSync,\n envDetector,\n envDetectorSync,\n hostDetector,\n hostDetectorSync,\n osDetector,\n osDetectorSync,\n processDetector,\n processDetectorSync,\n serviceInstanceIdDetectorSync,\n} from './detectors';\nexport { detectResourcesSync, detectResources } from './detect-resources';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\nimport {\n SEMRESATTRS_SERVICE_NAME,\n SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,\n SEMRESATTRS_TELEMETRY_SDK_NAME,\n SEMRESATTRS_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\nimport { SDK_INFO } from '@opentelemetry/core';\nimport { ResourceAttributes } from './types';\nimport { defaultServiceName } from './platform';\nimport { IResource } from './IResource';\n\n/**\n * A Resource describes the entity for which a signals (metrics or trace) are\n * collected.\n */\nexport class Resource implements IResource {\n static readonly EMPTY = new Resource({});\n private _syncAttributes?: ResourceAttributes;\n private _asyncAttributesPromise?: Promise;\n private _attributes?: ResourceAttributes;\n\n /**\n * Check if async attributes have resolved. This is useful to avoid awaiting\n * waitForAsyncAttributes (which will introduce asynchronous behavior) when not necessary.\n *\n * @returns true if the resource \"attributes\" property is not yet settled to its final value\n */\n public asyncAttributesPending?: boolean;\n\n /**\n * Returns an empty Resource\n */\n static empty(): IResource {\n return Resource.EMPTY;\n }\n\n /**\n * Returns a Resource that identifies the SDK in use.\n */\n static default(): IResource {\n return new Resource({\n [SEMRESATTRS_SERVICE_NAME]: defaultServiceName(),\n [SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]:\n SDK_INFO[SEMRESATTRS_TELEMETRY_SDK_LANGUAGE],\n [SEMRESATTRS_TELEMETRY_SDK_NAME]:\n SDK_INFO[SEMRESATTRS_TELEMETRY_SDK_NAME],\n [SEMRESATTRS_TELEMETRY_SDK_VERSION]:\n SDK_INFO[SEMRESATTRS_TELEMETRY_SDK_VERSION],\n });\n }\n\n constructor(\n /**\n * A dictionary of attributes with string keys and values that provide\n * information about the entity as numbers, strings or booleans\n * TODO: Consider to add check/validation on attributes.\n */\n attributes: ResourceAttributes,\n asyncAttributesPromise?: Promise\n ) {\n this._attributes = attributes;\n this.asyncAttributesPending = asyncAttributesPromise != null;\n this._syncAttributes = this._attributes ?? {};\n this._asyncAttributesPromise = asyncAttributesPromise?.then(\n asyncAttributes => {\n this._attributes = Object.assign({}, this._attributes, asyncAttributes);\n this.asyncAttributesPending = false;\n return asyncAttributes;\n },\n err => {\n diag.debug(\"a resource's async attributes promise rejected: %s\", err);\n this.asyncAttributesPending = false;\n return {};\n }\n );\n }\n\n get attributes(): ResourceAttributes {\n if (this.asyncAttributesPending) {\n diag.error(\n 'Accessing resource attributes before async attributes settled'\n );\n }\n\n return this._attributes ?? {};\n }\n\n /**\n * Returns a promise that will never be rejected. Resolves when all async attributes have finished being added to\n * this Resource's attributes. This is useful in exporters to block until resource detection\n * has finished.\n */\n async waitForAsyncAttributes?(): Promise {\n if (this.asyncAttributesPending) {\n await this._asyncAttributesPromise;\n }\n }\n\n /**\n * Returns a new, merged {@link Resource} by merging the current Resource\n * with the other Resource. In case of a collision, other Resource takes\n * precedence.\n *\n * @param other the Resource that will be merged with this.\n * @returns the newly merged Resource.\n */\n merge(other: IResource | null): IResource {\n if (!other) return this;\n\n // SpanAttributes from other resource overwrite attributes from this resource.\n const mergedSyncAttributes = {\n ...this._syncAttributes,\n //Support for old resource implementation where _syncAttributes is not defined\n ...((other as Resource)._syncAttributes ?? other.attributes),\n };\n\n if (\n !this._asyncAttributesPromise &&\n !(other as Resource)._asyncAttributesPromise\n ) {\n return new Resource(mergedSyncAttributes);\n }\n\n const mergedAttributesPromise = Promise.all([\n this._asyncAttributesPromise,\n (other as Resource)._asyncAttributesPromise,\n ]).then(([thisAsyncAttributes, otherAsyncAttributes]) => {\n return {\n ...this._syncAttributes,\n ...thisAsyncAttributes,\n //Support for old resource implementation where _syncAttributes is not defined\n ...((other as Resource)._syncAttributes ?? other.attributes),\n ...otherAsyncAttributes,\n };\n });\n\n return new Resource(mergedSyncAttributes, mergedAttributesPromise);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { W3CBaggagePropagator } from './baggage/propagation/W3CBaggagePropagator';\nexport { AnchoredClock, Clock } from './common/anchored-clock';\nexport {\n isAttributeKey,\n isAttributeValue,\n sanitizeAttributes,\n} from './common/attributes';\nexport {\n globalErrorHandler,\n setGlobalErrorHandler,\n} from './common/global-error-handler';\nexport { loggingErrorHandler } from './common/logging-error-handler';\nexport {\n addHrTimes,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n hrTimeToMicroseconds,\n hrTimeToMilliseconds,\n hrTimeToNanoseconds,\n hrTimeToTimeStamp,\n isTimeInput,\n isTimeInputHrTime,\n millisToHrTime,\n timeInputToHrTime,\n} from './common/time';\nexport {\n ErrorHandler,\n InstrumentationLibrary,\n InstrumentationScope,\n ShimWrapped,\n TimeOriginLegacy,\n} from './common/types';\nexport { hexToBinary } from './common/hex-to-binary';\nexport { ExportResult, ExportResultCode } from './ExportResult';\nimport {\n getKeyPairs,\n serializeKeyPairs,\n parseKeyPairsIntoRecord,\n parsePairKeyValue,\n} from './baggage/utils';\nexport const baggageUtils = {\n getKeyPairs,\n serializeKeyPairs,\n parseKeyPairsIntoRecord,\n parsePairKeyValue,\n};\nexport {\n RandomIdGenerator,\n SDK_INFO,\n _globalThis,\n getEnv,\n getEnvWithoutDefaults,\n hexToBase64,\n otperformance,\n unrefTimer,\n} from './platform';\nexport {\n CompositePropagator,\n CompositePropagatorConfig,\n} from './propagation/composite';\nexport {\n TRACE_PARENT_HEADER,\n TRACE_STATE_HEADER,\n W3CTraceContextPropagator,\n parseTraceParent,\n} from './trace/W3CTraceContextPropagator';\nexport { IdGenerator } from './trace/IdGenerator';\nexport {\n RPCMetadata,\n RPCType,\n deleteRPCMetadata,\n getRPCMetadata,\n setRPCMetadata,\n} from './trace/rpc-metadata';\nexport { AlwaysOffSampler } from './trace/sampler/AlwaysOffSampler';\nexport { AlwaysOnSampler } from './trace/sampler/AlwaysOnSampler';\nexport { ParentBasedSampler } from './trace/sampler/ParentBasedSampler';\nexport { TraceIdRatioBasedSampler } from './trace/sampler/TraceIdRatioBasedSampler';\nexport {\n isTracingSuppressed,\n suppressTracing,\n unsuppressTracing,\n} from './trace/suppress-tracing';\nexport { TraceState } from './trace/TraceState';\nexport {\n DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n DEFAULT_ENVIRONMENT,\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from './utils/environment';\nexport { merge } from './utils/merge';\nexport { TracesSamplerValues } from './utils/sampling';\nexport { TimeoutError, callWithTimeout } from './utils/timeout';\nexport { isUrlIgnored, urlMatches } from './utils/url';\nexport { isWrapped } from './utils/wrap';\nexport { BindOnceFuture } from './utils/callback';\nexport { VERSION } from './version';\nimport { _export } from './internal/exporter';\nexport const internal = {\n _export,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BaggageEntry,\n Context,\n propagation,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '@opentelemetry/api';\n\nimport { isTracingSuppressed } from '../../trace/suppress-tracing';\nimport {\n BAGGAGE_HEADER,\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_MAX_NAME_VALUE_PAIRS,\n BAGGAGE_MAX_PER_NAME_VALUE_PAIRS,\n} from '../constants';\nimport { getKeyPairs, parsePairKeyValue, serializeKeyPairs } from '../utils';\n\n/**\n * Propagates {@link Baggage} through Context format propagation.\n *\n * Based on the Baggage specification:\n * https://w3c.github.io/baggage/\n */\nexport class W3CBaggagePropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const baggage = propagation.getBaggage(context);\n if (!baggage || isTracingSuppressed(context)) return;\n const keyPairs = getKeyPairs(baggage)\n .filter((pair: string) => {\n return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;\n })\n .slice(0, BAGGAGE_MAX_NAME_VALUE_PAIRS);\n const headerValue = serializeKeyPairs(keyPairs);\n if (headerValue.length > 0) {\n setter.set(carrier, BAGGAGE_HEADER, headerValue);\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const headerValue = getter.get(carrier, BAGGAGE_HEADER);\n const baggageString = Array.isArray(headerValue)\n ? headerValue.join(BAGGAGE_ITEMS_SEPARATOR)\n : headerValue;\n if (!baggageString) return context;\n const baggage: Record = {};\n if (baggageString.length === 0) {\n return context;\n }\n const pairs = baggageString.split(BAGGAGE_ITEMS_SEPARATOR);\n pairs.forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n if (keyPair) {\n const baggageEntry: BaggageEntry = { value: keyPair.value };\n if (keyPair.metadata) {\n baggageEntry.metadata = keyPair.metadata;\n }\n baggage[keyPair.key] = baggageEntry;\n }\n });\n if (Object.entries(baggage).length === 0) {\n return context;\n }\n return propagation.setBaggage(context, propagation.createBaggage(baggage));\n }\n\n fields(): string[] {\n return [BAGGAGE_HEADER];\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Baggage,\n BaggageEntryMetadata,\n baggageEntryMetadataFromString,\n} from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n const valueProps = entry.split(BAGGAGE_PROPERTIES_SEPARATOR);\n if (valueProps.length <= 0) return;\n const keyPairPart = valueProps.shift();\n if (!keyPairPart) return;\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n const key = decodeURIComponent(\n keyPairPart.substring(0, separatorIndex).trim()\n );\n const value = decodeURIComponent(\n keyPairPart.substring(separatorIndex + 1).trim()\n );\n let metadata;\n if (valueProps.length > 0) {\n metadata = baggageEntryMetadataFromString(\n valueProps.join(BAGGAGE_PROPERTIES_SEPARATOR)\n );\n }\n return { key, value, metadata };\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record {\n if (typeof value !== 'string' || value.length === 0) return {};\n return value\n .split(BAGGAGE_ITEMS_SEPARATOR)\n .map(entry => {\n return parsePairKeyValue(entry);\n })\n .filter(keyPair => keyPair !== undefined && keyPair.value.length > 0)\n .reduce>((headers, keyPair) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers[keyPair!.key] = keyPair!.value;\n return headers;\n }, {});\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, SpanAttributeValue, SpanAttributes } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): SpanAttributes {\n const out: SpanAttributes = {};\n\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n\n for (const [key, val] of Object.entries(attributes)) {\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n } else {\n out[key] = val;\n }\n }\n\n return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n return typeof key === 'string' && key.length > 0;\n}\n\nexport function isAttributeValue(val: unknown): val is SpanAttributeValue {\n if (val == null) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n\n return isValidPrimitiveAttributeValue(val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n let type: string | undefined;\n\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null) continue;\n\n if (!type) {\n if (isValidPrimitiveAttributeValue(element)) {\n type = typeof element;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n\n if (typeof element === type) {\n continue;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction isValidPrimitiveAttributeValue(val: unknown): boolean {\n switch (typeof val) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n\n return false;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record {\n const result = {} as Record;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\nimport { TimeOriginLegacy } from './types';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\nexport function getTimeOrigin(): number {\n let timeOrigin = performance.timeOrigin;\n if (typeof timeOrigin !== 'number') {\n const perf: TimeOriginLegacy = performance as unknown as TimeOriginLegacy;\n timeOrigin = perf.timing && perf.timing.fetchStart;\n }\n return timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(getTimeOrigin());\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < getTimeOrigin()) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substr(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { getEnvWithoutDefaults, getEnv } from './environment';\nexport { _globalThis } from './globalThis';\nexport { hexToBase64 } from './hex-to-base64';\nexport { RandomIdGenerator } from './RandomIdGenerator';\nexport { otperformance } from './performance';\nexport { SDK_INFO } from './sdk-info';\nexport { unrefTimer } from './timer-util';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\nimport { _globalThis } from './globalThis';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required {\n const globalEnv = parseEnvironment(\n _globalThis as typeof globalThis & RAW_ENVIRONMENT\n );\n return Object.assign({}, DEFAULT_ENVIRONMENT, globalEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(_globalThis as typeof globalThis & RAW_ENVIRONMENT);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Updates to this file should also be replicated to @opentelemetry/api too.\n\n/**\n * - globalThis (New standard)\n * - self (Will return the current window instance for supported browsers)\n * - window (fallback for older browser implementations)\n * - global (NodeJS implementation)\n * - (When all else fails)\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef\nexport const _globalThis: typeof globalThis =\n typeof globalThis === 'object'\n ? globalThis\n : typeof self === 'object'\n ? self\n : typeof window === 'object'\n ? window\n : typeof global === 'object'\n ? global\n : ({} as typeof globalThis);\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const otperformance = performance;\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../../version';\nimport {\n SEMRESATTRS_TELEMETRY_SDK_NAME,\n SEMRESATTRS_PROCESS_RUNTIME_NAME,\n SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,\n TELEMETRYSDKLANGUAGEVALUES_WEBJS,\n SEMRESATTRS_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [SEMRESATTRS_TELEMETRY_SDK_NAME]: 'opentelemetry',\n [SEMRESATTRS_PROCESS_RUNTIME_NAME]: 'browser',\n [SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]: TELEMETRYSDKLANGUAGEVALUES_WEBJS,\n [SEMRESATTRS_TELEMETRY_SDK_VERSION]: VERSION,\n};\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.26.0';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(_timer: number): void {}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n TextMapGetter,\n TextMapPropagator,\n diag,\n TextMapSetter,\n} from '@opentelemetry/api';\n\n/** Configuration object for composite propagator */\nexport interface CompositePropagatorConfig {\n /**\n * List of propagators to run. Propagators run in the\n * list order. If a propagator later in the list writes the same context\n * key as a propagator earlier in the list, the later on will \"win\".\n */\n propagators?: TextMapPropagator[];\n}\n\n/** Combines multiple propagators into a single propagator. */\nexport class CompositePropagator implements TextMapPropagator {\n private readonly _propagators: TextMapPropagator[];\n private readonly _fields: string[];\n\n /**\n * Construct a composite propagator from a list of propagators.\n *\n * @param [config] Configuration object for composite propagator\n */\n constructor(config: CompositePropagatorConfig = {}) {\n this._propagators = config.propagators ?? [];\n\n this._fields = Array.from(\n new Set(\n this._propagators\n // older propagators may not have fields function, null check to be sure\n .map(p => (typeof p.fields === 'function' ? p.fields() : []))\n .reduce((x, y) => x.concat(y), [])\n )\n );\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same carrier key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to inject\n * @param carrier Carrier into which context will be injected\n */\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n for (const propagator of this._propagators) {\n try {\n propagator.inject(context, carrier, setter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n }\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same context key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to add values to\n * @param carrier Carrier from which to extract context\n */\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n return this._propagators.reduce((ctx, propagator) => {\n try {\n return propagator.extract(ctx, carrier, getter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n return ctx;\n }, context);\n }\n\n fields(): string[] {\n // return a new array so our fields cannot be modified\n return this._fields.slice();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n trace,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from './suppress-tracing';\nimport { TraceState } from './TraceState';\n\nexport const TRACE_PARENT_HEADER = 'traceparent';\nexport const TRACE_STATE_HEADER = 'tracestate';\n\nconst VERSION = '00';\nconst VERSION_PART = '(?!ff)[\\\\da-f]{2}';\nconst TRACE_ID_PART = '(?![0]{32})[\\\\da-f]{32}';\nconst PARENT_ID_PART = '(?![0]{16})[\\\\da-f]{16}';\nconst FLAGS_PART = '[\\\\da-f]{2}';\nconst TRACE_PARENT_REGEX = new RegExp(\n `^\\\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\\\s?$`\n);\n\n/**\n * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}\n * @param traceParent - A meta property that comes from server.\n * It should be dynamically generated server side to have the server's request trace Id,\n * a parent span Id that was set on the server's request span,\n * and the trace flags to indicate the server's sampling decision\n * (01 = sampled, 00 = not sampled).\n * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'\n * For more information see {@link https://www.w3.org/TR/trace-context/}\n */\nexport function parseTraceParent(traceParent: string): SpanContext | null {\n const match = TRACE_PARENT_REGEX.exec(traceParent);\n if (!match) return null;\n\n // According to the specification the implementation should be compatible\n // with future versions. If there are more parts, we only reject it if it's using version 00\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\n if (match[1] === '00' && match[5]) return null;\n\n return {\n traceId: match[2],\n spanId: match[3],\n traceFlags: parseInt(match[4], 16),\n };\n}\n\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n *\n * Based on the Trace Context specification:\n * https://www.w3.org/TR/trace-context/\n */\nexport class W3CTraceContextPropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n isTracingSuppressed(context) ||\n !isSpanContextValid(spanContext)\n )\n return;\n\n const traceParent = `${VERSION}-${spanContext.traceId}-${\n spanContext.spanId\n }-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;\n\n setter.set(carrier, TRACE_PARENT_HEADER, traceParent);\n if (spanContext.traceState) {\n setter.set(\n carrier,\n TRACE_STATE_HEADER,\n spanContext.traceState.serialize()\n );\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);\n if (!traceParentHeader) return context;\n const traceParent = Array.isArray(traceParentHeader)\n ? traceParentHeader[0]\n : traceParentHeader;\n if (typeof traceParent !== 'string') return context;\n const spanContext = parseTraceParent(traceParent);\n if (!spanContext) return context;\n\n spanContext.isRemote = true;\n\n const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);\n if (traceStateHeader) {\n // If more than one `tracestate` header is found, we merge them into a\n // single header.\n const state = Array.isArray(traceStateHeader)\n ? traceStateHeader.join(',')\n : traceStateHeader;\n spanContext.traceState = new TraceState(\n typeof state === 'string' ? state : undefined\n );\n }\n return trace.setSpanContext(context, spanContext);\n }\n\n fields(): string[] {\n return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { validateKey, validateValue } from '../internal/validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceState implements api.TraceState {\n private _internalState: Map = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceState {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceState {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceState {\n const traceState = new TraceState();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n obj: any;\n key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n let result: any = args.shift();\n const objects: WeakMap | undefined = new WeakMap<\n any,\n ObjectInto[]\n >();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n\n return result;\n}\n\nfunction takeValue(value: any): any {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n one: any,\n two: any,\n level = 0,\n objects: WeakMap\n): any {\n let result: any;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n } else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n } else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n result[key] = takeValue(two[key]);\n }\n }\n } else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n const twoValue = two[key];\n\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n } else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n } else {\n const obj1 = result[key];\n const obj2 = twoValue;\n\n if (\n wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)\n ) {\n delete result[key];\n } else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n\n result[key] = mergeTwoObjects(\n result[key],\n twoValue,\n level,\n objects\n );\n }\n }\n }\n } else {\n result = two;\n }\n }\n\n return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n obj: any,\n key: string,\n objects: WeakMap\n): boolean {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n return (\n !isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object'\n );\n}\n\nfunction isPrimitive(value: any): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null\n );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n\n return true;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\n **/\n\nconst objectTag = '[object Object]';\nconst nullTag = '[object Null]';\nconst undefinedTag = '[object Undefined]';\nconst funcProto = Function.prototype;\nconst funcToString = funcProto.toString;\nconst objectCtorString = funcToString.call(Object);\nconst getPrototype = overArg(Object.getPrototypeOf, Object);\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func: Function, transform: any): any {\n return function (arg: any) {\n return func(transform(arg));\n };\n}\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nexport function isPlainObject(value: any) {\n if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n return false;\n }\n const proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (\n typeof Ctor == 'function' &&\n Ctor instanceof Ctor &&\n funcToString.call(Ctor) === objectCtorString\n );\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value: any) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value: any) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return symToStringTag && symToStringTag in Object(value)\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value: any) {\n const isOwn = hasOwnProperty.call(value, symToStringTag as any),\n tag = value[symToStringTag as any];\n let unmasked = false;\n\n try {\n value[symToStringTag as any] = undefined;\n unmasked = true;\n } catch (e) {\n // silence\n }\n\n const result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag as any] = tag;\n } else {\n delete value[symToStringTag as any];\n }\n }\n return result;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value: any) {\n return nativeObjectToString.call(value);\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters): Promise {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred {\n private _promise: Promise;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context } from '@opentelemetry/api';\nimport { ExportResult } from '../ExportResult';\nimport { suppressTracing } from '../trace/suppress-tracing';\n\nexport interface Exporter {\n export(arg: T, resultCallback: (result: ExportResult) => void): void;\n}\n\n/**\n * @internal\n * Shared functionality used by Exporters while exporting data, including suppression of Traces.\n */\nexport function _export(\n exporter: Exporter,\n arg: T\n): Promise {\n return new Promise(resolve => {\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n exporter.export(arg, (result: ExportResult) => {\n resolve(result);\n });\n });\n });\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport { defaultServiceName } from './default-service-name';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function defaultServiceName(): string {\n return 'unknown_service';\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { Tracer } from './Tracer';\nexport {\n BasicTracerProvider,\n EXPORTER_FACTORY,\n ForceFlushState,\n PROPAGATOR_FACTORY,\n} from './BasicTracerProvider';\nexport { BatchSpanProcessor, RandomIdGenerator } from './platform';\nexport { ConsoleSpanExporter } from './export/ConsoleSpanExporter';\nexport { InMemorySpanExporter } from './export/InMemorySpanExporter';\nexport { ReadableSpan } from './export/ReadableSpan';\nexport { SimpleSpanProcessor } from './export/SimpleSpanProcessor';\nexport { SpanExporter } from './export/SpanExporter';\nexport { NoopSpanProcessor } from './export/NoopSpanProcessor';\nexport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nexport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nexport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nexport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\nexport { Sampler, SamplingDecision, SamplingResult } from './Sampler';\nexport { Span } from './Span';\nexport { SpanProcessor } from './SpanProcessor';\nexport { TimedEvent } from './TimedEvent';\nexport {\n BatchSpanProcessorBrowserConfig,\n BufferConfig,\n GeneralLimits,\n SDKRegistrationConfig,\n SpanLimits,\n TracerConfig,\n} from './types';\nexport { IdGenerator } from './IdGenerator';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n InstrumentationLibrary,\n sanitizeAttributes,\n isTracingSuppressed,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { BasicTracerProvider } from './BasicTracerProvider';\nimport { Span } from './Span';\nimport { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport { SpanProcessor } from './SpanProcessor';\nimport { Sampler } from './Sampler';\nimport { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationLibrary: InstrumentationLibrary,\n config: TracerConfig,\n private _tracerProvider: BasicTracerProvider\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this.resource = _tracerProvider.resource;\n this.instrumentationLibrary = instrumentationLibrary;\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let traceId;\n let traceState;\n let parentSpanId;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n parentSpanId = parentSpanContext.spanId;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new Span(\n this,\n context,\n name,\n spanContext,\n spanKind,\n parentSpanId,\n links,\n options.startTime,\n undefined,\n initAttributes\n );\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan ReturnType>(\n name: string,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType;\n startActiveSpan ReturnType>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n\n getActiveSpanProcessor(): SpanProcessor {\n return this._tracerProvider.getActiveSpanProcessor();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanAttributes,\n SpanAttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n InstrumentationLibrary,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport {\n SEMATTRS_EXCEPTION_MESSAGE,\n SEMATTRS_EXCEPTION_STACKTRACE,\n SEMATTRS_EXCEPTION_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport { ExceptionEventName } from './enums';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { Tracer } from './Tracer';\nimport { SpanLimits } from './types';\n\n/**\n * This class represents a span.\n */\nexport class Span implements APISpan, ReadableSpan {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanId?: string;\n readonly attributes: SpanAttributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new Span instance.\n *\n * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.\n * */\n constructor(\n parentTracer: Tracer,\n context: Context,\n spanName: string,\n spanContext: SpanContext,\n kind: SpanKind,\n parentSpanId?: string,\n links: Link[] = [],\n startTime?: TimeInput,\n _deprecatedClock?: unknown, // keeping this argument even though it is unused to ensure backwards compatibility\n attributes?: SpanAttributes\n ) {\n this.name = spanName;\n this._spanContext = spanContext;\n this.parentSpanId = parentSpanId;\n this.kind = kind;\n this.links = links;\n\n const now = Date.now();\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + getTimeOrigin());\n this._startTimeProvided = startTime != null;\n\n this.startTime = this._getTime(startTime ?? now);\n\n this.resource = parentTracer.resource;\n this.instrumentationLibrary = parentTracer.instrumentationLibrary;\n this._spanLimits = parentTracer.getSpanLimits();\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n\n if (attributes != null) {\n this.setAttributes(attributes);\n }\n\n this._spanProcessor = parentTracer.getActiveSpanProcessor();\n this._spanProcessor.onStart(this, context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: SpanAttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n if (\n Object.keys(this.attributes).length >=\n this._spanLimits.attributeCountLimit! &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): this {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n if (this._spanLimits.eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (this.events.length >= this._spanLimits.eventCountLimit!) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n addLink(link: Link): this {\n this.links.push(link);\n return this;\n }\n\n addLinks(links: Link[]): this {\n this.links.push(...links);\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = status;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this._ended = true;\n\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp < otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: SpanAttributes = {};\n if (typeof exception === 'string') {\n attributes[SEMATTRS_EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[SEMATTRS_EXCEPTION_TYPE] = exception.code.toString();\n } else if (exception.name) {\n attributes[SEMATTRS_EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[SEMATTRS_EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[SEMATTRS_EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (\n attributes[SEMATTRS_EXCEPTION_TYPE] ||\n attributes[SEMATTRS_EXCEPTION_MESSAGE]\n ) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n diag.warn(\n `Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substr(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: SpanAttributeValue): SpanAttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport { Sampler } from './Sampler';\nimport { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport {\n DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n getEnvWithoutDefaults,\n} from '@opentelemetry/core';\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n const parsedEnvConfig = getEnvWithoutDefaults();\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT ??\n parsedEnvConfig.OTEL_ATTRIBUTE_COUNT_LIMIT ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT ??\n parsedEnvConfig.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getEnv, TracesSamplerValues, ENVIRONMENT } from '@opentelemetry/core';\nimport { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst env = getEnv();\nconst FALLBACK_OTEL_TRACES_SAMPLER = TracesSamplerValues.AlwaysOn;\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n const _env = getEnv();\n\n return {\n sampler: buildSamplerFromEnv(env),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit: _env.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n attributeCountLimit: _env.OTEL_ATTRIBUTE_COUNT_LIMIT,\n },\n spanLimits: {\n attributeValueLengthLimit: _env.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n attributeCountLimit: _env.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,\n linkCountLimit: _env.OTEL_SPAN_LINK_COUNT_LIMIT,\n eventCountLimit: _env.OTEL_SPAN_EVENT_COUNT_LIMIT,\n attributePerEventCountLimit:\n _env.OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n attributePerLinkCountLimit: _env.OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n * @param environment optional, by default uses getEnv(), but allows passing a value to reuse parsed environment\n */\nexport function buildSamplerFromEnv(\n environment: Required = getEnv()\n): Sampler {\n switch (environment.OTEL_TRACES_SAMPLER) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(\n getSamplerProbabilityFromEnv(environment)\n );\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(\n getSamplerProbabilityFromEnv(environment)\n ),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${environment.OTEL_TRACES_SAMPLER} invalid, defaulting to ${FALLBACK_OTEL_TRACES_SAMPLER}\".`\n );\n return new AlwaysOnSampler();\n }\n}\n\nfunction getSamplerProbabilityFromEnv(\n environment: Required\n): number | undefined {\n if (\n environment.OTEL_TRACES_SAMPLER_ARG === undefined ||\n environment.OTEL_TRACES_SAMPLER_ARG === ''\n ) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n const probability = Number(environment.OTEL_TRACES_SAMPLER_ARG);\n\n if (isNaN(probability)) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is invalid, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n Link,\n SpanAttributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of SpanAttributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n Link,\n SpanAttributes,\n SpanKind,\n TraceFlags,\n trace,\n} from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private _upperBound: number;\n\n constructor(private readonly _ratio: number = 0) {\n this._ratio = this._normalize(_ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { BatchSpanProcessor } from './export/BatchSpanProcessor';\nexport { RandomIdGenerator } from './RandomIdGenerator';\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { SpanExporter } from '../../../export/SpanExporter';\nimport { BatchSpanProcessorBrowserConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase {\n private _visibilityChangeListener?: () => void;\n private _pageHideListener?: () => void;\n\n constructor(\n _exporter: SpanExporter,\n config?: BatchSpanProcessorBrowserConfig\n ) {\n super(_exporter, config);\n this.onInit(config);\n }\n\n private onInit(config?: BatchSpanProcessorBrowserConfig): void {\n if (\n config?.disableAutoFlushOnDocumentHide !== true &&\n typeof document !== 'undefined'\n ) {\n this._visibilityChangeListener = () => {\n if (document.visibilityState === 'hidden') {\n void this.forceFlush();\n }\n };\n this._pageHideListener = () => {\n void this.forceFlush();\n };\n document.addEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n\n // use 'pagehide' event as a fallback for Safari; see https://bugs.webkit.org/show_bug.cgi?id=116769\n document.addEventListener('pagehide', this._pageHideListener);\n }\n }\n\n protected onShutdown(): void {\n if (typeof document !== 'undefined') {\n if (this._visibilityChangeListener) {\n document.removeEventListener(\n 'visibilitychange',\n this._visibilityChangeListener\n );\n }\n if (this._pageHideListener) {\n document.removeEventListener('pagehide', this._pageHideListener);\n }\n }\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_CHAR_CODES_ARRAY = Array(32);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes * 2; i++) {\n SHARED_CHAR_CODES_ARRAY[i] = Math.floor(Math.random() * 16) + 48;\n // valid hex characters in the range 48-57 and 97-102\n if (SHARED_CHAR_CODES_ARRAY[i] >= 58) {\n SHARED_CHAR_CODES_ARRAY[i] += 39;\n }\n }\n return String.fromCharCode.apply(\n null,\n SHARED_CHAR_CODES_ARRAY.slice(0, bytes * 2)\n );\n };\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n context,\n diag,\n propagation,\n TextMapPropagator,\n trace,\n TracerProvider,\n} from '@opentelemetry/api';\nimport {\n CompositePropagator,\n W3CBaggagePropagator,\n W3CTraceContextPropagator,\n getEnv,\n merge,\n} from '@opentelemetry/core';\nimport { IResource, Resource } from '@opentelemetry/resources';\nimport { SpanProcessor, Tracer } from '.';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport { NoopSpanProcessor } from './export/NoopSpanProcessor';\nimport { SDKRegistrationConfig, TracerConfig } from './types';\nimport { SpanExporter } from './export/SpanExporter';\nimport { BatchSpanProcessor } from './platform';\nimport { reconfigureLimits } from './utility';\n\nexport type PROPAGATOR_FACTORY = () => TextMapPropagator;\nexport type EXPORTER_FACTORY = () => SpanExporter;\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n protected static readonly _registeredPropagators = new Map<\n string,\n PROPAGATOR_FACTORY\n >([\n ['tracecontext', () => new W3CTraceContextPropagator()],\n ['baggage', () => new W3CBaggagePropagator()],\n ]);\n\n protected static readonly _registeredExporters = new Map<\n string,\n EXPORTER_FACTORY\n >();\n\n private readonly _config: TracerConfig;\n private readonly _registeredSpanProcessors: SpanProcessor[] = [];\n private readonly _tracers: Map = new Map();\n\n activeSpanProcessor: SpanProcessor;\n readonly resource: IResource;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this.resource = mergedConfig.resource ?? Resource.empty();\n this.resource = Resource.default().merge(this.resource);\n this._config = Object.assign({}, mergedConfig, {\n resource: this.resource,\n });\n\n const defaultExporter = this._buildExporterFromEnv();\n if (defaultExporter !== undefined) {\n const batchProcessor = new BatchSpanProcessor(defaultExporter);\n this.activeSpanProcessor = batchProcessor;\n } else {\n this.activeSpanProcessor = new NoopSpanProcessor();\n }\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): Tracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this\n )\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this._tracers.get(key)!;\n }\n\n /**\n * Adds a new {@link SpanProcessor} to this tracer.\n * @param spanProcessor the new SpanProcessor to be added.\n */\n addSpanProcessor(spanProcessor: SpanProcessor): void {\n if (this._registeredSpanProcessors.length === 0) {\n // since we might have enabled by default a batchProcessor, we disable it\n // before adding the new one\n this.activeSpanProcessor\n .shutdown()\n .catch(err =>\n diag.error(\n 'Error while trying to shutdown current span processor',\n err\n )\n );\n }\n this._registeredSpanProcessors.push(spanProcessor);\n this.activeSpanProcessor = new MultiSpanProcessor(\n this._registeredSpanProcessors\n );\n }\n\n getActiveSpanProcessor(): SpanProcessor {\n return this.activeSpanProcessor;\n }\n\n /**\n * Register this TracerProvider for use with the OpenTelemetry API.\n * Undefined values may be replaced with defaults, and\n * null values will be skipped.\n *\n * @param config Configuration object for SDK registration\n */\n register(config: SDKRegistrationConfig = {}): void {\n trace.setGlobalTracerProvider(this);\n if (config.propagator === undefined) {\n config.propagator = this._buildPropagatorFromEnv();\n }\n\n if (config.contextManager) {\n context.setGlobalContextManager(config.contextManager);\n }\n\n if (config.propagator) {\n propagation.setGlobalPropagator(config.propagator);\n }\n }\n\n forceFlush(): Promise {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._registeredSpanProcessors.map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise {\n return this.activeSpanProcessor.shutdown();\n }\n\n /**\n * TS cannot yet infer the type of this.constructor:\n * https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146\n * There is no need to override either of the getters in your child class.\n * The type of the registered component maps should be the same across all\n * classes in the inheritance tree.\n */\n protected _getPropagator(name: string): TextMapPropagator | undefined {\n return (\n this.constructor as typeof BasicTracerProvider\n )._registeredPropagators.get(name)?.();\n }\n\n protected _getSpanExporter(name: string): SpanExporter | undefined {\n return (\n this.constructor as typeof BasicTracerProvider\n )._registeredExporters.get(name)?.();\n }\n\n protected _buildPropagatorFromEnv(): TextMapPropagator | undefined {\n // per spec, propagators from env must be deduplicated\n const uniquePropagatorNames = Array.from(\n new Set(getEnv().OTEL_PROPAGATORS)\n );\n\n const propagators = uniquePropagatorNames.map(name => {\n const propagator = this._getPropagator(name);\n if (!propagator) {\n diag.warn(\n `Propagator \"${name}\" requested through environment variable is unavailable.`\n );\n }\n\n return propagator;\n });\n const validPropagators = propagators.reduce(\n (list, item) => {\n if (item) {\n list.push(item);\n }\n return list;\n },\n []\n );\n\n if (validPropagators.length === 0) {\n return;\n } else if (uniquePropagatorNames.length === 1) {\n return validPropagators[0];\n } else {\n return new CompositePropagator({\n propagators: validPropagators,\n });\n }\n }\n\n protected _buildExporterFromEnv(): SpanExporter | undefined {\n const exporterName = getEnv().OTEL_TRACES_EXPORTER;\n if (exporterName === 'none' || exporterName === '') return;\n const exporter = this._getSpanExporter(exporterName);\n if (!exporter) {\n diag.error(\n `Exporter \"${exporterName}\" requested through environment variable is unavailable.`\n );\n }\n return exporter;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { Span } from './Span';\nimport { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n constructor(private readonly _spanProcessors: SpanProcessor[]) {}\n\n forceFlush(): Promise {\n const promises: Promise[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise {\n const promises: Promise[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '@opentelemetry/api';\nimport { ReadableSpan } from './ReadableSpan';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\n\n/** No-op implementation of SpanProcessor */\nexport class NoopSpanProcessor implements SpanProcessor {\n onStart(_span: Span, _context: Context): void {}\n onEnd(_span: ReadableSpan): void {}\n shutdown(): Promise {\n return Promise.resolve();\n }\n forceFlush(): Promise {\n return Promise.resolve();\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, TraceFlags } from '@opentelemetry/api';\nimport {\n internal,\n ExportResultCode,\n globalErrorHandler,\n BindOnceFuture,\n ExportResult,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\nimport { Resource } from '@opentelemetry/resources';\n\n/**\n * An implementation of the {@link SpanProcessor} that converts the {@link Span}\n * to {@link ReadableSpan} and passes it to the configured exporter.\n *\n * Only spans that are sampled are converted.\n *\n * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead.\n */\nexport class SimpleSpanProcessor implements SpanProcessor {\n private _shutdownOnce: BindOnceFuture;\n private _unresolvedExports: Set>;\n\n constructor(private readonly _exporter: SpanExporter) {\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n this._unresolvedExports = new Set>();\n }\n\n async forceFlush(): Promise {\n // await unresolved resources before resolving\n await Promise.all(Array.from(this._unresolvedExports));\n if (this._exporter.forceFlush) {\n await this._exporter.forceFlush();\n }\n }\n\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n const doExport = () =>\n internal\n ._export(this._exporter, [span])\n .then((result: ExportResult) => {\n if (result.code !== ExportResultCode.SUCCESS) {\n globalErrorHandler(\n result.error ??\n new Error(\n `SimpleSpanProcessor: span export failed (status ${result})`\n )\n );\n }\n })\n .catch(error => {\n globalErrorHandler(error);\n });\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (span.resource.asyncAttributesPending) {\n const exportPromise = (span.resource as Resource)\n .waitForAsyncAttributes?.()\n .then(\n () => {\n if (exportPromise != null) {\n this._unresolvedExports.delete(exportPromise);\n }\n return doExport();\n },\n err => globalErrorHandler(err)\n );\n\n // store the unresolved exports\n if (exportPromise != null) {\n this._unresolvedExports.add(exportPromise);\n }\n } else {\n void doExport();\n }\n }\n\n shutdown(): Promise {\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise {\n return this._exporter.shutdown();\n }\n}\n", "export { AsyncLocalStorageContextManager } from \"./AsyncLocalStorageContextManager\";\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { type Context, ROOT_CONTEXT } from \"@opentelemetry/api\";\nimport { AbstractAsyncHooksContextManager } from \"./AbstractAsyncHooksContextManager\";\n\nexport class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager {\n private _asyncLocalStorage: AsyncLocalStorage;\n\n constructor() {\n super();\n this._asyncLocalStorage = new AsyncLocalStorage();\n }\n\n active(): Context {\n return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;\n }\n\n with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType {\n const cb = thisArg == null ? fn : fn.bind(thisArg);\n return this._asyncLocalStorage.run(context, cb as never, ...args);\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n this._asyncLocalStorage.disable();\n return this;\n }\n}\n", "/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventEmitter } from \"node:events\";\nimport type { Context, ContextManager } from \"@opentelemetry/api\";\n\ntype Func = (...args: unknown[]) => T;\n\n/**\n * Store a map for each event of all original listeners and their \"patched\"\n * version. So when a listener is removed by the user, the corresponding\n * patched function will be also removed.\n */\ninterface PatchMap {\n [name: string]: WeakMap, Func>;\n}\n\nconst ADD_LISTENER_METHODS = [\n \"addListener\" as const,\n \"on\" as const,\n \"once\" as const,\n \"prependListener\" as const,\n \"prependOnceListener\" as const,\n];\n\nexport abstract class AbstractAsyncHooksContextManager\n implements ContextManager\n{\n abstract active(): Context;\n\n abstract with ReturnType>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType,\n ...args: A\n ): ReturnType;\n\n abstract enable(): this;\n\n abstract disable(): this;\n\n /**\n * Binds a the certain context or the active one to the target function and then returns the target\n * @param context A context (span) to be bind to target\n * @param target a function or event emitter. When target or one of its callbacks is called,\n * the provided context will be used as the active context for the duration of the call.\n */\n bind(context: Context, target: T): T {\n if (target instanceof EventEmitter) {\n return this._bindEventEmitter(context, target);\n }\n\n if (typeof target === \"function\") {\n return this._bindFunction(context, target);\n }\n return target;\n }\n\n // biome-ignore lint/complexity/noBannedTypes: this is from the original code\n private _bindFunction(context: Context, target: T): T {\n const manager = this;\n const contextWrapper = function (this: never, ...args: unknown[]) {\n return manager.with(context, () => target.apply(this, args));\n };\n Object.defineProperty(contextWrapper, \"length\", {\n enumerable: false,\n configurable: true,\n writable: false,\n value: target.length,\n });\n /**\n * It isn't possible to tell Typescript that contextWrapper is the same as T\n * so we forced to cast as any here.\n */\n // biome-ignore lint/suspicious/noExplicitAny: this is from the original code\n return contextWrapper as any;\n }\n\n /**\n * By default, EventEmitter call their callback with their context, which we do\n * not want, instead we will bind a specific context to all callbacks that\n * go through it.\n * @param context the context we want to bind\n * @param ee EventEmitter an instance of EventEmitter to patch\n */\n private _bindEventEmitter(\n context: Context,\n ee: T,\n ): T {\n const map = this._getPatchMap(ee);\n if (map !== undefined) {\n return ee;\n }\n this._createPatchMap(ee);\n\n // patch methods that add a listener to propagate context\n // biome-ignore lint/complexity/noForEach: this is from the original code\n ADD_LISTENER_METHODS.forEach((methodName) => {\n if (ee[methodName] === undefined) {\n return;\n }\n ee[methodName] = this._patchAddListener(ee, ee[methodName], context);\n });\n // patch methods that remove a listener\n if (typeof ee.removeListener === \"function\") {\n ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);\n }\n if (typeof ee.off === \"function\") {\n ee.off = this._patchRemoveListener(ee, ee.off);\n }\n // patch method that remove all listeners\n if (typeof ee.removeAllListeners === \"function\") {\n ee.removeAllListeners = this._patchRemoveAllListeners(\n ee,\n ee.removeAllListeners,\n );\n }\n return ee;\n }\n\n /**\n * Patch methods that remove a given listener so that we match the \"patched\"\n * version of that listener (the one that propagate context).\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n // biome-ignore lint/complexity/noBannedTypes: this is from the original code\n private _patchRemoveListener(ee: EventEmitter, original: Function) {\n const contextManager = this;\n return function (this: never, event: string, listener: Func) {\n const events = contextManager._getPatchMap(ee)?.[event];\n if (events === undefined) {\n return original.call(this, event, listener);\n }\n const patchedListener = events.get(listener);\n return original.call(this, event, patchedListener || listener);\n };\n }\n\n /**\n * Patch methods that remove all listeners so we remove our\n * internal references for a given event.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n // biome-ignore lint/complexity/noBannedTypes: this is from the original code\n private _patchRemoveAllListeners(ee: EventEmitter, original: Function) {\n const contextManager = this;\n return function (this: never, event: string) {\n const map = contextManager._getPatchMap(ee);\n if (map !== undefined) {\n // biome-ignore lint/style/noArguments: this is from the original code\n if (arguments.length === 0) {\n contextManager._createPatchMap(ee);\n } else if (map[event] !== undefined) {\n delete map[event];\n }\n }\n // biome-ignore lint/style/noArguments: this is from the original code\n return original.apply(this, arguments);\n };\n }\n\n /**\n * Patch methods on an event emitter instance that can add listeners so we\n * can force them to propagate a given context.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n * @param [context] context to propagate when calling listeners\n */\n private _patchAddListener(\n ee: EventEmitter,\n // biome-ignore lint/complexity/noBannedTypes: this is from the original code\n original: Function,\n context: Context,\n ) {\n const contextManager = this;\n return function (this: never, event: string, listener: Func) {\n /**\n * This check is required to prevent double-wrapping the listener.\n * The implementation for ee.once wraps the listener and calls ee.on.\n * Without this check, we would wrap that wrapped listener.\n * This causes an issue because ee.removeListener depends on the onceWrapper\n * to properly remove the listener. If we wrap their wrapper, we break\n * that detection.\n */\n if (contextManager._wrapped) {\n return original.call(this, event, listener);\n }\n let map = contextManager._getPatchMap(ee);\n if (map === undefined) {\n map = contextManager._createPatchMap(ee);\n }\n let listeners = map[event];\n if (listeners === undefined) {\n listeners = new WeakMap();\n map[event] = listeners;\n }\n const patchedListener = contextManager.bind(context, listener);\n // store a weak reference of the user listener to ours\n listeners.set(listener, patchedListener);\n\n /**\n * See comment at the start of this function for the explanation of this property.\n */\n contextManager._wrapped = true;\n try {\n return original.call(this, event, patchedListener);\n } finally {\n contextManager._wrapped = false;\n }\n };\n }\n\n private _createPatchMap(ee: EventEmitter): PatchMap {\n const map = Object.create(null);\n // biome-ignore lint/suspicious/noExplicitAny: this is from the original code\n (ee as any)[this._kOtListeners] = map;\n return map;\n }\n private _getPatchMap(ee: EventEmitter): PatchMap | undefined {\n return (ee as never)[this._kOtListeners];\n }\n\n private readonly _kOtListeners = Symbol(\"OtListeners\");\n private _wrapped = false;\n}\n", "import {\n type Attributes,\n type Exception,\n type Span,\n type SpanKind,\n SpanStatusCode,\n trace,\n} from \"@opentelemetry/api\";\n\nexport type MeasureOptions<\n /**\n * Arguments for the function being measured\n */\n ARGS,\n /**\n * The return type of the function being measured\n * (awaited result if the return value is a promise)\n */\n RESULT,\n /**\n * The raw return type of the function being measured\n * (it is used to determine if the onSuccess function can be async)\n */\n RAW_RESULT,\n> = {\n name: string;\n /**\n * The kind of the span\n */\n spanKind?: SpanKind;\n /**\n * Attributes to be added to the span\n */\n attributes?: Attributes;\n\n onStart?: (span: Span, args: ARGS) => void;\n /**\n * Allows you to specify a function that will be called when the span ends\n * and will be passed the span & result of the function being measured.\n *\n * This way you can do things like add additional attributes to the span\n */\n onSuccess?: (\n span: Span,\n result: RESULT,\n ) => RAW_RESULT extends Promise ? Promise | void : void;\n\n /**\n * Allows you to specify a function that will be called when the span ends\n * with an error and will be passed the (current) span & error that occurred.\n *\n * This way you can do things like add additional attributes to the span\n */\n onError?: (span: Span, error: unknown) => void;\n\n /**\n * You can specify a function that will allow you to throw an error based on the value of the\n * result (returned by the measured function). This error will only be used for recording the error\n * in the span and will not be thrown.\n */\n checkResult?: (\n result: RESULT,\n ) => RAW_RESULT extends Promise ? Promise | void : void;\n};\n\n/**\n * Wraps a function in a span, measuring the time it takes to execute\n * the function.\n *\n * @param name (string) The name of the span that will be created\n * @param fn (function) The function to be measured\n * @returns (function) The wrapped function, with the same signature as the original function\n */\nexport function measure(\n name: string,\n fn: (...args: A) => T,\n): (...args: A) => T;\n\n/**\n * Wraps a function in a span, measuring the time it takes to execute\n * the function.\n *\n * @param options param name and spanKind\n * @param fn\n */\nexport function measure(\n options: MeasureOptions,\n fn: (...args: A) => R,\n): (...args: A) => R;\n\nexport function measure(\n nameOrOptions: string | MeasureOptions,\n fn: (...args: A) => R,\n): (...args: A) => R {\n const isOptions = typeof nameOrOptions === \"object\";\n const name: string = isOptions ? nameOrOptions.name : nameOrOptions;\n const spanKind: SpanKind | undefined = isOptions\n ? nameOrOptions.spanKind\n : undefined;\n const attributes: Attributes | undefined = isOptions\n ? nameOrOptions.attributes\n : undefined;\n const onStart = isOptions ? nameOrOptions.onStart : undefined;\n const onSuccess = isOptions ? nameOrOptions.onSuccess : undefined;\n const onError = isOptions ? nameOrOptions.onError : undefined;\n const checkResult = isOptions ? nameOrOptions.checkResult : undefined;\n\n return (...args: A): R => {\n function handleActiveSpan(span: Span): R {\n let shouldEndSpan = true;\n\n let pendingPromiseChain: Promise | undefined;\n\n if (onStart) {\n try {\n onStart(span, args);\n } catch {\n // swallow error\n }\n }\n\n try {\n const returnValue = fn(...args);\n if (isPromise(returnValue)) {\n shouldEndSpan = false;\n return handlePromise(span, returnValue, {\n onSuccess,\n onError,\n checkResult,\n }) as R;\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n\n // HACK - `onSuccess` can be async, so we need to wait for it to finish before ending the span (in the finally clause)\n if (onSuccess) {\n pendingPromiseChain = new Promise((resolve) => {\n try {\n const onSuccessResult = onSuccess(span, returnValue);\n if (onSuccessResult instanceof Promise) {\n onSuccessResult.then(() => {\n resolve(returnValue);\n });\n } else {\n resolve(returnValue);\n }\n } catch (_error) {\n // swallow error\n // console.debug(\"Error in onSuccess\", _error);\n resolve(returnValue);\n }\n });\n }\n\n return returnValue;\n } catch (error) {\n const sendError: Exception =\n error instanceof Error ? error : \"Unknown error occurred\";\n span.recordException(sendError);\n\n if (onError) {\n try {\n onError(span, error);\n } catch {\n // swallow error\n }\n }\n\n throw error;\n } finally {\n if (pendingPromiseChain) {\n pendingPromiseChain.then(() => {\n if (shouldEndSpan) {\n span.end();\n }\n });\n } else if (shouldEndSpan) {\n span.end();\n }\n }\n }\n\n const tracer = trace.getTracer(\"fpx-tracer\");\n return tracer.startActiveSpan(\n name,\n { kind: spanKind, attributes },\n handleActiveSpan,\n );\n };\n}\n\n/**\n * Handle complete flow of a promise (including ending the span)\n *\n * @returns the promise\n */\nasync function handlePromise(\n span: Span,\n promise: Promise,\n options: Pick<\n MeasureOptions>,\n \"onSuccess\" | \"onError\" | \"checkResult\"\n >,\n): Promise {\n const { onSuccess, onError, checkResult } = options;\n try {\n const result = await Promise.resolve(promise);\n\n if (checkResult) {\n try {\n await checkResult(result);\n } catch (error) {\n // recordException only accepts Error objects or strings\n const sendError: Exception =\n error instanceof Error ? error : \"Unknown error occured\";\n span.recordException(sendError);\n\n if (onError) {\n try {\n await onError(span, sendError);\n } catch {\n // swallow error\n }\n }\n\n if (onSuccess) {\n try {\n await onSuccess(span, result);\n } catch {\n // swallow error\n }\n }\n\n return result;\n }\n }\n\n span.setStatus({ code: SpanStatusCode.OK });\n if (onSuccess) {\n try {\n await onSuccess(span, result);\n } catch {\n // swallow error\n }\n }\n\n return result;\n } catch (error) {\n try {\n // recordException only accepts Error objects or strings\n const sendError: Exception =\n error instanceof Error ? error : \"Unknown error occured\";\n span.recordException(sendError);\n\n const message =\n typeof sendError === \"string\"\n ? sendError\n : sendError.message || \"Unknown error occured\";\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n\n if (onError) {\n try {\n onError(span, error);\n } catch {\n // swallow error\n }\n }\n } catch {\n // swallow error\n }\n\n // Rethrow the error\n throw error;\n } finally {\n span.end();\n }\n}\n\nfunction isPromise(value: unknown): value is Promise {\n return value instanceof Promise;\n}\n", "export { patchFetch } from \"./fetch\";\nexport { patchConsole } from \"./log\";\nexport { patchWaitUntil } from \"./waitUntil\";\nexport { patchCloudflareBindings } from \"./cf-bindings\";\n", "import { SpanKind } from \"@opentelemetry/api\";\nimport shimmer from \"shimmer\";\nimport { measure } from \"../measure\";\nimport {\n getRequestAttributes,\n getResponseAttributes,\n isWrapped,\n} from \"../utils\";\n\nconst { wrap } = shimmer;\n\nexport function patchFetch() {\n // Check if the function is already patched\n // If it is, we don't want to patch it again\n if (isWrapped(globalThis.fetch)) {\n return;\n }\n\n wrap(globalThis, \"fetch\", (original) => {\n return measure(\n {\n name: \"fetch\",\n spanKind: SpanKind.CLIENT,\n onStart: (span, [input, init]) => {\n span.setAttributes(getRequestAttributes(input, init));\n },\n onSuccess: async (span, response) => {\n const attributes = await getResponseAttributes(\n (await response).clone(),\n );\n span.setAttributes(attributes);\n },\n },\n original,\n ) as typeof original;\n });\n}\n", "export * from \"./errors\";\nexport * from \"./json\";\nexport * from \"./request\";\nexport * from \"./wrapper\";\n", "export function errorToJson(error: Error) {\n return {\n name: error.name, // Includes the name of the error, e.g., 'TypeError'\n message: error.message, // The message string of the error\n stack: error.stack, // Stack trace of where the error occurred (useful for debugging)\n };\n}\n\ntype LikelyNeonDbError = {\n name: string;\n message: string;\n sourceError?: Error;\n};\n\n/**\n * Quick and dirty type guard to check if an error is *likely* a NeonDbError\n */\nexport function isLikelyNeonDbError(\n error: unknown,\n): error is LikelyNeonDbError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"name\" in error &&\n typeof error.name === \"string\" &&\n \"message\" in error &&\n typeof error.message === \"string\" &&\n (!(\"sourceError\" in error) || error.sourceError instanceof Error)\n );\n}\n\nexport function neonDbErrorToJson(error: LikelyNeonDbError) {\n return {\n name: error.name,\n message: error.message,\n sourceError: error.sourceError ? errorToJson(error.sourceError) : undefined,\n\n // NOTE - NeonDbError does not include a stack trace! https://github.com/neondatabase/serverless/issues/82\n stack: error?.sourceError?.stack,\n\n // TODO - Figure out how to extract these fields from NeonDbError...\n //\n // where: error?.sourceError?.where,\n // table: error?.sourceError?.table,\n // column: error?.sourceError?.column,\n // dataType: error?.sourceError?.dataType,\n // internalQuery: error?.sourceError?.internalQuery,\n };\n}\n", "export function safelySerializeJSON(obj: unknown): string {\n const seen = new WeakSet();\n return JSON.stringify(obj, (_key, value) => {\n // HACK - Do not serialize binary data - There is probably a smarter way to do this\n if (isUintArray(value)) {\n return \"BINARY\";\n }\n if (typeof value === \"object\" && value !== null) {\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n }\n return value;\n });\n}\n\nexport function isUintArray(arr: unknown): arr is number[] {\n return (\n arr instanceof Uint8Array ||\n arr instanceof Uint16Array ||\n arr instanceof Uint32Array\n );\n}\n", "import type { Response as WorkerResponse } from \"@cloudflare/workers-types\";\nimport type { Attributes } from \"@opentelemetry/api\";\nimport {\n SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,\n SEMATTRS_HTTP_SCHEME,\n} from \"@opentelemetry/semantic-conventions\";\nimport {\n EXTRA_SEMATTRS_HTTP_REQUEST_METHOD,\n EXTRA_SEMATTRS_HTTP_RESPONSE_STATUS_CODE,\n EXTRA_SEMATTRS_URL_FULL,\n FPX_REQUEST_BODY,\n FPX_REQUEST_ENV,\n FPX_REQUEST_PATHNAME,\n FPX_REQUEST_SCHEME,\n FPX_REQUEST_SEARCH,\n FPX_RESPONSE_BODY,\n} from \"../constants\";\nimport type {\n GlobalResponse,\n HonoResponse,\n InitParam,\n InputParam,\n} from \"../types\";\n\n// There are so many different types of headers\n// and we want to support all of them so we can\n// use a single function to do it all\ntype PossibleHeaders =\n | Headers\n | HonoResponse[\"headers\"]\n | GlobalResponse[\"headers\"];\n\nexport function headersToObject(headers: PossibleHeaders) {\n const returnObject: Record = {};\n headers.forEach((value, key) => {\n returnObject[key] = value;\n });\n\n return returnObject;\n}\n\n/**\n * HELPER\n */\nexport async function getRootRequestAttributes(request: Request, env: unknown) {\n let attributes: Attributes = {\n // NOTE - We should not do this in production\n [FPX_REQUEST_ENV]: JSON.stringify(env),\n };\n\n if (request.body) {\n const bodyAttr = await formatRootRequestBody(request);\n if (bodyAttr) {\n attributes = {\n ...attributes,\n ...bodyAttr,\n };\n }\n }\n\n if (request.headers) {\n const headers = headersToObject(new Headers(request.headers));\n for (const [key, value] of Object.entries(headers)) {\n attributes[`http.request.header.${key}`] = value;\n }\n }\n\n return attributes;\n}\n\nasync function formatRootRequestBody(request: Request) {\n if (!request.body) {\n return null;\n }\n\n const contentType = request.headers.get(\"content-type\");\n\n const shouldParseAsText =\n contentType?.includes(\"application/json\") ||\n contentType?.includes(\"text/\") ||\n contentType?.includes(\"x-www-form-urlencoded\");\n\n if (shouldParseAsText) {\n // Return as text\n return {\n [FPX_REQUEST_BODY]: await request.text(),\n };\n }\n\n // TODO - Check how files are handled\n if (contentType?.includes(\"multipart/form-data\")) {\n const formData = await request.formData();\n const textifiedFormData = formDataToJson(formData);\n return {\n [FPX_REQUEST_BODY]: textifiedFormData,\n };\n }\n\n return {\n [FPX_REQUEST_BODY]: formatBody(request.body),\n };\n}\n\nexport function getRequestAttributes(input: InputParam, init?: InitParam) {\n const requestMethod =\n typeof input === \"string\" || input instanceof URL ? \"GET\" : input.method;\n const requestUrl = input instanceof Request ? input.url : input;\n const url = new URL(requestUrl);\n const urlScheme = url.protocol.replace(\":\", \"\");\n const attributes: Attributes = {\n [EXTRA_SEMATTRS_HTTP_REQUEST_METHOD]: requestMethod,\n // [HTTP_REQUEST_METHOD_ORIGINAL]: request.method,\n // TODO: remove login/password from URL (if we want to follow\n // the otel spec for this attribute)\n // TODO: think about how to handle a redirect\n [EXTRA_SEMATTRS_URL_FULL]: url.toString(),\n // Bunch of custom attributes even though some experimental\n // packages from otel already have similar attributes\n [FPX_REQUEST_PATHNAME]: url.pathname,\n [FPX_REQUEST_SEARCH]: url.search,\n // TODO: Add path\n // [SEMATTRS_]\n [FPX_REQUEST_SCHEME]: urlScheme,\n };\n\n // Init should not be null or undefined\n if (init) {\n const { body } = init;\n if (body != null) {\n attributes[FPX_REQUEST_BODY] = formatBody(body);\n }\n\n if (init.headers) {\n const headers = headersToObject(new Headers(init.headers));\n for (const [key, value] of Object.entries(headers)) {\n attributes[`http.request.header.${key}`] = value;\n }\n }\n }\n\n return attributes;\n}\n\nfunction formatBody(body: BodyInit) {\n if (body instanceof FormData) {\n return formDataToJson(body);\n }\n\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n return \"#fpx.arrayBuffer\";\n }\n if (body instanceof ReadableStream) {\n return \"#fpx.stream\";\n }\n if (body instanceof Blob) {\n return \"#fpx.blob\";\n }\n\n if (body instanceof URLSearchParams) {\n return body.toString();\n }\n\n return body;\n}\n\nfunction formDataToJson(formData: FormData) {\n const jsonObject: Record> = {};\n\n for (const [key, value] of formData.entries()) {\n // Handle multiple values for the same key (e.g., checkboxes)\n if (jsonObject[key]) {\n if (!Array.isArray(jsonObject[key])) {\n jsonObject[key] = [jsonObject[key]];\n }\n jsonObject[key].push(value ? formDataValueToString(value) : value);\n } else {\n jsonObject[key] = value ? formDataValueToString(value) : value;\n }\n }\n\n return JSON.stringify(jsonObject);\n}\n\nfunction formDataValueToString(value: string | File) {\n if (value instanceof File) {\n return value.name ?? `#fpx.file.{${value.name}}.{${value.size}}`;\n }\n\n return value;\n}\n\nasync function tryGetResponseBodyAsText(\n response: GlobalResponse | WorkerResponse,\n) {\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"image/\")) {\n return \"#fpx.image\";\n }\n if (contentType?.includes(\"application/pdf\")) {\n return \"#fpx.pdf\";\n }\n if (contentType?.includes(\"application/zip\")) {\n return \"#fpx.zip\";\n }\n if (contentType?.includes(\"audio/\")) {\n return \"#fpx.audio\";\n }\n if (contentType?.includes(\"video/\")) {\n return \"#fpx.video\";\n }\n if (\n contentType?.includes(\"application/octet-stream\") ||\n contentType?.includes(\"application/vnd.ms-excel\") ||\n contentType?.includes(\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n ) ||\n contentType?.includes(\"application/vnd.ms-powerpoint\") ||\n contentType?.includes(\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n ) ||\n contentType?.includes(\"application/msword\") ||\n contentType?.includes(\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n )\n ) {\n return \"#fpx.binary\";\n }\n\n try {\n return await response.text();\n } catch {\n return null;\n }\n}\n\nexport async function getResponseAttributes(\n response: GlobalResponse | HonoResponse,\n) {\n const attributes: Attributes = {\n [EXTRA_SEMATTRS_HTTP_RESPONSE_STATUS_CODE]: String(response.status),\n [SEMATTRS_HTTP_SCHEME]: response.url.split(\":\")[0],\n };\n\n const responseText = await tryGetResponseBodyAsText(response);\n if (responseText) {\n attributes[FPX_RESPONSE_BODY] = responseText;\n }\n\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength) {\n attributes[SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH] = contentLength;\n }\n\n const headers = response.headers;\n const responseHeaders = headersToObject(headers);\n for (const [key, value] of Object.entries(responseHeaders)) {\n attributes[`http.response.header.${key}`] = value;\n }\n\n return attributes;\n}\n", "/**\n * SEMATTRS_* are constants that should actually be exposed by the Samantic Conventions package\n * but are not.\n */\nexport const EXTRA_SEMATTRS_HTTP_REQUEST_METHOD = \"http.request.method\";\nexport const EXTRA_SEMATTRS_HTTP_RESPONSE_STATUS_CODE =\n \"http.response.status_code\";\nexport const EXTRA_SEMATTRS_URL_FULL = \"url.full\";\n\nexport const FPX_REQUEST_PATHNAME = \"fpx.http.request.pathname\";\nexport const FPX_REQUEST_SEARCH = \"fpx.http.request.search\";\nexport const FPX_REQUEST_SCHEME = \"fpx.http.request.scheme\";\nexport const FPX_REQUEST_BODY = \"fpx.http.request.body\";\nexport const FPX_REQUEST_ENV = \"fpx.http.request.env\";\n\nexport const FPX_RESPONSE_BODY = \"fpx.http.response.body\";\n\nexport const CF_BINDING_TYPE = \"cf.binding.type\";\nexport const CF_BINDING_NAME = \"cf.binding.name\";\nexport const CF_BINDING_METHOD = \"cf.binding.method\";\nexport const CF_BINDING_RESULT = \"cf.binding.result\";\nexport const CF_BINDING_ERROR = \"cf.binding.error\";\n\n// NOT YET IMPLEMENTED\nexport const FPX_REQUEST_HANDLER_FILE = \"fpx.http.request.handler.file\";\nexport const FPX_REQUEST_HANDLER_SOURCE_CODE =\n \"fpx.http.request.handler.source_code\";\n", "export function isWrapped(func: unknown) {\n return (\n typeof func === \"function\" && \"__wrapped\" in func && func.__wrapped === true\n );\n}\n", "import { trace } from \"@opentelemetry/api\";\nimport shimmer from \"shimmer\";\nimport {\n errorToJson,\n isLikelyNeonDbError,\n isWrapped,\n neonDbErrorToJson,\n safelySerializeJSON,\n} from \"../utils\";\n\nconst { wrap } = shimmer;\n\ntype DEBUG = \"debug\";\ntype LOG = \"log\";\ntype INFO = \"info\";\ntype WARN = \"warn\";\ntype ERROR = \"error\";\n\ntype LEVELS = LOG | INFO | WARN | ERROR | DEBUG;\n\nexport function patchConsole() {\n patchMethod(\"debug\", \"debug\");\n patchMethod(\"log\", \"info\");\n patchMethod(\"warn\", \"warn\");\n patchMethod(\"error\", \"error\");\n}\n\nfunction patchMethod(methodName: LEVELS, level: string) {\n // Check if the function is already patched\n // If it is, we don't want to patch it again\n if (isWrapped(console[methodName])) {\n return;\n }\n\n wrap(console, methodName, (original) => {\n // NOTE - Original message needs to be typed as `string` to be compatible with the original method,\n // but in fact it is `unknown`.\n // People pass non-string arguments to console.log all the time.\n return (originalMessage: string, ...args: unknown[]) => {\n const span = trace.getActiveSpan();\n\n if (span) {\n const { message, messageType } = serializeLogMessage(originalMessage);\n\n span.addEvent(\"log\", {\n message: message,\n messageType,\n level,\n arguments: safelySerializeJSON(args?.map(transformLogMessage)),\n });\n }\n\n // IMPORTANT - We need to return the original message, otherwise the console method will not work as expected\n return original(originalMessage, ...args);\n };\n });\n}\n\n/**\n * Helper that takes the first argument to a log method and transforms it into a string\n * that can be logged.\n *\n * Also returns `messageType` to be used in the log event, as a hint to the UI.\n */\nfunction serializeLogMessage(rawMessage: unknown) {\n const messageType = rawMessage === null ? \"null\" : typeof rawMessage;\n const transformedMessage = transformLogMessage(rawMessage);\n const stringifiedMessage =\n transformedMessage === \"string\"\n ? transformedMessage\n : safelySerializeJSON(transformedMessage);\n\n return {\n message: stringifiedMessage,\n messageType,\n };\n}\n\n/**\n * Helper that takes a log message and transforms it into something that\n * hopefully can be stringified (into JSON), we don't lose information on\n * what was logged.\n *\n * The reason this is necessary is because Error objects do not\n * serialize well to JSON.\n *\n * Also NeonDbErrors do not extend the Error class, so they need their own handling.\n */\nfunction transformLogMessage(message: unknown) {\n if (isLikelyNeonDbError(message)) {\n return neonDbErrorToJson(message);\n }\n\n if (message instanceof Error) {\n return errorToJson(message);\n }\n\n return message;\n}\n", "/**\n * This returns a proxy-ed ExecutionContext which has a waitUntil method that\n * collects promises passed to it. It also returns an array of promises that\n */\nexport function patchWaitUntil(context: ExecutionContext) {\n const promises: Promise[] = [];\n\n const proxyContext = new Proxy(context, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (prop === \"waitUntil\" && typeof value === \"function\") {\n const original: ExecutionContext[\"waitUntil\"] = value;\n return function waitUntil(this: unknown, promise: Promise) {\n const scope = this === receiver ? target : this;\n promises.push(promise);\n return original.apply(scope, [promise]);\n };\n }\n\n return value;\n },\n });\n\n return { proxyContext, promises };\n}\n", "import type { Span } from \"@opentelemetry/api\";\nimport {\n CF_BINDING_ERROR,\n CF_BINDING_METHOD,\n CF_BINDING_NAME,\n CF_BINDING_RESULT,\n CF_BINDING_TYPE,\n} from \"../constants\";\nimport { measure } from \"../measure\";\nimport { errorToJson, isUintArray, safelySerializeJSON } from \"../utils\";\n\n/**\n * A key used to mark objects as proxied by us, so that we don't proxy them again.\n *\n * @internal\n */\nconst IS_PROXIED_KEY = \"__fpx_proxied\";\n\n/**\n * Patch Cloudflare bindings to add instrumentation\n *\n * @param env - The environment for the worker, which may contain Cloudflare bindings\n */\nexport function patchCloudflareBindings(\n env?: Record | null,\n) {\n const envKeys = env ? Object.keys(env) : [];\n for (const bindingName of envKeys) {\n // Skip any environment variables that are not objects,\n // since they can't be bindings\n const envValue = env?.[bindingName];\n if (!envValue || typeof envValue !== \"object\") {\n continue;\n }\n\n env[bindingName] = patchCloudflareBinding(envValue, bindingName);\n }\n}\n\n/**\n * Proxy a Cloudflare binding to add instrumentation.\n * For now, just wraps all functions on the binding to use a measured version of the function.\n *\n * For R2, we could still specifically proxy and add smarts for:\n * - createMultipartUpload\n * - resumeMultipartUpload\n *\n * @param o - The binding to proxy\n * @param bindingName - The name of the binding in the environment, e.g., \"AI\" or \"AVATARS_BUCKET\"\n *\n * @returns A proxied binding\n */\nfunction patchCloudflareBinding(o: object, bindingName: string) {\n if (!isCloudflareBinding(o)) {\n return o;\n }\n\n if (isAlreadyProxied(o)) {\n return o;\n }\n\n // HACK - Special logic for D1, since we only really care about the `_send` and `_sendOrThrow` methods,\n // not about the `prepare`, etc, methods.\n if (isCloudflareD1Binding(o)) {\n return proxyD1Binding(o, bindingName);\n }\n\n const proxiedBinding = new Proxy(o, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n const methodName = String(prop);\n\n // OPTIMIZE - Do we want to do these lookups / this wrapping every time the property is accessed?\n const bindingType = getConstructorName(target);\n\n // The name for the span, which will show up in the UI\n const name = `${bindingName}.${methodName}`;\n\n const measuredBinding = measure(\n {\n name,\n attributes: getCfBindingAttributes(\n bindingType,\n bindingName,\n methodName,\n ),\n onStart: (span, args) => {\n span.setAttributes({\n args: safelySerializeJSON(args),\n });\n },\n onSuccess: (span, result) => {\n addResultAttribute(span, result);\n },\n onError: handleError,\n },\n // OPTIMIZE - bind is expensive, can we avoid it?\n value.bind(target),\n );\n return measuredBinding;\n }\n\n return value;\n },\n });\n\n // We need to mark the binding as proxied so that we don't proxy it again in the future,\n // since Workers can re-use env vars across requests.\n markAsProxied(proxiedBinding);\n\n return proxiedBinding;\n}\n\n/**\n * Proxy a D1 binding to add instrumentation to database calls.\n *\n * In order to instrument the calls to the database itself, we need to proxy the `_send` and `_sendOrThrow` methods.\n * As of writing, the code that makes these calls is here:\n * https://github.com/cloudflare/workerd/blob/bee639d6c2ff41bfc1bd75a40c9d3c98724585ce/src/cloudflare/internal/d1-api.ts#L131\n *\n * @param o - The D1Database binding to proxy\n *\n * @returns A proxied binding, whose `.database._send` and `.database._sendOrThrow` methods are instrumented\n */\nfunction proxyD1Binding(o: object, bindingName: string) {\n if (!isCloudflareD1Binding(o)) {\n return o;\n }\n\n if (isAlreadyProxied(o)) {\n return o;\n }\n\n const d1Proxy = new Proxy(o, {\n get(d1Target, d1Prop) {\n const d1Method = String(d1Prop);\n const d1Value = Reflect.get(d1Target, d1Prop);\n // HACK - These are technically public methods on the database object,\n // but they have an underscore prefix which usually means \"private\" by convention.\n //\n const isSendingQuery =\n d1Method === \"_send\" || d1Method === \"_sendOrThrow\";\n if (typeof d1Value === \"function\" && isSendingQuery) {\n return measure(\n {\n name: \"D1 Call\",\n attributes: getCfBindingAttributes(\n \"D1Database\",\n bindingName,\n d1Method,\n ),\n onStart: (span, args) => {\n span.setAttributes({\n args: safelySerializeJSON(args),\n });\n },\n onSuccess: (span, result) => {\n addResultAttribute(span, result);\n },\n onError: handleError,\n },\n // OPTIMIZE - bind is expensive, can we avoid it?\n d1Value.bind(d1Target),\n );\n }\n\n return d1Value;\n },\n });\n\n markAsProxied(d1Proxy);\n\n return d1Proxy;\n}\n\n/**\n * Get the attributes for a Cloudflare binding\n *\n * @param bindingType - The type of the binding, e.g., \"D1Database\" or \"R2Bucket\"\n * @param bindingName - The name of the binding in the environment, e.g., \"AI\" or \"AVATARS_BUCKET\"\n * @param methodName - The name of the method being called on the binding, e.g., \"run\" or \"put\"\n *\n * @returns The attributes for the binding\n */\nfunction getCfBindingAttributes(\n bindingType: string,\n bindingName: string,\n methodName: string,\n) {\n return {\n [CF_BINDING_TYPE]: bindingType,\n [CF_BINDING_NAME]: bindingName,\n [CF_BINDING_METHOD]: methodName,\n };\n}\n\n/**\n * Add \"cf.binding.result\" attribute to a span\n *\n * @NOTE - The results of method calls could be so wildly different, and sometimes very large.\n * We should be more careful here with what we attribute to the span.\n * Also, might want to turn this off by default in production.\n *\n * @param span - The span to add the attribute to\n * @param result - The result to add to the span\n */\nfunction addResultAttribute(span: Span, result: unknown) {\n // HACK - Probably a smarter way to avoid serlializing massive amounts of binary data, but this works for now\n const isBinary = isUintArray(result);\n span.setAttributes({\n [CF_BINDING_RESULT]: isBinary ? \"binary\" : safelySerializeJSON(result),\n });\n}\n\n/**\n * Add \"cf.binding.error\" attribute to a span\n *\n * @param span - The span to add the attribute to\n * @param error - The error to add to the span\n */\nfunction handleError(span: Span, error: unknown) {\n const serializableError = error instanceof Error ? errorToJson(error) : error;\n const errorAttributes = {\n [CF_BINDING_ERROR]: safelySerializeJSON(serializableError),\n };\n span.setAttributes(errorAttributes);\n}\n\n// TODO - Remove this, it is temporary\nfunction isCloudflareBinding(o: unknown): o is object {\n return (\n isCloudflareAiBinding(o) ||\n isCloudflareR2Binding(o) ||\n isCloudflareD1Binding(o) ||\n isCloudflareKVBinding(o)\n );\n}\n\nfunction isCloudflareAiBinding(o: unknown) {\n const constructorName = getConstructorName(o);\n if (constructorName !== \"Ai\") {\n return false;\n }\n\n // TODO - Edge case, also check for `fetcher` and other known properties on this binding, in case the user is using another class named Ai (?)\n return true;\n}\n\nfunction isCloudflareR2Binding(o: unknown) {\n const constructorName = getConstructorName(o);\n if (constructorName !== \"R2Bucket\") {\n return false;\n }\n\n // TODO - Edge case, also check for `list`, `delete`, and other known methods on this binding, in case the user is using another class named R2Bucket (?)\n return true;\n}\n\nfunction isCloudflareD1Binding(o: unknown) {\n const constructorName = getConstructorName(o);\n if (constructorName !== \"D1Database\") {\n return false;\n }\n\n return true;\n}\n\nfunction isCloudflareKVBinding(o: unknown) {\n const constructorName = getConstructorName(o);\n if (constructorName !== \"KvNamespace\") {\n return false;\n }\n\n return true;\n}\n\n/**\n * Get the constructor name of an object\n *\n * Helps us detect Cloudflare bindings\n *\n * @param o - The object to get the constructor name of\n * @returns The constructor name\n *\n * Example:\n * ```ts\n * const o = new Ai();\n * getConstructorName(o); // \"Ai\"\n * ```\n */\nfunction getConstructorName(o: unknown) {\n return Object.getPrototypeOf(o).constructor.name;\n}\n\n/**\n * Check if a Cloudflare binding is already proxied by us\n *\n * @param o - The binding to check\n * @returns `true` if the binding is already proxied, `false` otherwise\n */\nfunction isAlreadyProxied(o: object) {\n if (IS_PROXIED_KEY in o) {\n return !!o[IS_PROXIED_KEY];\n }\n\n return false;\n}\n\n/**\n * Mark a Cloudflare binding as proxied by us, so that we don't proxy it again\n *\n * @param o - The binding to mark\n */\nfunction markAsProxied(o: object) {\n Object.defineProperty(o, IS_PROXIED_KEY, {\n value: true,\n writable: true,\n configurable: true,\n });\n}\n", "import { context, propagation } from \"@opentelemetry/api\";\n\nexport function propagateFpxTraceId(request: Request) {\n // HACK - We need to extract the traceparent from the request headers\n // but we also need to set a dummy traceparent in the case that\n // we are receiving an explicit trace-id to use from FPX.\n //\n // Extract fpx trace ID from request headers (if it exists)\n // and set it as a dummy active context\n //\n // TODO - Validate the id here using an otel helper, and warn if it is invalid\n const traceId = request.headers.get(\"x-fpx-trace-id\");\n\n let activeContext = context.active();\n if (traceId) {\n activeContext = propagation.extract(context.active(), {\n traceparent: createTraceparentHeader(traceId),\n });\n } else {\n activeContext = propagation.extract(context.active(), request.headers);\n }\n\n return activeContext;\n}\n\n/**\n * Creates a traceparent header with a random span id\n *\n * @param traceId - The trace id to use in the traceparent header\n * @returns A traceparent header\n */\nfunction createTraceparentHeader(traceId: string): string {\n const version = \"00\"; // Version of the traceparent header\n\n // NOTE - A dummy span id like the following will be rejected by trace propagation API\n // Look in the otel codebase for their regex - it filters out anything that's just 0 repeating\n //\n // const spanId = '0000000000000000'; // Dummy span ID\n //\n // HACK - Generate a random span id so we can spoof a proper trace parent\n //\n const spanId = generateSpanId();\n const traceFlags = \"01\"; // Trace flags (01 means sampled)\n\n return `${version}-${traceId}-${spanId}-${traceFlags}`;\n}\n\n/**\n * Generates a random 16-character hex string that is not all zeros\n *\n * @returns A random 16-character hex string\n */\nfunction generateSpanId(): string {\n let spanId: string;\n do {\n spanId = [...Array(16)]\n .map(() => Math.floor(Math.random() * 16).toString(16))\n .join(\"\");\n } while (/^[0]{16}$/.test(spanId));\n return spanId;\n}\n", "import type { HonoLikeApp } from \"./types\";\n\ntype FetchFn = typeof fetch;\n\n/**\n * TODO - In production, we should make sure this request has some sort of repudiation\n * We only want to respond like this when we know the request came from the service\n * and not from a random user.\n */\nexport function isRouteInspectorRequest(request: Request) {\n return !!request.headers.get(\"X-Fpx-Route-Inspector\");\n}\n\n/**\n * Responds to the route inspector request by sending the routes to the FPX service.\n *\n * @param fetchFn - The fetch function to use to send the request.\n * @param fpxEndpoint - The endpoint of the FPX service.\n * @param app - The Hono app to get the routes from.\n * @returns\n */\nexport function respondWithRoutes(\n fetchFn: FetchFn,\n fpxEndpoint: string,\n app: HonoLikeApp,\n) {\n const routes = getRoutesFromApp(app) ?? [];\n\n try {\n // HACK - Construct the routes endpoint here\n // We could also do what we did before and submit the routes to the same `/v1/traces`\n // but that route handler is so chaotic right now I wanted to have this as a separate\n // endpoint.\n const routesEndpoint = getRoutesEndpoint(fpxEndpoint);\n fetchFn(routesEndpoint.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ routes }),\n }).catch((_e) => {\n // NOTE - We're not awaiting this fetch, so we need to catch its errors\n // to avoid unhandled promise rejections.\n // TODO - Use a logger, or only log if library debugging is enabled\n // console.error(\"Error sending routes to FPX\", e);\n });\n } catch (_e) {\n // TODO - Use a logger, or only log if library debugging is enabled\n // console.error(\"Error sending routes to FPX\", e);\n }\n\n return new Response(\"OK\");\n}\n\nfunction getRoutesFromApp(app: HonoLikeApp) {\n return app?.routes?.map((route) => ({\n method: route.method,\n path: route.path,\n handler: route.handler.toString(),\n handlerType: route.handler.length < 2 ? \"route\" : \"middleware\",\n }));\n}\n\nfunction getRoutesEndpoint(fpxEndpoint: string) {\n const routesEndpoint = new URL(fpxEndpoint);\n routesEndpoint.pathname = \"/v0/probed-routes\";\n return routesEndpoint.toString();\n}\n", "// src/index.ts\nimport { Hono } from \"./hono.js\";\nexport {\n Hono\n};\n", "// src/hono.ts\nimport { HonoBase } from \"./hono-base.js\";\nimport { RegExpRouter } from \"./router/reg-exp-router/index.js\";\nimport { SmartRouter } from \"./router/smart-router/index.js\";\nimport { TrieRouter } from \"./router/trie-router/index.js\";\nvar Hono = class extends HonoBase {\n constructor(options = {}) {\n super(options);\n this.router = options.router ?? new SmartRouter({\n routers: [new RegExpRouter(), new TrieRouter()]\n });\n }\n};\nexport {\n Hono\n};\n", "// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar COMPOSED_HANDLER = Symbol(\"composedHandler\");\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n return err.getResponse();\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class {\n get;\n post;\n put;\n delete;\n options;\n patch;\n all;\n on;\n use;\n router;\n getPath;\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n if (typeof handler !== \"string\") {\n this.addRoute(method, this.#path, handler);\n }\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const strict = options.strict ?? true;\n delete options.strict;\n Object.assign(this, options);\n this.getPath = strict ? options.getPath ?? getPath : getPathNoStrict;\n }\n clone() {\n const clone = new Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.routes = this.routes;\n return clone;\n }\n notFoundHandler = notFoundHandler;\n errorHandler = errorHandler;\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.addRoute(r.method, r.path, handler);\n });\n return this;\n }\n basePath(path) {\n const subApp = this.clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n notFound = (handler) => {\n this.notFoundHandler = handler;\n return this;\n };\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n replaceRequest = options.replaceRequest;\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = url.pathname.slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n addRoute(method, path, handler) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = { path, method, handler };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n matchRoute(method, path) {\n return this.router.match(method, path);\n }\n handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.matchRoute(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.notFoundHandler(c);\n });\n } catch (err) {\n return this.handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.notFoundHandler(c))\n ).catch((err) => this.handleError(err, c)) : res ?? this.notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.handleError(err, c);\n }\n })();\n }\n fetch = (request, ...rest) => {\n return this.dispatch(request, rest[1], rest[0], request.method);\n };\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n if (requestInit !== void 0) {\n input = new Request(input, requestInit);\n }\n return this.fetch(input, Env, executionCtx);\n }\n input = input.toString();\n const path = /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`;\n const req = new Request(path, requestInit);\n return this.fetch(req, Env, executionCtx);\n };\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n COMPOSED_HANDLER,\n Hono as HonoBase\n};\n", "// src/compose.ts\nimport { Context } from \"./context.js\";\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n if (context instanceof Context) {\n context.req.routeIndex = i;\n }\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (!handler) {\n if (context instanceof Context && context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n } else {\n try {\n res = await handler(context, () => {\n return dispatch(i + 1);\n });\n } catch (err) {\n if (err instanceof Error && context instanceof Context && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n", "// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setHeaders = (headers, map = {}) => {\n Object.entries(map).forEach(([key, value]) => headers.set(key, value));\n return headers;\n};\nvar Context = class {\n #rawRequest;\n #req;\n env = {};\n #var;\n finalized = false;\n error;\n #status = 200;\n #executionCtx;\n #headers;\n #preparedHeaders;\n #res;\n #isFresh = true;\n #layout;\n #renderer;\n #notFoundHandler;\n #matchResult;\n #path;\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n get res() {\n this.#isFresh = false;\n return this.#res ||= new Response(\"404 Not Found\", { status: 404 });\n }\n set res(_res) {\n this.#isFresh = false;\n if (this.#res && _res) {\n try {\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n } catch (e) {\n if (e instanceof TypeError && e.message.includes(\"immutable\")) {\n this.res = new Response(_res.body, {\n headers: _res.headers,\n status: _res.status\n });\n return;\n } else {\n throw e;\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n setLayout = (layout) => this.#layout = layout;\n getLayout = () => this.#layout;\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n header = (name, value, options) => {\n if (value === void 0) {\n if (this.#headers) {\n this.#headers.delete(name);\n } else if (this.#preparedHeaders) {\n delete this.#preparedHeaders[name.toLocaleLowerCase()];\n }\n if (this.finalized) {\n this.res.headers.delete(name);\n }\n return;\n }\n if (options?.append) {\n if (!this.#headers) {\n this.#isFresh = false;\n this.#headers = new Headers(this.#preparedHeaders);\n this.#preparedHeaders = {};\n }\n this.#headers.append(name, value);\n } else {\n if (this.#headers) {\n this.#headers.set(name, value);\n } else {\n this.#preparedHeaders ??= {};\n this.#preparedHeaders[name.toLowerCase()] = value;\n }\n }\n if (this.finalized) {\n if (options?.append) {\n this.res.headers.append(name, value);\n } else {\n this.res.headers.set(name, value);\n }\n }\n };\n status = (status) => {\n this.#isFresh = false;\n this.#status = status;\n };\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n newResponse = (data, arg, headers) => {\n if (this.#isFresh && !headers && !arg && this.#status === 200) {\n return new Response(data, {\n headers: this.#preparedHeaders\n });\n }\n if (arg && typeof arg !== \"number\") {\n const header = new Headers(arg.headers);\n if (this.#headers) {\n this.#headers.forEach((v, k) => {\n if (k === \"set-cookie\") {\n header.append(k, v);\n } else {\n header.set(k, v);\n }\n });\n }\n const headers2 = setHeaders(header, this.#preparedHeaders);\n return new Response(data, {\n headers: headers2,\n status: arg.status ?? this.#status\n });\n }\n const status = typeof arg === \"number\" ? arg : this.#status;\n this.#preparedHeaders ??= {};\n this.#headers ??= new Headers();\n setHeaders(this.#headers, this.#preparedHeaders);\n if (this.#res) {\n this.#res.headers.forEach((v, k) => {\n if (k === \"set-cookie\") {\n this.#headers?.append(k, v);\n } else {\n this.#headers?.set(k, v);\n }\n });\n setHeaders(this.#headers, this.#preparedHeaders);\n }\n headers ??= {};\n for (const [k, v] of Object.entries(headers)) {\n if (typeof v === \"string\") {\n this.#headers.set(k, v);\n } else {\n this.#headers.delete(k);\n for (const v2 of v) {\n this.#headers.append(k, v2);\n }\n }\n }\n return new Response(data, {\n status,\n headers: this.#headers\n });\n };\n body = (data, arg, headers) => {\n return typeof arg === \"number\" ? this.newResponse(data, arg, headers) : this.newResponse(data, arg);\n };\n text = (text, arg, headers) => {\n if (!this.#preparedHeaders) {\n if (this.#isFresh && !headers && !arg) {\n return new Response(text);\n }\n this.#preparedHeaders = {};\n }\n this.#preparedHeaders[\"content-type\"] = TEXT_PLAIN;\n return typeof arg === \"number\" ? this.newResponse(text, arg, headers) : this.newResponse(text, arg);\n };\n json = (object, arg, headers) => {\n const body = JSON.stringify(object);\n this.#preparedHeaders ??= {};\n this.#preparedHeaders[\"content-type\"] = \"application/json; charset=UTF-8\";\n return typeof arg === \"number\" ? this.newResponse(body, arg, headers) : this.newResponse(body, arg);\n };\n html = (html, arg, headers) => {\n this.#preparedHeaders ??= {};\n this.#preparedHeaders[\"content-type\"] = \"text/html; charset=UTF-8\";\n if (typeof html === \"object\") {\n return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html2) => {\n return typeof arg === \"number\" ? this.newResponse(html2, arg, headers) : this.newResponse(html2, arg);\n });\n }\n return typeof arg === \"number\" ? this.newResponse(html, arg, headers) : this.newResponse(html, arg);\n };\n redirect = (location, status) => {\n this.#headers ??= new Headers();\n this.#headers.set(\"Location\", location);\n return this.newResponse(null, status ?? 302);\n };\n notFound = () => {\n this.#notFoundHandler ??= () => new Response();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n", "// src/request.ts\nimport { parseBody } from \"./utils/body.js\";\nimport { decodeURIComponent_, getQueryParam, getQueryParams } from \"./utils/url.js\";\nvar HonoRequest = class {\n raw;\n #validatedData;\n #matchResult;\n routeIndex = 0;\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n this.#validatedData = {};\n }\n param(key) {\n return key ? this.getDecodedParam(key) : this.getAllDecodedParams();\n }\n getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex][1][key];\n const param = this.getParamValue(paramKey);\n return param ? /\\%/.test(param) ? decodeURIComponent_(param) : param : void 0;\n }\n getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);\n for (const key of keys) {\n const value = this.getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value && typeof value === \"string\") {\n decoded[key] = /\\%/.test(value) ? decodeURIComponent_(value) : value;\n }\n }\n return decoded;\n }\n getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name.toLowerCase()) ?? void 0;\n }\n const headerData = {};\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return this.bodyCache.parsedBody ??= await parseBody(this, options);\n }\n cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n const anyCachedKey = Object.keys(bodyCache)[0];\n if (anyCachedKey) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n json() {\n return this.cachedBody(\"json\");\n }\n text() {\n return this.cachedBody(\"text\");\n }\n arrayBuffer() {\n return this.cachedBody(\"arrayBuffer\");\n }\n blob() {\n return this.cachedBody(\"blob\");\n }\n formData() {\n return this.cachedBody(\"formData\");\n }\n addValidatedData(target, data) {\n this.#validatedData[target] = data;\n }\n valid(target) {\n return this.#validatedData[target];\n }\n get url() {\n return this.raw.url;\n }\n get method() {\n return this.raw.method;\n }\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nexport {\n HonoRequest\n};\n", "// src/utils/body.ts\nimport { HonoRequest } from \"../request.js\";\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;\n const contentType = headers.get(\"Content-Type\");\n if (contentType?.startsWith(\"multipart/form-data\") || contentType?.startsWith(\"application/x-www-form-urlencoded\")) {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n const formData = await request.formData();\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n form[key] = value;\n }\n};\nvar handleParsingNestedValues = (form, key, value) => {\n let nestedForm = form;\n const keys = key.split(\".\");\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nexport {\n parseBody\n};\n", "// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n if (!patternCache[label]) {\n if (match[2]) {\n patternCache[label] = [label, match[1], new RegExp(\"^\" + match[2] + \"$\")];\n } else {\n patternCache[label] = [label, match[1], true];\n }\n }\n return patternCache[label];\n }\n return null;\n};\nvar tryDecodeURI = (str) => {\n try {\n return decodeURI(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decodeURI(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", 8);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n return queryIndex === -1 ? \"\" : \"?\" + url.slice(queryIndex + 1);\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result[result.length - 1] === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (...paths) => {\n let p = \"\";\n let endsWithSlash = false;\n for (let path of paths) {\n if (p[p.length - 1] === \"/\") {\n p = p.slice(0, -1);\n endsWithSlash = true;\n }\n if (path[0] !== \"/\") {\n path = `/${path}`;\n }\n if (path === \"/\" && endsWithSlash) {\n p = `${p}/`;\n } else if (path !== \"/\") {\n p = `${p}${path}`;\n }\n if (path === \"/\" && p === \"\") {\n p = \"/\";\n }\n }\n return p;\n};\nvar checkOptionalParameter = (path) => {\n if (!path.match(/\\:.+\\?$/)) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (/\\?/.test(segment)) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.replace(\"?\", \"\");\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar _decodeURI = (value) => {\n if (!/[%+]/.test(value)) {\n return value;\n }\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return /%/.test(value) ? decodeURIComponent_(value) : value;\n};\nvar _getQueryParam = (url, key, multiple) => {\n let encoded;\n if (!multiple && key && !/[%+]/.test(key)) {\n let keyIndex2 = url.indexOf(`?${key}`, 8);\n if (keyIndex2 === -1) {\n keyIndex2 = url.indexOf(`&${key}`, 8);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = {};\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath\n};\n", "// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n", "// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n", "// src/router/reg-exp-router/index.ts\nimport { RegExpRouter } from \"./router.js\";\nexport {\n RegExpRouter\n};\n", "// src/router/reg-exp-router/router.ts\nimport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHOD_NAME_ALL,\n UnsupportedPathError\n} from \"../../router.js\";\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { PATH_ERROR } from \"./node.js\";\nimport { Trie } from \"./trie.js\";\nvar emptyParam = [];\nvar nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];\nvar wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\nfunction buildWildcardRegExp(path) {\n return wildcardRegExpCache[path] ??= new RegExp(\n path === \"*\" ? \"\" : `^${path.replace(\n /\\/\\*$|([.\\\\+*[^\\]$()])/g,\n (_, metaChar) => metaChar ? `\\\\${metaChar}` : \"(?:|/.*)\"\n )}$`\n );\n}\nfunction clearWildcardRegExpCache() {\n wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\n}\nfunction buildMatcherFromPreprocessedRoutes(routes) {\n const trie = new Trie();\n const handlerData = [];\n if (routes.length === 0) {\n return nullMatcher;\n }\n const routesWithStaticPathFlag = routes.map(\n (route) => [!/\\*|\\/:/.test(route[0]), ...route]\n ).sort(\n ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length\n );\n const staticMap = /* @__PURE__ */ Object.create(null);\n for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {\n const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];\n if (pathErrorCheckOnly) {\n staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];\n } else {\n j++;\n }\n let paramAssoc;\n try {\n paramAssoc = trie.insert(path, j, pathErrorCheckOnly);\n } catch (e) {\n throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;\n }\n if (pathErrorCheckOnly) {\n continue;\n }\n handlerData[j] = handlers.map(([h, paramCount]) => {\n const paramIndexMap = /* @__PURE__ */ Object.create(null);\n paramCount -= 1;\n for (; paramCount >= 0; paramCount--) {\n const [key, value] = paramAssoc[paramCount];\n paramIndexMap[key] = value;\n }\n return [h, paramIndexMap];\n });\n }\n const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();\n for (let i = 0, len = handlerData.length; i < len; i++) {\n for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {\n const map = handlerData[i][j]?.[1];\n if (!map) {\n continue;\n }\n const keys = Object.keys(map);\n for (let k = 0, len3 = keys.length; k < len3; k++) {\n map[keys[k]] = paramReplacementMap[map[keys[k]]];\n }\n }\n }\n const handlerMap = [];\n for (const i in indexReplacementMap) {\n handlerMap[i] = handlerData[indexReplacementMap[i]];\n }\n return [regexp, handlerMap, staticMap];\n}\nfunction findMiddleware(middleware, path) {\n if (!middleware) {\n return void 0;\n }\n for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {\n if (buildWildcardRegExp(k).test(path)) {\n return [...middleware[k]];\n }\n }\n return void 0;\n}\nvar RegExpRouter = class {\n name = \"RegExpRouter\";\n middleware;\n routes;\n constructor() {\n this.middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n this.routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n }\n add(method, path, handler) {\n const { middleware, routes } = this;\n if (!middleware || !routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n if (!middleware[method]) {\n ;\n [middleware, routes].forEach((handlerMap) => {\n handlerMap[method] = /* @__PURE__ */ Object.create(null);\n Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {\n handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];\n });\n });\n }\n if (path === \"/*\") {\n path = \"*\";\n }\n const paramCount = (path.match(/\\/:/g) || []).length;\n if (/\\*$/.test(path)) {\n const re = buildWildcardRegExp(path);\n if (method === METHOD_NAME_ALL) {\n Object.keys(middleware).forEach((m) => {\n middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n });\n } else {\n middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n }\n Object.keys(middleware).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(middleware[m]).forEach((p) => {\n re.test(p) && middleware[m][p].push([handler, paramCount]);\n });\n }\n });\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(routes[m]).forEach(\n (p) => re.test(p) && routes[m][p].push([handler, paramCount])\n );\n }\n });\n return;\n }\n const paths = checkOptionalParameter(path) || [path];\n for (let i = 0, len = paths.length; i < len; i++) {\n const path2 = paths[i];\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n routes[m][path2] ||= [\n ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []\n ];\n routes[m][path2].push([handler, paramCount - len + i + 1]);\n }\n });\n }\n }\n match(method, path) {\n clearWildcardRegExpCache();\n const matchers = this.buildAllMatchers();\n this.match = (method2, path2) => {\n const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];\n const staticMatch = matcher[2][path2];\n if (staticMatch) {\n return staticMatch;\n }\n const match = path2.match(matcher[0]);\n if (!match) {\n return [[], emptyParam];\n }\n const index = match.indexOf(\"\", 1);\n return [matcher[1][index], match];\n };\n return this.match(method, path);\n }\n buildAllMatchers() {\n const matchers = /* @__PURE__ */ Object.create(null);\n [...Object.keys(this.routes), ...Object.keys(this.middleware)].forEach((method) => {\n matchers[method] ||= this.buildMatcher(method);\n });\n this.middleware = this.routes = void 0;\n return matchers;\n }\n buildMatcher(method) {\n const routes = [];\n let hasOwnRoute = method === METHOD_NAME_ALL;\n [this.middleware, this.routes].forEach((r) => {\n const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];\n if (ownRoute.length !== 0) {\n hasOwnRoute ||= true;\n routes.push(...ownRoute);\n } else if (method !== METHOD_NAME_ALL) {\n routes.push(\n ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])\n );\n }\n });\n if (!hasOwnRoute) {\n return null;\n } else {\n return buildMatcherFromPreprocessedRoutes(routes);\n }\n }\n};\nexport {\n RegExpRouter\n};\n", "// src/router/reg-exp-router/node.ts\nvar LABEL_REG_EXP_STR = \"[^/]+\";\nvar ONLY_WILDCARD_REG_EXP_STR = \".*\";\nvar TAIL_WILDCARD_REG_EXP_STR = \"(?:|/.*)\";\nvar PATH_ERROR = Symbol();\nvar regExpMetaChars = new Set(\".\\\\+*[^]$()\");\nfunction compareKey(a, b) {\n if (a.length === 1) {\n return b.length === 1 ? a < b ? -1 : 1 : -1;\n }\n if (b.length === 1) {\n return 1;\n }\n if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {\n return 1;\n } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {\n return -1;\n }\n if (a === LABEL_REG_EXP_STR) {\n return 1;\n } else if (b === LABEL_REG_EXP_STR) {\n return -1;\n }\n return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;\n}\nvar Node = class {\n index;\n varIndex;\n children = /* @__PURE__ */ Object.create(null);\n insert(tokens, index, paramMap, context, pathErrorCheckOnly) {\n if (tokens.length === 0) {\n if (this.index !== void 0) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n this.index = index;\n return;\n }\n const [token, ...restTokens] = tokens;\n const pattern = token === \"*\" ? restTokens.length === 0 ? [\"\", \"\", ONLY_WILDCARD_REG_EXP_STR] : [\"\", \"\", LABEL_REG_EXP_STR] : token === \"/*\" ? [\"\", \"\", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n let node;\n if (pattern) {\n const name = pattern[1];\n let regexpStr = pattern[2] || LABEL_REG_EXP_STR;\n if (name && pattern[2]) {\n regexpStr = regexpStr.replace(/^\\((?!\\?:)(?=[^)]+\\)$)/, \"(?:\");\n if (/\\((?!\\?:)/.test(regexpStr)) {\n throw PATH_ERROR;\n }\n }\n node = this.children[regexpStr];\n if (!node) {\n if (Object.keys(this.children).some(\n (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.children[regexpStr] = new Node();\n if (name !== \"\") {\n node.varIndex = context.varIndex++;\n }\n }\n if (!pathErrorCheckOnly && name !== \"\") {\n paramMap.push([name, node.varIndex]);\n }\n } else {\n node = this.children[token];\n if (!node) {\n if (Object.keys(this.children).some(\n (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.children[token] = new Node();\n }\n }\n node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);\n }\n buildRegExpStr() {\n const childKeys = Object.keys(this.children).sort(compareKey);\n const strList = childKeys.map((k) => {\n const c = this.children[k];\n return (typeof c.varIndex === \"number\" ? `(${k})@${c.varIndex}` : regExpMetaChars.has(k) ? `\\\\${k}` : k) + c.buildRegExpStr();\n });\n if (typeof this.index === \"number\") {\n strList.unshift(`#${this.index}`);\n }\n if (strList.length === 0) {\n return \"\";\n }\n if (strList.length === 1) {\n return strList[0];\n }\n return \"(?:\" + strList.join(\"|\") + \")\";\n }\n};\nexport {\n Node,\n PATH_ERROR\n};\n", "// src/router/reg-exp-router/trie.ts\nimport { Node } from \"./node.js\";\nvar Trie = class {\n context = { varIndex: 0 };\n root = new Node();\n insert(path, index, pathErrorCheckOnly) {\n const paramAssoc = [];\n const groups = [];\n for (let i = 0; ; ) {\n let replaced = false;\n path = path.replace(/\\{[^}]+\\}/g, (m) => {\n const mark = `@\\\\${i}`;\n groups[i] = [mark, m];\n i++;\n replaced = true;\n return mark;\n });\n if (!replaced) {\n break;\n }\n }\n const tokens = path.match(/(?::[^\\/]+)|(?:\\/\\*$)|./g) || [];\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = tokens.length - 1; j >= 0; j--) {\n if (tokens[j].indexOf(mark) !== -1) {\n tokens[j] = tokens[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n this.root.insert(tokens, index, paramAssoc, this.context, pathErrorCheckOnly);\n return paramAssoc;\n }\n buildRegExp() {\n let regexp = this.root.buildRegExpStr();\n if (regexp === \"\") {\n return [/^$/, [], []];\n }\n let captureIndex = 0;\n const indexReplacementMap = [];\n const paramReplacementMap = [];\n regexp = regexp.replace(/#(\\d+)|@(\\d+)|\\.\\*\\$/g, (_, handlerIndex, paramIndex) => {\n if (typeof handlerIndex !== \"undefined\") {\n indexReplacementMap[++captureIndex] = Number(handlerIndex);\n return \"$()\";\n }\n if (typeof paramIndex !== \"undefined\") {\n paramReplacementMap[Number(paramIndex)] = ++captureIndex;\n return \"\";\n }\n return \"\";\n });\n return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];\n }\n};\nexport {\n Trie\n};\n", "// src/router/smart-router/index.ts\nimport { SmartRouter } from \"./router.js\";\nexport {\n SmartRouter\n};\n", "// src/router/smart-router/router.ts\nimport { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from \"../../router.js\";\nvar SmartRouter = class {\n name = \"SmartRouter\";\n routers = [];\n routes = [];\n constructor(init) {\n Object.assign(this, init);\n }\n add(method, path, handler) {\n if (!this.routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n this.routes.push([method, path, handler]);\n }\n match(method, path) {\n if (!this.routes) {\n throw new Error(\"Fatal error\");\n }\n const { routers, routes } = this;\n const len = routers.length;\n let i = 0;\n let res;\n for (; i < len; i++) {\n const router = routers[i];\n try {\n routes.forEach((args) => {\n router.add(...args);\n });\n res = router.match(method, path);\n } catch (e) {\n if (e instanceof UnsupportedPathError) {\n continue;\n }\n throw e;\n }\n this.match = router.match.bind(router);\n this.routers = [router];\n this.routes = void 0;\n break;\n }\n if (i === len) {\n throw new Error(\"Fatal error\");\n }\n this.name = `SmartRouter + ${this.activeRouter.name}`;\n return res;\n }\n get activeRouter() {\n if (this.routes || this.routers.length !== 1) {\n throw new Error(\"No active router has been determined yet.\");\n }\n return this.routers[0];\n }\n};\nexport {\n SmartRouter\n};\n", "// src/router/trie-router/index.ts\nimport { TrieRouter } from \"./router.js\";\nexport {\n TrieRouter\n};\n", "// src/router/trie-router/router.ts\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { Node } from \"./node.js\";\nvar TrieRouter = class {\n name = \"TrieRouter\";\n node;\n constructor() {\n this.node = new Node();\n }\n add(method, path, handler) {\n const results = checkOptionalParameter(path);\n if (results) {\n for (const p of results) {\n this.node.insert(method, p, handler);\n }\n return;\n }\n this.node.insert(method, path, handler);\n }\n match(method, path) {\n return this.node.search(method, path);\n }\n};\nexport {\n TrieRouter\n};\n", "// src/router/trie-router/node.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { getPattern, splitPath, splitRoutingPath } from \"../../utils/url.js\";\nvar Node = class {\n methods;\n children;\n patterns;\n order = 0;\n name;\n params = /* @__PURE__ */ Object.create(null);\n constructor(method, handler, children) {\n this.children = children || /* @__PURE__ */ Object.create(null);\n this.methods = [];\n this.name = \"\";\n if (method && handler) {\n const m = /* @__PURE__ */ Object.create(null);\n m[method] = { handler, possibleKeys: [], score: 0, name: this.name };\n this.methods = [m];\n }\n this.patterns = [];\n }\n insert(method, path, handler) {\n this.name = `${method} ${path}`;\n this.order = ++this.order;\n let curNode = this;\n const parts = splitRoutingPath(path);\n const possibleKeys = [];\n for (let i = 0, len = parts.length; i < len; i++) {\n const p = parts[i];\n if (Object.keys(curNode.children).includes(p)) {\n curNode = curNode.children[p];\n const pattern2 = getPattern(p);\n if (pattern2) {\n possibleKeys.push(pattern2[1]);\n }\n continue;\n }\n curNode.children[p] = new Node();\n const pattern = getPattern(p);\n if (pattern) {\n curNode.patterns.push(pattern);\n possibleKeys.push(pattern[1]);\n }\n curNode = curNode.children[p];\n }\n if (!curNode.methods.length) {\n curNode.methods = [];\n }\n const m = /* @__PURE__ */ Object.create(null);\n const handlerSet = {\n handler,\n possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),\n name: this.name,\n score: this.order\n };\n m[method] = handlerSet;\n curNode.methods.push(m);\n return curNode;\n }\n gHSets(node, method, nodeParams, params) {\n const handlerSets = [];\n for (let i = 0, len = node.methods.length; i < len; i++) {\n const m = node.methods[i];\n const handlerSet = m[method] || m[METHOD_NAME_ALL];\n const processedSet = /* @__PURE__ */ Object.create(null);\n if (handlerSet !== void 0) {\n handlerSet.params = /* @__PURE__ */ Object.create(null);\n handlerSet.possibleKeys.forEach((key) => {\n const processed = processedSet[handlerSet.name];\n handlerSet.params[key] = params[key] && !processed ? params[key] : nodeParams[key] ?? params[key];\n processedSet[handlerSet.name] = true;\n });\n handlerSets.push(handlerSet);\n }\n }\n return handlerSets;\n }\n search(method, path) {\n const handlerSets = [];\n this.params = /* @__PURE__ */ Object.create(null);\n const curNode = this;\n let curNodes = [curNode];\n const parts = splitPath(path);\n for (let i = 0, len = parts.length; i < len; i++) {\n const part = parts[i];\n const isLast = i === len - 1;\n const tempNodes = [];\n for (let j = 0, len2 = curNodes.length; j < len2; j++) {\n const node = curNodes[j];\n const nextNode = node.children[part];\n if (nextNode) {\n nextNode.params = node.params;\n if (isLast === true) {\n if (nextNode.children[\"*\"]) {\n handlerSets.push(\n ...this.gHSets(nextNode.children[\"*\"], method, node.params, /* @__PURE__ */ Object.create(null))\n );\n }\n handlerSets.push(...this.gHSets(nextNode, method, node.params, /* @__PURE__ */ Object.create(null)));\n } else {\n tempNodes.push(nextNode);\n }\n }\n for (let k = 0, len3 = node.patterns.length; k < len3; k++) {\n const pattern = node.patterns[k];\n const params = { ...node.params };\n if (pattern === \"*\") {\n const astNode = node.children[\"*\"];\n if (astNode) {\n handlerSets.push(...this.gHSets(astNode, method, node.params, /* @__PURE__ */ Object.create(null)));\n tempNodes.push(astNode);\n }\n continue;\n }\n if (part === \"\") {\n continue;\n }\n const [key, name, matcher] = pattern;\n const child = node.children[key];\n const restPathString = parts.slice(i).join(\"/\");\n if (matcher instanceof RegExp && matcher.test(restPathString)) {\n params[name] = restPathString;\n handlerSets.push(...this.gHSets(child, method, node.params, params));\n continue;\n }\n if (matcher === true || matcher instanceof RegExp && matcher.test(part)) {\n if (typeof key === \"string\") {\n params[name] = part;\n if (isLast === true) {\n handlerSets.push(...this.gHSets(child, method, params, node.params));\n if (child.children[\"*\"]) {\n handlerSets.push(...this.gHSets(child.children[\"*\"], method, params, node.params));\n }\n } else {\n child.params = params;\n tempNodes.push(child);\n }\n }\n }\n }\n }\n curNodes = tempNodes;\n }\n const results = handlerSets.sort((a, b) => {\n return a.score - b.score;\n });\n return [results.map(({ handler, params }) => [handler, params])];\n }\n};\nexport {\n Node\n};\n", "import { type Context, Hono } from \"hono\";\nimport { bearerAuth } from \"hono/bearer-auth\";\n\nimport { events, type EventInsert, repositories, users } from \"../db\";\nimport { githubApiMiddleware, githubWebhooksMiddleware } from \"../middleware\";\nimport type { HonoEnv } from \"../types\";\n\nconst api = new Hono();\n\napi.use(\"/github/*\", githubApiMiddleware);\napi.use(\"/github/webhook\", githubWebhooksMiddleware);\n\napi.post(\"/github/webhook\", async (c) => {\n const db = c.var.db;\n const webhooks = c.var.webhooks;\n const fetchUserById = c.var.fetchUserById;\n\n webhooks.on(\n [\"issues.opened\", \"star.created\", \"watch.started\"],\n async ({ payload, name }) => {\n const userId = payload.sender.id;\n\n try {\n await db\n .insert(repositories)\n .values({\n description: payload.repository.description,\n fullName: payload.repository.full_name,\n id: payload.repository.id,\n name: payload.repository.name,\n stargazersCount: payload.repository.stargazers_count,\n watchersCount: payload.repository.watchers_count,\n })\n .onConflictDoUpdate({\n target: repositories.id,\n set: {\n stargazersCount: payload.repository.stargazers_count,\n watchersCount: payload.repository.watchers_count,\n },\n });\n } catch (error) {\n return c.text(`Error fetching repository: ${error}`, 500);\n }\n\n try {\n const user = await fetchUserById(userId);\n\n await db\n .insert(users)\n .values({\n avatar: user.avatar_url,\n company: user.company,\n emailAddress: user.email,\n handle: user.login,\n id: user.id,\n location: user.location,\n name: user.name,\n twitterHandle: user.twitter_username,\n })\n .onConflictDoNothing({ target: users.id });\n } catch (error) {\n return c.text(`Error inserting user: ${error}`, 500);\n }\n\n // Only issues have an event ID\n let eventId: number | undefined;\n if (name === \"issues\") {\n eventId = payload.issue.id;\n }\n\n try {\n await db.insert(events).values({\n eventId,\n eventAction: payload.action,\n eventName: name,\n repoId: payload.repository.id,\n userId,\n });\n } catch (error) {\n return c.text(`Error inserting event: ${error}`, 500);\n }\n },\n );\n});\n\napi.get(\n // Params will be replaced by repo id once dashboard is implemented.\n \"/github/:owner/:repo\",\n bearerAuth({\n // Basic bearer token auth for now until the dashboard is implemented.\n verifyToken: async (token, c: Context) =>\n token === c.env.GITHUB_BEARER_TOKEN,\n }),\n async (c) => {\n const db = c.var.db;\n const fetchRepoWithUsersAndEvents = c.var.fetchRepoWithUsersAndEvents;\n const owner = c.req.param(\"owner\");\n const repo = c.req.param(\"repo\");\n\n const countQuery = c.req.query(\"count\");\n const count = countQuery ? Number.parseInt(countQuery, 10) : 50;\n\n try {\n const {\n id,\n fullName,\n name,\n stargazers,\n watchers,\n description,\n stargazersCount,\n } = await fetchRepoWithUsersAndEvents({\n count,\n owner,\n repo,\n });\n\n await db\n .insert(repositories)\n .values({\n fullName,\n id,\n name,\n description,\n stargazersCount,\n watchersCount: watchers.totalCount,\n })\n .onConflictDoNothing({\n target: repositories.id,\n });\n\n const usersWithInteractions = stargazers.users.concat(watchers.users);\n await db.insert(users).values(usersWithInteractions).onConflictDoNothing({\n target: users.id,\n });\n\n const stargazerEvents: Array = stargazers.users.map(\n (user) => ({\n eventName: \"star\",\n eventAction: \"created\",\n repoId: id,\n userId: user.id,\n }),\n );\n if (stargazerEvents.length > 0) {\n await db.insert(events).values(stargazerEvents).onConflictDoNothing();\n }\n\n const watcherEvents: Array = watchers.users.map((user) => ({\n eventName: \"watch\",\n eventAction: \"started\",\n repoId: id,\n userId: user.id,\n }));\n if (watcherEvents.length > 0) {\n await db.insert(events).values(watcherEvents).onConflictDoNothing();\n }\n\n return c.text(\"Updated stargazers and watchers!\");\n } catch (error) {\n return c.text(\n `Error fetching and storing users and events: ${error}`,\n 500,\n );\n }\n },\n);\n\nexport default api;\n", "// src/middleware/bearer-auth/index.ts\nimport { HTTPException } from \"../../http-exception.js\";\nimport { timingSafeEqual } from \"../../utils/buffer.js\";\nvar TOKEN_STRINGS = \"[A-Za-z0-9._~+/-]+=*\";\nvar PREFIX = \"Bearer\";\nvar HEADER = \"Authorization\";\nvar bearerAuth = (options) => {\n if (!(\"token\" in options || \"verifyToken\" in options)) {\n throw new Error('bearer auth middleware requires options for \"token\"');\n }\n if (!options.realm) {\n options.realm = \"\";\n }\n if (options.prefix === void 0) {\n options.prefix = PREFIX;\n }\n const realm = options.realm?.replace(/\"/g, '\\\\\"');\n const prefixRegexStr = options.prefix === \"\" ? \"\" : `${options.prefix} +`;\n const regexp = new RegExp(`^${prefixRegexStr}(${TOKEN_STRINGS}) *$`);\n const wwwAuthenticatePrefix = options.prefix === \"\" ? \"\" : `${options.prefix} `;\n const throwHTTPException = async (c, status, wwwAuthenticateHeader, messageOption) => {\n const headers = {\n \"WWW-Authenticate\": wwwAuthenticateHeader\n };\n const responseMessage = typeof messageOption === \"function\" ? await messageOption(c) : messageOption;\n const res = typeof responseMessage === \"string\" ? new Response(responseMessage, { status, headers }) : new Response(JSON.stringify(responseMessage), {\n status,\n headers: {\n ...headers,\n \"content-type\": \"application/json; charset=UTF-8\"\n }\n });\n throw new HTTPException(status, { res });\n };\n return async function bearerAuth2(c, next) {\n const headerToken = c.req.header(options.headerName || HEADER);\n if (!headerToken) {\n await throwHTTPException(\n c,\n 401,\n `${wwwAuthenticatePrefix}realm=\"${realm}\"`,\n options.noAuthenticationHeaderMessage || \"Unauthorized\"\n );\n } else {\n const match = regexp.exec(headerToken);\n if (!match) {\n await throwHTTPException(\n c,\n 400,\n `${wwwAuthenticatePrefix}error=\"invalid_request\"`,\n options.invalidAuthenticationHeaderMessage || \"Bad Request\"\n );\n } else {\n let equal = false;\n if (\"verifyToken\" in options) {\n equal = await options.verifyToken(match[1], c);\n } else if (typeof options.token === \"string\") {\n equal = await timingSafeEqual(options.token, match[1], options.hashFunction);\n } else if (Array.isArray(options.token) && options.token.length > 0) {\n for (const token of options.token) {\n if (await timingSafeEqual(token, match[1], options.hashFunction)) {\n equal = true;\n break;\n }\n }\n }\n if (!equal) {\n await throwHTTPException(\n c,\n 401,\n `${wwwAuthenticatePrefix}error=\"invalid_token\"`,\n options.invalidTokenMessage || \"Unauthorized\"\n );\n }\n }\n }\n await next();\n };\n};\nexport {\n bearerAuth\n};\n", "// src/http-exception.ts\nvar HTTPException = class extends Error {\n res;\n status;\n constructor(status = 500, options) {\n super(options?.message, { cause: options?.cause });\n this.res = options?.res;\n this.status = status;\n }\n getResponse() {\n if (this.res) {\n const newResponse = new Response(this.res.body, {\n status: this.status,\n headers: this.res.headers\n });\n return newResponse;\n }\n return new Response(this.message, {\n status: this.status\n });\n }\n};\nexport {\n HTTPException\n};\n", "// src/utils/buffer.ts\nimport { sha256 } from \"./crypto.js\";\nvar equal = (a, b) => {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n const va = new DataView(a);\n const vb = new DataView(b);\n let i = va.byteLength;\n while (i--) {\n if (va.getUint8(i) !== vb.getUint8(i)) {\n return false;\n }\n }\n return true;\n};\nvar timingSafeEqual = async (a, b, hashFunction) => {\n if (!hashFunction) {\n hashFunction = sha256;\n }\n const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]);\n if (!sa || !sb) {\n return false;\n }\n return sa === sb && a === b;\n};\nvar bufferToString = (buffer) => {\n if (buffer instanceof ArrayBuffer) {\n const enc = new TextDecoder(\"utf-8\");\n return enc.decode(buffer);\n }\n return buffer;\n};\nvar bufferToFormData = (arrayBuffer, contentType) => {\n const response = new Response(arrayBuffer, {\n headers: {\n \"Content-Type\": contentType\n }\n });\n return response.formData();\n};\nexport {\n bufferToFormData,\n bufferToString,\n equal,\n timingSafeEqual\n};\n", "// src/utils/crypto.ts\nvar sha256 = async (data) => {\n const algorithm = { name: \"SHA-256\", alias: \"sha256\" };\n const hash = await createHash(data, algorithm);\n return hash;\n};\nvar sha1 = async (data) => {\n const algorithm = { name: \"SHA-1\", alias: \"sha1\" };\n const hash = await createHash(data, algorithm);\n return hash;\n};\nvar md5 = async (data) => {\n const algorithm = { name: \"MD5\", alias: \"md5\" };\n const hash = await createHash(data, algorithm);\n return hash;\n};\nvar createHash = async (data, algorithm) => {\n let sourceBuffer;\n if (data instanceof ReadableStream) {\n let body = \"\";\n const reader = data.getReader();\n await reader?.read().then(async (chuck) => {\n const value = await createHash(chuck.value || \"\", algorithm);\n body += value;\n });\n return body;\n }\n if (ArrayBuffer.isView(data) || data instanceof ArrayBuffer) {\n sourceBuffer = data;\n } else {\n if (typeof data === \"object\") {\n data = JSON.stringify(data);\n }\n sourceBuffer = new TextEncoder().encode(String(data));\n }\n if (crypto && crypto.subtle) {\n const buffer = await crypto.subtle.digest(\n {\n name: algorithm.name\n },\n sourceBuffer\n );\n const hash = Array.prototype.map.call(new Uint8Array(buffer), (x) => (\"00\" + x.toString(16)).slice(-2)).join(\"\");\n return hash;\n }\n return null;\n};\nexport {\n createHash,\n md5,\n sha1,\n sha256\n};\n", "export * from \"./schema\";\n", "import { relations } from \"drizzle-orm\";\nimport {\n integer,\n pgTable,\n serial,\n text,\n timestamp,\n unique,\n} from \"drizzle-orm/pg-core\";\n\nexport const repositories = pgTable(\"repositories\", {\n id: integer(\"id\").primaryKey(),\n createdAt: timestamp(\"created_at\").notNull().defaultNow(),\n name: text(\"name\").notNull(),\n fullName: text(\"full_name\").notNull(),\n description: text(\"description\"),\n stargazersCount: integer(\"stargazers_count\").notNull().default(0),\n watchersCount: integer(\"watchers_count\").notNull().default(0),\n});\n\nexport const users = pgTable(\"users\", {\n id: integer(\"id\").primaryKey(),\n createdAt: timestamp(\"created_at\").notNull().defaultNow(),\n avatar: text(\"avatar\").notNull(),\n handle: text(\"handle\").notNull(),\n company: text(\"company\"),\n emailAddress: text(\"email_address\"),\n location: text(\"location\"),\n role: text(\"role\"),\n name: text(\"name\"),\n twitterHandle: text(\"twitter_handle\"),\n});\n\nexport const events = pgTable(\n \"events\",\n {\n id: serial(\"id\").primaryKey(),\n createdAt: timestamp(\"created_at\").notNull().defaultNow(),\n userId: integer(\"user_id\")\n .notNull()\n .references(() => users.id, { onDelete: \"cascade\" }),\n repoId: integer(\"repo_id\")\n .notNull()\n .references(() => repositories.id, {\n onDelete: \"cascade\",\n }),\n eventId: integer(\"event_id\"),\n eventName: text(\"event_name\").notNull(),\n eventAction: text(\"event_action\").notNull(),\n },\n (t) => ({\n uniqueEvent: unique().on(t.userId, t.repoId, t.eventName, t.eventAction),\n }),\n);\n\nexport const repositoriesEvents = relations(repositories, ({ many }) => ({\n events: many(events),\n}));\n\nexport const usersEvents = relations(users, ({ many }) => ({\n events: many(events),\n}));\n\nexport const eventsUser = relations(events, ({ one }) => ({\n user: one(users, {\n fields: [events.userId],\n references: [users.id],\n }),\n}));\n\nexport type Repository = typeof repositories.$inferSelect;\nexport type RepositoryInsert = typeof repositories.$inferInsert;\nexport type UserInsert = typeof users.$inferInsert;\nexport type EventInsert = typeof events.$inferInsert;\n", "import type { AnyColumn } from './column.ts';\nimport { Column } from './column.ts';\nimport { entityKind, is } from './entity.ts';\nimport type { Relation } from './relations.ts';\nimport type { View } from './sql/sql.ts';\nimport { SQL, sql } from './sql/sql.ts';\nimport { Table } from './table.ts';\nimport { ViewBaseConfig } from './view-common.ts';\n\nexport class ColumnAliasProxyHandler implements ProxyHandler {\n\tstatic readonly [entityKind]: string = 'ColumnAliasProxyHandler';\n\n\tconstructor(private table: Table | View) {}\n\n\tget(columnObj: TColumn, prop: string | symbol): any {\n\t\tif (prop === 'table') {\n\t\t\treturn this.table;\n\t\t}\n\n\t\treturn columnObj[prop as keyof TColumn];\n\t}\n}\n\nexport class TableAliasProxyHandler implements ProxyHandler {\n\tstatic readonly [entityKind]: string = 'TableAliasProxyHandler';\n\n\tconstructor(private alias: string, private replaceOriginalName: boolean) {}\n\n\tget(target: T, prop: string | symbol): any {\n\t\tif (prop === Table.Symbol.IsAlias) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (prop === Table.Symbol.Name) {\n\t\t\treturn this.alias;\n\t\t}\n\n\t\tif (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {\n\t\t\treturn this.alias;\n\t\t}\n\n\t\tif (prop === ViewBaseConfig) {\n\t\t\treturn {\n\t\t\t\t...target[ViewBaseConfig as keyof typeof target],\n\t\t\t\tname: this.alias,\n\t\t\t\tisAlias: true,\n\t\t\t};\n\t\t}\n\n\t\tif (prop === Table.Symbol.Columns) {\n\t\t\tconst columns = (target as Table)[Table.Symbol.Columns];\n\t\t\tif (!columns) {\n\t\t\t\treturn columns;\n\t\t\t}\n\n\t\t\tconst proxiedColumns: { [key: string]: any } = {};\n\n\t\t\tObject.keys(columns).map((key) => {\n\t\t\t\tproxiedColumns[key] = new Proxy(\n\t\t\t\t\tcolumns[key]!,\n\t\t\t\t\tnew ColumnAliasProxyHandler(new Proxy(target, this)),\n\t\t\t\t);\n\t\t\t});\n\n\t\t\treturn proxiedColumns;\n\t\t}\n\n\t\tconst value = target[prop as keyof typeof target];\n\t\tif (is(value, Column)) {\n\t\t\treturn new Proxy(value as AnyColumn, new ColumnAliasProxyHandler(new Proxy(target, this)));\n\t\t}\n\n\t\treturn value;\n\t}\n}\n\nexport class RelationTableAliasProxyHandler implements ProxyHandler {\n\tstatic readonly [entityKind]: string = 'RelationTableAliasProxyHandler';\n\n\tconstructor(private alias: string) {}\n\n\tget(target: T, prop: string | symbol): any {\n\t\tif (prop === 'sourceTable') {\n\t\t\treturn aliasedTable(target.sourceTable, this.alias);\n\t\t}\n\n\t\treturn target[prop as keyof typeof target];\n\t}\n}\n\nexport function aliasedTable(table: T, tableAlias: string): T {\n\treturn new Proxy(table, new TableAliasProxyHandler(tableAlias, false));\n}\n\nexport function aliasedRelation(relation: T, tableAlias: string): T {\n\treturn new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));\n}\n\nexport function aliasedTableColumn(column: T, tableAlias: string): T {\n\treturn new Proxy(\n\t\tcolumn,\n\t\tnew ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))),\n\t);\n}\n\nexport function mapColumnsInAliasedSQLToAlias(query: SQL.Aliased, alias: string): SQL.Aliased {\n\treturn new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);\n}\n\nexport function mapColumnsInSQLToAlias(query: SQL, alias: string): SQL {\n\treturn sql.join(query.queryChunks.map((c) => {\n\t\tif (is(c, Column)) {\n\t\t\treturn aliasedTableColumn(c, alias);\n\t\t}\n\t\tif (is(c, SQL)) {\n\t\t\treturn mapColumnsInSQLToAlias(c, alias);\n\t\t}\n\t\tif (is(c, SQL.Aliased)) {\n\t\t\treturn mapColumnsInAliasedSQLToAlias(c, alias);\n\t\t}\n\t\treturn c;\n\t}));\n}\n", "import type {\n\tColumnBuilderBaseConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tGeneratedColumnConfig,\n\tGeneratedIdentityConfig,\n} from './column-builder.ts';\nimport { entityKind } from './entity.ts';\nimport type { DriverValueMapper, SQL, SQLWrapper } from './sql/sql.ts';\nimport type { Table } from './table.ts';\nimport type { Update } from './utils.ts';\n\nexport interface ColumnBaseConfig<\n\tTDataType extends ColumnDataType,\n\tTColumnType extends string,\n> extends ColumnBuilderBaseConfig {\n\ttableName: string;\n\tnotNull: boolean;\n\thasDefault: boolean;\n\tisPrimaryKey: boolean;\n\tisAutoincrement: boolean;\n\thasRuntimeDefault: boolean;\n}\n\nexport type ColumnTypeConfig, TTypeConfig extends object> = T & {\n\tbrand: 'Column';\n\ttableName: T['tableName'];\n\tname: T['name'];\n\tdataType: T['dataType'];\n\tcolumnType: T['columnType'];\n\tdata: T['data'];\n\tdriverParam: T['driverParam'];\n\tnotNull: T['notNull'];\n\thasDefault: T['hasDefault'];\n\tisPrimaryKey: T['isPrimaryKey'];\n\tisAutoincrement: T['isAutoincrement'];\n\thasRuntimeDefault: T['hasRuntimeDefault'];\n\tenumValues: T['enumValues'];\n\tbaseColumn: T extends { baseColumn: infer U } ? U : unknown;\n\tgenerated: GeneratedColumnConfig | undefined;\n} & TTypeConfig;\n\nexport type ColumnRuntimeConfig = ColumnBuilderRuntimeConfig<\n\tTData,\n\tTRuntimeConfig\n>;\n\nexport interface Column<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTRuntimeConfig extends object = object,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTTypeConfig extends object = object,\n> extends DriverValueMapper, SQLWrapper {\n\t// SQLWrapper runtime implementation is defined in 'sql/sql.ts'\n}\n/*\n\t`Column` only accepts a full `ColumnConfig` as its generic.\n\tTo infer parts of the config, use `AnyColumn` that accepts a partial config.\n\tSee `GetColumnData` for example usage of inferring.\n*/\nexport abstract class Column<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n> implements DriverValueMapper, SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Column';\n\n\tdeclare readonly _: ColumnTypeConfig;\n\n\treadonly name: string;\n\treadonly primary: boolean;\n\treadonly notNull: boolean;\n\treadonly default: T['data'] | SQL | undefined;\n\treadonly defaultFn: (() => T['data'] | SQL) | undefined;\n\treadonly onUpdateFn: (() => T['data'] | SQL) | undefined;\n\treadonly hasDefault: boolean;\n\treadonly isUnique: boolean;\n\treadonly uniqueName: string | undefined;\n\treadonly uniqueType: string | undefined;\n\treadonly dataType: T['dataType'];\n\treadonly columnType: T['columnType'];\n\treadonly enumValues: T['enumValues'] = undefined;\n\treadonly generated: GeneratedColumnConfig | undefined = undefined;\n\treadonly generatedIdentity: GeneratedIdentityConfig | undefined = undefined;\n\n\tprotected config: ColumnRuntimeConfig;\n\n\tconstructor(\n\t\treadonly table: Table,\n\t\tconfig: ColumnRuntimeConfig,\n\t) {\n\t\tthis.config = config;\n\t\tthis.name = config.name;\n\t\tthis.notNull = config.notNull;\n\t\tthis.default = config.default;\n\t\tthis.defaultFn = config.defaultFn;\n\t\tthis.onUpdateFn = config.onUpdateFn;\n\t\tthis.hasDefault = config.hasDefault;\n\t\tthis.primary = config.primaryKey;\n\t\tthis.isUnique = config.isUnique;\n\t\tthis.uniqueName = config.uniqueName;\n\t\tthis.uniqueType = config.uniqueType;\n\t\tthis.dataType = config.dataType as T['dataType'];\n\t\tthis.columnType = config.columnType;\n\t\tthis.generated = config.generated;\n\t\tthis.generatedIdentity = config.generatedIdentity;\n\t}\n\n\tabstract getSQLType(): string;\n\n\tmapFromDriverValue(value: unknown): unknown {\n\t\treturn value;\n\t}\n\n\tmapToDriverValue(value: unknown): unknown {\n\t\treturn value;\n\t}\n\n\t// ** @internal */\n\tshouldDisableInsert(): boolean {\n\t\treturn this.config.generated !== undefined && this.config.generated.type !== 'byDefault';\n\t}\n}\n\nexport type UpdateColConfig<\n\tT extends ColumnBaseConfig,\n\tTUpdate extends Partial>,\n> = Update;\n\nexport type AnyColumn> = {}> = Column<\n\tRequired, TPartial>>\n>;\n\nexport type GetColumnData =\n\t// dprint-ignore\n\tTInferMode extends 'raw' // Raw mode\n\t\t? TColumn['_']['data'] // Just return the underlying type\n\t\t: TColumn['_']['notNull'] extends true // Query mode\n\t\t? TColumn['_']['data'] // Query mode, not null\n\t\t: TColumn['_']['data'] | null; // Query mode, nullable\n\nexport type InferColumnsDataTypes> = {\n\t[Key in keyof TColumns]: GetColumnData;\n};\n", "export const entityKind = Symbol.for('drizzle:entityKind');\nexport const hasOwnEntityKind = Symbol.for('drizzle:hasOwnEntityKind');\n\nexport interface DrizzleEntity {\n\t[entityKind]: string;\n}\n\nexport type DrizzleEntityClass =\n\t& ((abstract new(...args: any[]) => T) | (new(...args: any[]) => T))\n\t& DrizzleEntity;\n\nexport function is>(value: any, type: T): value is InstanceType {\n\tif (!value || typeof value !== 'object') {\n\t\treturn false;\n\t}\n\n\tif (value instanceof type) { // eslint-disable-line no-instanceof/no-instanceof\n\t\treturn true;\n\t}\n\n\tif (!Object.prototype.hasOwnProperty.call(type, entityKind)) {\n\t\tthrow new Error(\n\t\t\t`Class \"${\n\t\t\t\ttype.name ?? ''\n\t\t\t}\" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`,\n\t\t);\n\t}\n\n\tlet cls = value.constructor;\n\tif (cls) {\n\t\t// Traverse the prototype chain to find the entityKind\n\t\twhile (cls) {\n\t\t\tif (entityKind in cls && cls[entityKind] === type[entityKind]) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tcls = Object.getPrototypeOf(cls);\n\t\t}\n\t}\n\n\treturn false;\n}\n", "import { entityKind, is } from '~/entity.ts';\nimport type { SelectedFields } from '~/operations.ts';\nimport { isPgEnum } from '~/pg-core/columns/enum.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { tracer } from '~/tracing.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type { AnyColumn } from '../column.ts';\nimport { Column } from '../column.ts';\nimport { Table } from '../table.ts';\n\n/**\n * This class is used to indicate a primitive param value that is used in `sql` tag.\n * It is only used on type level and is never instantiated at runtime.\n * If you see a value of this type in the code, its runtime value is actually the primitive param value.\n */\nexport class FakePrimitiveParam {\n\tstatic readonly [entityKind]: string = 'FakePrimitiveParam';\n}\n\nexport type Chunk =\n\t| string\n\t| Table\n\t| View\n\t| AnyColumn\n\t| Name\n\t| Param\n\t| Placeholder\n\t| SQL;\n\nexport interface BuildQueryConfig {\n\tescapeName(name: string): string;\n\tescapeParam(num: number, value: unknown): string;\n\tescapeString(str: string): string;\n\tprepareTyping?: (encoder: DriverValueEncoder) => QueryTypingsValue;\n\tparamStartIndex?: { value: number };\n\tinlineParams?: boolean;\n\tinvokeSource?: 'indexes' | undefined;\n}\n\nexport type QueryTypingsValue = 'json' | 'decimal' | 'time' | 'timestamp' | 'uuid' | 'date' | 'none';\n\nexport interface Query {\n\tsql: string;\n\tparams: unknown[];\n}\n\nexport interface QueryWithTypings extends Query {\n\ttypings?: QueryTypingsValue[];\n}\n\n/**\n * Any value that implements the `getSQL` method. The implementations include:\n * - `Table`\n * - `Column`\n * - `View`\n * - `Subquery`\n * - `SQL`\n * - `SQL.Aliased`\n * - `Placeholder`\n * - `Param`\n */\nexport interface SQLWrapper {\n\tgetSQL(): SQL;\n\tshouldOmitSQLParens?(): boolean;\n}\n\nexport function isSQLWrapper(value: unknown): value is SQLWrapper {\n\treturn value !== null && value !== undefined && typeof (value as any).getSQL === 'function';\n}\n\nfunction mergeQueries(queries: QueryWithTypings[]): QueryWithTypings {\n\tconst result: QueryWithTypings = { sql: '', params: [] };\n\tfor (const query of queries) {\n\t\tresult.sql += query.sql;\n\t\tresult.params.push(...query.params);\n\t\tif (query.typings?.length) {\n\t\t\tif (!result.typings) {\n\t\t\t\tresult.typings = [];\n\t\t\t}\n\t\t\tresult.typings.push(...query.typings);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class StringChunk implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'StringChunk';\n\n\treadonly value: string[];\n\n\tconstructor(value: string | string[]) {\n\t\tthis.value = Array.isArray(value) ? value : [value];\n\t}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\nexport class SQL implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'SQL';\n\n\tdeclare _: {\n\t\tbrand: 'SQL';\n\t\ttype: T;\n\t};\n\n\t/** @internal */\n\tdecoder: DriverValueDecoder = noopDecoder;\n\tprivate shouldInlineParams = false;\n\n\tconstructor(readonly queryChunks: SQLChunk[]) {}\n\n\tappend(query: SQL): this {\n\t\tthis.queryChunks.push(...query.queryChunks);\n\t\treturn this;\n\t}\n\n\ttoQuery(config: BuildQueryConfig): QueryWithTypings {\n\t\treturn tracer.startActiveSpan('drizzle.buildSQL', (span) => {\n\t\t\tconst query = this.buildQueryFromSourceParams(this.queryChunks, config);\n\t\t\tspan?.setAttributes({\n\t\t\t\t'drizzle.query.text': query.sql,\n\t\t\t\t'drizzle.query.params': JSON.stringify(query.params),\n\t\t\t});\n\t\t\treturn query;\n\t\t});\n\t}\n\n\tbuildQueryFromSourceParams(chunks: SQLChunk[], _config: BuildQueryConfig): Query {\n\t\tconst config = Object.assign({}, _config, {\n\t\t\tinlineParams: _config.inlineParams || this.shouldInlineParams,\n\t\t\tparamStartIndex: _config.paramStartIndex || { value: 0 },\n\t\t});\n\n\t\tconst {\n\t\t\tescapeName,\n\t\t\tescapeParam,\n\t\t\tprepareTyping,\n\t\t\tinlineParams,\n\t\t\tparamStartIndex,\n\t\t} = config;\n\n\t\treturn mergeQueries(chunks.map((chunk): QueryWithTypings => {\n\t\t\tif (is(chunk, StringChunk)) {\n\t\t\t\treturn { sql: chunk.value.join(''), params: [] };\n\t\t\t}\n\n\t\t\tif (is(chunk, Name)) {\n\t\t\t\treturn { sql: escapeName(chunk.value), params: [] };\n\t\t\t}\n\n\t\t\tif (chunk === undefined) {\n\t\t\t\treturn { sql: '', params: [] };\n\t\t\t}\n\n\t\t\tif (Array.isArray(chunk)) {\n\t\t\t\tconst result: SQLChunk[] = [new StringChunk('(')];\n\t\t\t\tfor (const [i, p] of chunk.entries()) {\n\t\t\t\t\tresult.push(p);\n\t\t\t\t\tif (i < chunk.length - 1) {\n\t\t\t\t\t\tresult.push(new StringChunk(', '));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult.push(new StringChunk(')'));\n\t\t\t\treturn this.buildQueryFromSourceParams(result, config);\n\t\t\t}\n\n\t\t\tif (is(chunk, SQL)) {\n\t\t\t\treturn this.buildQueryFromSourceParams(chunk.queryChunks, {\n\t\t\t\t\t...config,\n\t\t\t\t\tinlineParams: inlineParams || chunk.shouldInlineParams,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (is(chunk, Table)) {\n\t\t\t\tconst schemaName = chunk[Table.Symbol.Schema];\n\t\t\t\tconst tableName = chunk[Table.Symbol.Name];\n\t\t\t\treturn {\n\t\t\t\t\tsql: schemaName === undefined\n\t\t\t\t\t\t? escapeName(tableName)\n\t\t\t\t\t\t: escapeName(schemaName) + '.' + escapeName(tableName),\n\t\t\t\t\tparams: [],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (is(chunk, Column)) {\n\t\t\t\tif (_config.invokeSource === 'indexes') {\n\t\t\t\t\treturn { sql: escapeName(chunk.name), params: [] };\n\t\t\t\t}\n\t\t\t\treturn { sql: escapeName(chunk.table[Table.Symbol.Name]) + '.' + escapeName(chunk.name), params: [] };\n\t\t\t}\n\n\t\t\tif (is(chunk, View)) {\n\t\t\t\tconst schemaName = chunk[ViewBaseConfig].schema;\n\t\t\t\tconst viewName = chunk[ViewBaseConfig].name;\n\t\t\t\treturn {\n\t\t\t\t\tsql: schemaName === undefined\n\t\t\t\t\t\t? escapeName(viewName)\n\t\t\t\t\t\t: escapeName(schemaName) + '.' + escapeName(viewName),\n\t\t\t\t\tparams: [],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (is(chunk, Param)) {\n\t\t\t\tif (is(chunk.value, Placeholder)) {\n\t\t\t\t\treturn { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ['none'] };\n\t\t\t\t}\n\n\t\t\t\tconst mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);\n\n\t\t\t\tif (is(mappedValue, SQL)) {\n\t\t\t\t\treturn this.buildQueryFromSourceParams([mappedValue], config);\n\t\t\t\t}\n\n\t\t\t\tif (inlineParams) {\n\t\t\t\t\treturn { sql: this.mapInlineParam(mappedValue, config), params: [] };\n\t\t\t\t}\n\n\t\t\t\tlet typings: QueryTypingsValue[] = ['none'];\n\t\t\t\tif (prepareTyping) {\n\t\t\t\t\ttypings = [prepareTyping(chunk.encoder)];\n\t\t\t\t}\n\n\t\t\t\treturn { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };\n\t\t\t}\n\n\t\t\tif (is(chunk, Placeholder)) {\n\t\t\t\treturn { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ['none'] };\n\t\t\t}\n\n\t\t\tif (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {\n\t\t\t\treturn { sql: escapeName(chunk.fieldAlias), params: [] };\n\t\t\t}\n\n\t\t\tif (is(chunk, Subquery)) {\n\t\t\t\tif (chunk._.isWith) {\n\t\t\t\t\treturn { sql: escapeName(chunk._.alias), params: [] };\n\t\t\t\t}\n\t\t\t\treturn this.buildQueryFromSourceParams([\n\t\t\t\t\tnew StringChunk('('),\n\t\t\t\t\tchunk._.sql,\n\t\t\t\t\tnew StringChunk(') '),\n\t\t\t\t\tnew Name(chunk._.alias),\n\t\t\t\t], config);\n\t\t\t}\n\n\t\t\tif (isPgEnum(chunk)) {\n\t\t\t\tif (chunk.schema) {\n\t\t\t\t\treturn { sql: escapeName(chunk.schema) + '.' + escapeName(chunk.enumName), params: [] };\n\t\t\t\t}\n\t\t\t\treturn { sql: escapeName(chunk.enumName), params: [] };\n\t\t\t}\n\n\t\t\tif (isSQLWrapper(chunk)) {\n\t\t\t\tif (chunk.shouldOmitSQLParens?.()) {\n\t\t\t\t\treturn this.buildQueryFromSourceParams([chunk.getSQL()], config);\n\t\t\t\t}\n\t\t\t\treturn this.buildQueryFromSourceParams([\n\t\t\t\t\tnew StringChunk('('),\n\t\t\t\t\tchunk.getSQL(),\n\t\t\t\t\tnew StringChunk(')'),\n\t\t\t\t], config);\n\t\t\t}\n\n\t\t\tif (inlineParams) {\n\t\t\t\treturn { sql: this.mapInlineParam(chunk, config), params: [] };\n\t\t\t}\n\n\t\t\treturn { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ['none'] };\n\t\t}));\n\t}\n\n\tprivate mapInlineParam(\n\t\tchunk: unknown,\n\t\t{ escapeString }: BuildQueryConfig,\n\t): string {\n\t\tif (chunk === null) {\n\t\t\treturn 'null';\n\t\t}\n\t\tif (typeof chunk === 'number' || typeof chunk === 'boolean') {\n\t\t\treturn chunk.toString();\n\t\t}\n\t\tif (typeof chunk === 'string') {\n\t\t\treturn escapeString(chunk);\n\t\t}\n\t\tif (typeof chunk === 'object') {\n\t\t\tconst mappedValueAsString = chunk.toString();\n\t\t\tif (mappedValueAsString === '[object Object]') {\n\t\t\t\treturn escapeString(JSON.stringify(chunk));\n\t\t\t}\n\t\t\treturn escapeString(mappedValueAsString);\n\t\t}\n\t\tthrow new Error('Unexpected param value: ' + chunk);\n\t}\n\n\tgetSQL(): SQL {\n\t\treturn this;\n\t}\n\n\tas(alias: string): SQL.Aliased;\n\t/**\n\t * @deprecated\n\t * Use ``sql`query`.as(alias)`` instead.\n\t */\n\tas(): SQL;\n\t/**\n\t * @deprecated\n\t * Use ``sql`query`.as(alias)`` instead.\n\t */\n\tas(alias: string): SQL.Aliased;\n\tas(alias?: string): SQL | SQL.Aliased {\n\t\t// TODO: remove with deprecated overloads\n\t\tif (alias === undefined) {\n\t\t\treturn this;\n\t\t}\n\n\t\treturn new SQL.Aliased(this, alias);\n\t}\n\n\tmapWith<\n\t\tTDecoder extends\n\t\t\t| DriverValueDecoder\n\t\t\t| DriverValueDecoder['mapFromDriverValue'],\n\t>(decoder: TDecoder): SQL> {\n\t\tthis.decoder = typeof decoder === 'function' ? { mapFromDriverValue: decoder } : decoder;\n\t\treturn this as SQL>;\n\t}\n\n\tinlineParams(): this {\n\t\tthis.shouldInlineParams = true;\n\t\treturn this;\n\t}\n\n\t/**\n\t * This method is used to conditionally include a part of the query.\n\t *\n\t * @param condition - Condition to check\n\t * @returns itself if the condition is `true`, otherwise `undefined`\n\t */\n\tif(condition: any | undefined): this | undefined {\n\t\treturn condition ? this : undefined;\n\t}\n}\n\nexport type GetDecoderResult = T extends Column ? T['_']['data'] : T extends\n\t| DriverValueDecoder\n\t| DriverValueDecoder['mapFromDriverValue'] ? TData\n: never;\n\n/**\n * Any DB name (table, column, index etc.)\n */\nexport class Name implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Name';\n\n\tprotected brand!: 'Name';\n\n\tconstructor(readonly value: string) {}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n/**\n * Any DB name (table, column, index etc.)\n * @deprecated Use `sql.identifier` instead.\n */\nexport function name(value: string): Name {\n\treturn new Name(value);\n}\n\nexport interface DriverValueDecoder {\n\tmapFromDriverValue(value: TDriverParam): TData;\n}\n\nexport interface DriverValueEncoder {\n\tmapToDriverValue(value: TData): TDriverParam | SQL;\n}\n\nexport function isDriverValueEncoder(value: unknown): value is DriverValueEncoder {\n\treturn typeof value === 'object' && value !== null && 'mapToDriverValue' in value\n\t\t&& typeof (value as any).mapToDriverValue === 'function';\n}\n\nexport const noopDecoder: DriverValueDecoder = {\n\tmapFromDriverValue: (value) => value,\n};\n\nexport const noopEncoder: DriverValueEncoder = {\n\tmapToDriverValue: (value) => value,\n};\n\nexport interface DriverValueMapper\n\textends DriverValueDecoder, DriverValueEncoder\n{}\n\nexport const noopMapper: DriverValueMapper = {\n\t...noopDecoder,\n\t...noopEncoder,\n};\n\n/** Parameter value that is optionally bound to an encoder (for example, a column). */\nexport class Param implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Param';\n\n\tprotected brand!: 'BoundParamValue';\n\n\t/**\n\t * @param value - Parameter value\n\t * @param encoder - Encoder to convert the value to a driver parameter\n\t */\n\tconstructor(\n\t\treadonly value: TDataType,\n\t\treadonly encoder: DriverValueEncoder = noopEncoder,\n\t) {}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n/** @deprecated Use `sql.param` instead. */\nexport function param(\n\tvalue: TData,\n\tencoder?: DriverValueEncoder,\n): Param {\n\treturn new Param(value, encoder);\n}\n\n/**\n * Anything that can be passed to the `` sql`...` `` tagged function.\n */\nexport type SQLChunk =\n\t| StringChunk\n\t| SQLChunk[]\n\t| SQLWrapper\n\t| SQL\n\t| Table\n\t| View\n\t| Subquery\n\t| AnyColumn\n\t| Param\n\t| Name\n\t| undefined\n\t| FakePrimitiveParam\n\t| Placeholder;\n\nexport function sql(strings: TemplateStringsArray, ...params: any[]): SQL;\n/*\n\tThe type of `params` is specified as `SQLChunk[]`, but that's slightly incorrect -\n\tin runtime, users won't pass `FakePrimitiveParam` instances as `params` - they will pass primitive values\n\twhich will be wrapped in `Param`. That's why the overload specifies `params` as `any[]` and not as `SQLSourceParam[]`.\n\tThis type is used to make our lives easier and the type checker happy.\n*/\nexport function sql(strings: TemplateStringsArray, ...params: SQLChunk[]): SQL {\n\tconst queryChunks: SQLChunk[] = [];\n\tif (params.length > 0 || (strings.length > 0 && strings[0] !== '')) {\n\t\tqueryChunks.push(new StringChunk(strings[0]!));\n\t}\n\tfor (const [paramIndex, param] of params.entries()) {\n\t\tqueryChunks.push(param, new StringChunk(strings[paramIndex + 1]!));\n\t}\n\n\treturn new SQL(queryChunks);\n}\n\nexport namespace sql {\n\texport function empty(): SQL {\n\t\treturn new SQL([]);\n\t}\n\n\t/** @deprecated - use `sql.join()` */\n\texport function fromList(list: SQLChunk[]): SQL {\n\t\treturn new SQL(list);\n\t}\n\n\t/**\n\t * Convenience function to create an SQL query from a raw string.\n\t * @param str The raw SQL query string.\n\t */\n\texport function raw(str: string): SQL {\n\t\treturn new SQL([new StringChunk(str)]);\n\t}\n\n\t/**\n\t * Join a list of SQL chunks with a separator.\n\t * @example\n\t * ```ts\n\t * const query = sql.join([sql`a`, sql`b`, sql`c`]);\n\t * // sql`abc`\n\t * ```\n\t * @example\n\t * ```ts\n\t * const query = sql.join([sql`a`, sql`b`, sql`c`], sql`, `);\n\t * // sql`a, b, c`\n\t * ```\n\t */\n\texport function join(chunks: SQLChunk[], separator?: SQLChunk): SQL {\n\t\tconst result: SQLChunk[] = [];\n\t\tfor (const [i, chunk] of chunks.entries()) {\n\t\t\tif (i > 0 && separator !== undefined) {\n\t\t\t\tresult.push(separator);\n\t\t\t}\n\t\t\tresult.push(chunk);\n\t\t}\n\t\treturn new SQL(result);\n\t}\n\n\t/**\n\t * Create a SQL chunk that represents a DB identifier (table, column, index etc.).\n\t * When used in a query, the identifier will be escaped based on the DB engine.\n\t * For example, in PostgreSQL, identifiers are escaped with double quotes.\n\t *\n\t * **WARNING: This function does not offer any protection against SQL injections, so you must validate any user input beforehand.**\n\t *\n\t * @example ```ts\n\t * const query = sql`SELECT * FROM ${sql.identifier('my-table')}`;\n\t * // 'SELECT * FROM \"my-table\"'\n\t * ```\n\t */\n\texport function identifier(value: string): Name {\n\t\treturn new Name(value);\n\t}\n\n\texport function placeholder(name: TName): Placeholder {\n\t\treturn new Placeholder(name);\n\t}\n\n\texport function param(\n\t\tvalue: TData,\n\t\tencoder?: DriverValueEncoder,\n\t): Param {\n\t\treturn new Param(value, encoder);\n\t}\n}\n\nexport namespace SQL {\n\texport class Aliased implements SQLWrapper {\n\t\tstatic readonly [entityKind]: string = 'SQL.Aliased';\n\n\t\tdeclare _: {\n\t\t\tbrand: 'SQL.Aliased';\n\t\t\ttype: T;\n\t\t};\n\n\t\t/** @internal */\n\t\tisSelectionField = false;\n\n\t\tconstructor(\n\t\t\treadonly sql: SQL,\n\t\t\treadonly fieldAlias: string,\n\t\t) {}\n\n\t\tgetSQL(): SQL {\n\t\t\treturn this.sql;\n\t\t}\n\n\t\t/** @internal */\n\t\tclone() {\n\t\t\treturn new Aliased(this.sql, this.fieldAlias);\n\t\t}\n\t}\n}\n\nexport class Placeholder implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Placeholder';\n\n\tdeclare protected: TValue;\n\n\tconstructor(readonly name: TName) {}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n/** @deprecated Use `sql.placeholder` instead. */\nexport function placeholder(name: TName): Placeholder {\n\treturn new Placeholder(name);\n}\n\nexport function fillPlaceholders(params: unknown[], values: Record): unknown[] {\n\treturn params.map((p) => {\n\t\tif (is(p, Placeholder)) {\n\t\t\tif (!(p.name in values)) {\n\t\t\t\tthrow new Error(`No value for placeholder \"${p.name}\" was provided`);\n\t\t\t}\n\n\t\t\treturn values[p.name];\n\t\t}\n\n\t\tif (is(p, Param) && is(p.value, Placeholder)) {\n\t\t\tif (!(p.value.name in values)) {\n\t\t\t\tthrow new Error(`No value for placeholder \"${p.value.name}\" was provided`);\n\t\t\t}\n\n\t\t\treturn p.encoder.mapToDriverValue(values[p.value.name]);\n\t\t}\n\n\t\treturn p;\n\t});\n}\n\nexport type ColumnsSelection = Record;\n\nexport abstract class View<\n\tTName extends string = string,\n\tTExisting extends boolean = boolean,\n\tTSelection extends ColumnsSelection = ColumnsSelection,\n> implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'View';\n\n\tdeclare _: {\n\t\tbrand: 'View';\n\t\tviewBrand: string;\n\t\tname: TName;\n\t\texisting: TExisting;\n\t\tselectedFields: TSelection;\n\t};\n\n\t/** @internal */\n\t[ViewBaseConfig]: {\n\t\tname: TName;\n\t\toriginalName: TName;\n\t\tschema: string | undefined;\n\t\tselectedFields: SelectedFields;\n\t\tisExisting: TExisting;\n\t\tquery: TExisting extends true ? undefined : SQL;\n\t\tisAlias: boolean;\n\t};\n\n\tconstructor(\n\t\t{ name, schema, selectedFields, query }: {\n\t\t\tname: TName;\n\t\t\tschema: string | undefined;\n\t\t\tselectedFields: SelectedFields;\n\t\t\tquery: SQL | undefined;\n\t\t},\n\t) {\n\t\tthis[ViewBaseConfig] = {\n\t\t\tname,\n\t\t\toriginalName: name,\n\t\t\tschema,\n\t\t\tselectedFields,\n\t\t\tquery: query as (TExisting extends true ? undefined : SQL),\n\t\t\tisExisting: !query as TExisting,\n\t\t\tisAlias: false,\n\t\t};\n\t}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n// Defined separately from the Column class to resolve circular dependency\nColumn.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n\n// Defined separately from the Table class to resolve circular dependency\nTable.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n\n// Defined separately from the Column class to resolve circular dependency\nSubquery.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport type { Writable } from '~/utils.ts';\nimport { PgColumn, PgColumnBuilder } from './common.ts';\n\nexport type PgEnumColumnBuilderInitial =\n\tPgEnumColumnBuilder<{\n\t\tname: TName;\n\t\tdataType: 'string';\n\t\tcolumnType: 'PgEnumColumn';\n\t\tdata: TValues[number];\n\t\tenumValues: TValues;\n\t\tdriverParam: string;\n\t\tgenerated: undefined;\n\t}>;\n\nconst isPgEnumSym = Symbol.for('drizzle:isPgEnum');\nexport interface PgEnum {\n\t(name: TName): PgEnumColumnBuilderInitial;\n\n\treadonly enumName: string;\n\treadonly enumValues: TValues;\n\treadonly schema: string | undefined;\n\t/** @internal */\n\t[isPgEnumSym]: true;\n}\n\nexport function isPgEnum(obj: unknown): obj is PgEnum<[string, ...string[]]> {\n\treturn !!obj && typeof obj === 'function' && isPgEnumSym in obj && obj[isPgEnumSym] === true;\n}\n\nexport class PgEnumColumnBuilder<\n\tT extends ColumnBuilderBaseConfig<'string', 'PgEnumColumn'> & { enumValues: [string, ...string[]] },\n> extends PgColumnBuilder }> {\n\tstatic readonly [entityKind]: string = 'PgEnumColumnBuilder';\n\n\tconstructor(name: string, enumInstance: PgEnum) {\n\t\tsuper(name, 'string', 'PgEnumColumn');\n\t\tthis.config.enum = enumInstance;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgEnumColumn> {\n\t\treturn new PgEnumColumn>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class PgEnumColumn & { enumValues: [string, ...string[]] }>\n\textends PgColumn }>\n{\n\tstatic readonly [entityKind]: string = 'PgEnumColumn';\n\n\treadonly enum = this.config.enum;\n\toverride readonly enumValues = this.config.enum.enumValues;\n\n\tconstructor(\n\t\ttable: AnyPgTable<{ name: T['tableName'] }>,\n\t\tconfig: PgEnumColumnBuilder['config'],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.enum = config.enum;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn this.enum.enumName;\n\t}\n}\n\n// Gratitude to zod for the enum function types\nexport function pgEnum>(\n\tenumName: string,\n\tvalues: T | Writable,\n): PgEnum> {\n\treturn pgEnumWithSchema(enumName, values, undefined);\n}\n\n/** @internal */\nexport function pgEnumWithSchema>(\n\tenumName: string,\n\tvalues: T | Writable,\n\tschema?: string,\n): PgEnum> {\n\tconst enumInstance: PgEnum> = Object.assign(\n\t\t(name: TName): PgEnumColumnBuilderInitial> =>\n\t\t\tnew PgEnumColumnBuilder(name, enumInstance),\n\t\t{\n\t\t\tenumName,\n\t\t\tenumValues: values,\n\t\t\tschema,\n\t\t\t[isPgEnumSym]: true,\n\t\t} as const,\n\t);\n\n\treturn enumInstance;\n}\n", "import type {\n\tColumnBuilderBase,\n\tColumnBuilderBaseConfig,\n\tColumnBuilderExtraConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tGeneratedColumnConfig,\n\tHasGenerated,\n\tMakeColumnConfig,\n} from '~/column-builder.ts';\nimport { ColumnBuilder } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { Column } from '~/column.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport type { Update } from '~/utils.ts';\n\nimport type { SQL } from '~/index.ts';\nimport type { ForeignKey, UpdateDeleteAction } from '~/pg-core/foreign-keys.ts';\nimport { ForeignKeyBuilder } from '~/pg-core/foreign-keys.ts';\nimport type { AnyPgTable, PgTable } from '~/pg-core/table.ts';\nimport { iife } from '~/tracing-utils.ts';\nimport type { PgIndexOpClass } from '../indexes.ts';\nimport { uniqueKeyName } from '../unique-constraint.ts';\nimport { makePgArray, parsePgArray } from '../utils/array.ts';\n\nexport interface ReferenceConfig {\n\tref: () => PgColumn;\n\tactions: {\n\t\tonUpdate?: UpdateDeleteAction;\n\t\tonDelete?: UpdateDeleteAction;\n\t};\n}\n\nexport interface PgColumnBuilderBase<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> extends ColumnBuilderBase {}\n\nexport abstract class PgColumnBuilder<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n\tTExtraConfig extends ColumnBuilderExtraConfig = ColumnBuilderExtraConfig,\n> extends ColumnBuilder\n\timplements PgColumnBuilderBase\n{\n\tprivate foreignKeyConfigs: ReferenceConfig[] = [];\n\n\tstatic readonly [entityKind]: string = 'PgColumnBuilder';\n\n\tarray(size?: number): PgArrayBuilder<\n\t\t& {\n\t\t\tname: T['name'];\n\t\t\tdataType: 'array';\n\t\t\tcolumnType: 'PgArray';\n\t\t\tdata: T['data'][];\n\t\t\tdriverParam: T['driverParam'][] | string;\n\t\t\tenumValues: T['enumValues'];\n\t\t\tgenerated: GeneratedColumnConfig;\n\t\t}\n\t\t& (T extends { notNull: true } ? { notNull: true } : {})\n\t\t& (T extends { hasDefault: true } ? { hasDefault: true } : {}),\n\t\tT\n\t> {\n\t\treturn new PgArrayBuilder(this.config.name, this as PgColumnBuilder, size);\n\t}\n\n\treferences(\n\t\tref: ReferenceConfig['ref'],\n\t\tactions: ReferenceConfig['actions'] = {},\n\t): this {\n\t\tthis.foreignKeyConfigs.push({ ref, actions });\n\t\treturn this;\n\t}\n\n\tunique(\n\t\tname?: string,\n\t\tconfig?: { nulls: 'distinct' | 'not distinct' },\n\t): this {\n\t\tthis.config.isUnique = true;\n\t\tthis.config.uniqueName = name;\n\t\tthis.config.uniqueType = config?.nulls;\n\t\treturn this;\n\t}\n\n\tgeneratedAlwaysAs(as: SQL | T['data'] | (() => SQL)): HasGenerated {\n\t\tthis.config.generated = {\n\t\t\tas,\n\t\t\ttype: 'always',\n\t\t\tmode: 'stored',\n\t\t};\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tbuildForeignKeys(column: PgColumn, table: PgTable): ForeignKey[] {\n\t\treturn this.foreignKeyConfigs.map(({ ref, actions }) => {\n\t\t\treturn iife(\n\t\t\t\t(ref, actions) => {\n\t\t\t\t\tconst builder = new ForeignKeyBuilder(() => {\n\t\t\t\t\t\tconst foreignColumn = ref();\n\t\t\t\t\t\treturn { columns: [column], foreignColumns: [foreignColumn] };\n\t\t\t\t\t});\n\t\t\t\t\tif (actions.onUpdate) {\n\t\t\t\t\t\tbuilder.onUpdate(actions.onUpdate);\n\t\t\t\t\t}\n\t\t\t\t\tif (actions.onDelete) {\n\t\t\t\t\t\tbuilder.onDelete(actions.onDelete);\n\t\t\t\t\t}\n\t\t\t\t\treturn builder.build(table);\n\t\t\t\t},\n\t\t\t\tref,\n\t\t\t\tactions,\n\t\t\t);\n\t\t});\n\t}\n\n\t/** @internal */\n\tabstract build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgColumn>;\n\n\t/** @internal */\n\tbuildExtraConfigColumn(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): ExtraConfigColumn {\n\t\treturn new ExtraConfigColumn(table, this.config);\n\t}\n}\n\n// To understand how to use `PgColumn` and `PgColumn`, see `Column` and `AnyColumn` documentation.\nexport abstract class PgColumn<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\tTRuntimeConfig extends object = {},\n\tTTypeConfig extends object = {},\n> extends Column {\n\tstatic readonly [entityKind]: string = 'PgColumn';\n\n\tconstructor(\n\t\toverride readonly table: PgTable,\n\t\tconfig: ColumnBuilderRuntimeConfig,\n\t) {\n\t\tif (!config.uniqueName) {\n\t\t\tconfig.uniqueName = uniqueKeyName(table, [config.name]);\n\t\t}\n\t\tsuper(table, config);\n\t}\n}\n\nexport type IndexedExtraConfigType = { order?: 'asc' | 'desc'; nulls?: 'first' | 'last'; opClass?: string };\n\nexport class ExtraConfigColumn<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'ExtraConfigColumn';\n\n\toverride getSQLType(): string {\n\t\treturn this.getSQLType();\n\t}\n\n\tindexConfig: IndexedExtraConfigType = {\n\t\torder: this.config.order ?? 'asc',\n\t\tnulls: this.config.nulls ?? 'last',\n\t\topClass: this.config.opClass,\n\t};\n\tdefaultConfig: IndexedExtraConfigType = {\n\t\torder: 'asc',\n\t\tnulls: 'last',\n\t\topClass: undefined,\n\t};\n\n\tasc(): Omit {\n\t\tthis.indexConfig.order = 'asc';\n\t\treturn this;\n\t}\n\n\tdesc(): Omit {\n\t\tthis.indexConfig.order = 'desc';\n\t\treturn this;\n\t}\n\n\tnullsFirst(): Omit {\n\t\tthis.indexConfig.nulls = 'first';\n\t\treturn this;\n\t}\n\n\tnullsLast(): Omit {\n\t\tthis.indexConfig.nulls = 'last';\n\t\treturn this;\n\t}\n\n\t/**\n\t * ### PostgreSQL documentation quote\n\t *\n\t * > An operator class with optional parameters can be specified for each column of an index.\n\t * The operator class identifies the operators to be used by the index for that column.\n\t * For example, a B-tree index on four-byte integers would use the int4_ops class;\n\t * this operator class includes comparison functions for four-byte integers.\n\t * In practice the default operator class for the column's data type is usually sufficient.\n\t * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.\n\t * For example, we might want to sort a complex-number data type either by absolute value or by real part.\n\t * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.\n\t * More information about operator classes check:\n\t *\n\t * ### Useful links\n\t * https://www.postgresql.org/docs/current/sql-createindex.html\n\t *\n\t * https://www.postgresql.org/docs/current/indexes-opclass.html\n\t *\n\t * https://www.postgresql.org/docs/current/xindex.html\n\t *\n\t * ### Additional types\n\t * If you have the `pg_vector` extension installed in your database, you can use the\n\t * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.\n\t *\n\t * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**\n\t *\n\t * @param opClass\n\t * @returns\n\t */\n\top(opClass: PgIndexOpClass): Omit {\n\t\tthis.indexConfig.opClass = opClass;\n\t\treturn this;\n\t}\n}\n\nexport class IndexedColumn {\n\tstatic readonly [entityKind]: string = 'IndexedColumn';\n\tconstructor(\n\t\tname: string | undefined,\n\t\ttype: string,\n\t\tindexConfig: IndexedExtraConfigType,\n\t) {\n\t\tthis.name = name;\n\t\tthis.type = type;\n\t\tthis.indexConfig = indexConfig;\n\t}\n\n\tname: string | undefined;\n\ttype: string;\n\tindexConfig: IndexedExtraConfigType;\n}\n\nexport type AnyPgColumn> = {}> = PgColumn<\n\tRequired, TPartial>>\n>;\n\nexport class PgArrayBuilder<\n\tT extends ColumnBuilderBaseConfig<'array', 'PgArray'>,\n\tTBase extends ColumnBuilderBaseConfig,\n> extends PgColumnBuilder<\n\tT,\n\t{\n\t\tbaseBuilder: PgColumnBuilder;\n\t\tsize: number | undefined;\n\t},\n\t{\n\t\tbaseBuilder: PgColumnBuilder;\n\t}\n> {\n\tstatic override readonly [entityKind] = 'PgArrayBuilder';\n\n\tconstructor(\n\t\tname: string,\n\t\tbaseBuilder: PgArrayBuilder['config']['baseBuilder'],\n\t\tsize: number | undefined,\n\t) {\n\t\tsuper(name, 'array', 'PgArray');\n\t\tthis.config.baseBuilder = baseBuilder;\n\t\tthis.config.size = size;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgArray, TBase> {\n\t\tconst baseColumn = this.config.baseBuilder.build(table);\n\t\treturn new PgArray, TBase>(\n\t\t\ttable as AnyPgTable<{ name: MakeColumnConfig['tableName'] }>,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t\tbaseColumn,\n\t\t);\n\t}\n}\n\nexport class PgArray<\n\tT extends ColumnBaseConfig<'array', 'PgArray'>,\n\tTBase extends ColumnBuilderBaseConfig,\n> extends PgColumn {\n\treadonly size: number | undefined;\n\n\tstatic readonly [entityKind]: string = 'PgArray';\n\n\tconstructor(\n\t\ttable: AnyPgTable<{ name: T['tableName'] }>,\n\t\tconfig: PgArrayBuilder['config'],\n\t\treadonly baseColumn: PgColumn,\n\t\treadonly range?: [number | undefined, number | undefined],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.size = config.size;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn `${this.baseColumn.getSQLType()}[${typeof this.size === 'number' ? this.size : ''}]`;\n\t}\n\n\toverride mapFromDriverValue(value: unknown[] | string): T['data'] {\n\t\tif (typeof value === 'string') {\n\t\t\t// Thank you node-postgres for not parsing enum arrays\n\t\t\tvalue = parsePgArray(value);\n\t\t}\n\t\treturn value.map((v) => this.baseColumn.mapFromDriverValue(v));\n\t}\n\n\toverride mapToDriverValue(value: unknown[], isNestedArray = false): unknown[] | string {\n\t\tconst a = value.map((v) =>\n\t\t\tv === null\n\t\t\t\t? null\n\t\t\t\t: is(this.baseColumn, PgArray)\n\t\t\t\t? this.baseColumn.mapToDriverValue(v as unknown[], true)\n\t\t\t\t: this.baseColumn.mapToDriverValue(v)\n\t\t);\n\t\tif (isNestedArray) return a;\n\t\treturn makePgArray(a);\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { Column } from './column.ts';\nimport type { MySqlColumn } from './mysql-core/index.ts';\nimport type { ExtraConfigColumn, PgColumn, PgSequenceOptions } from './pg-core/index.ts';\nimport type { SQL } from './sql/sql.ts';\nimport type { SQLiteColumn } from './sqlite-core/index.ts';\nimport type { Simplify } from './utils.ts';\n\nexport type ColumnDataType =\n\t| 'string'\n\t| 'number'\n\t| 'boolean'\n\t| 'array'\n\t| 'json'\n\t| 'date'\n\t| 'bigint'\n\t| 'custom'\n\t| 'buffer';\n\nexport type Dialect = 'pg' | 'mysql' | 'sqlite' | 'common';\n\nexport type GeneratedStorageMode = 'virtual' | 'stored';\n\nexport type GeneratedType = 'always' | 'byDefault';\n\nexport type GeneratedColumnConfig = {\n\tas: TDataType | SQL | (() => SQL);\n\ttype?: GeneratedType;\n\tmode?: GeneratedStorageMode;\n};\n\nexport type GeneratedIdentityConfig = {\n\tsequenceName?: string;\n\tsequenceOptions?: PgSequenceOptions;\n\ttype: 'always' | 'byDefault';\n};\n\nexport interface ColumnBuilderBaseConfig {\n\tname: string;\n\tdataType: TDataType;\n\tcolumnType: TColumnType;\n\tdata: unknown;\n\tdriverParam: unknown;\n\tenumValues: string[] | undefined;\n\tgenerated: GeneratedColumnConfig | undefined;\n}\n\nexport type MakeColumnConfig<\n\tT extends ColumnBuilderBaseConfig,\n\tTTableName extends string,\n\tTData = T extends { $type: infer U } ? U : T['data'],\n> = {\n\tname: T['name'];\n\ttableName: TTableName;\n\tdataType: T['dataType'];\n\tcolumnType: T['columnType'];\n\tdata: TData;\n\tdriverParam: T['driverParam'];\n\tnotNull: T extends { notNull: true } ? true : false;\n\thasDefault: T extends { hasDefault: true } ? true : false;\n\tisPrimaryKey: T extends { isPrimaryKey: true } ? true : false;\n\tisAutoincrement: T extends { isAutoincrement: true } ? true : false;\n\thasRuntimeDefault: T extends { hasRuntimeDefault: true } ? true : false;\n\tenumValues: T['enumValues'];\n\tbaseColumn: T extends { baseBuilder: infer U extends ColumnBuilderBase } ? BuildColumn\n\t\t: never;\n\tgenerated: T['generated'] extends object ? T['generated'] : undefined;\n} & {};\n\nexport type ColumnBuilderTypeConfig<\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tT extends ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> = Simplify<\n\t& {\n\t\tbrand: 'ColumnBuilder';\n\t\tname: T['name'];\n\t\tdataType: T['dataType'];\n\t\tcolumnType: T['columnType'];\n\t\tdata: T['data'];\n\t\tdriverParam: T['driverParam'];\n\t\tnotNull: T extends { notNull: infer U } ? U : boolean;\n\t\thasDefault: T extends { hasDefault: infer U } ? U : boolean;\n\t\tenumValues: T['enumValues'];\n\t\tgenerated: GeneratedColumnConfig | undefined;\n\t}\n\t& TTypeConfig\n>;\n\nexport type ColumnBuilderRuntimeConfig = {\n\tname: string;\n\tnotNull: boolean;\n\tdefault: TData | SQL | undefined;\n\tdefaultFn: (() => TData | SQL) | undefined;\n\tonUpdateFn: (() => TData | SQL) | undefined;\n\thasDefault: boolean;\n\tprimaryKey: boolean;\n\tisUnique: boolean;\n\tuniqueName: string | undefined;\n\tuniqueType: string | undefined;\n\tdataType: string;\n\tcolumnType: string;\n\tgenerated: GeneratedColumnConfig | undefined;\n\tgeneratedIdentity: GeneratedIdentityConfig | undefined;\n} & TRuntimeConfig;\n\nexport interface ColumnBuilderExtraConfig {\n\tprimaryKeyHasDefault?: boolean;\n}\n\nexport type NotNull = T & {\n\t_: {\n\t\tnotNull: true;\n\t};\n};\n\nexport type HasDefault = T & {\n\t_: {\n\t\thasDefault: true;\n\t};\n};\n\nexport type IsPrimaryKey = T & {\n\t_: {\n\t\tisPrimaryKey: true;\n\t};\n};\n\nexport type IsAutoincrement = T & {\n\t_: {\n\t\tisAutoincrement: true;\n\t};\n};\n\nexport type HasRuntimeDefault = T & {\n\t_: {\n\t\thasRuntimeDefault: true;\n\t};\n};\n\nexport type $Type = T & {\n\t_: {\n\t\t$type: TType;\n\t};\n};\n\nexport type HasGenerated = T & {\n\t_: {\n\t\thasDefault: true;\n\t\tgenerated: TGenerated;\n\t};\n};\n\nexport type IsIdentityByDefault<\n\tT extends ColumnBuilderBase,\n\tTType extends 'always' | 'byDefault',\n> = T & {\n\t_: {\n\t\tnotNull: true;\n\t\thasDefault: true;\n\t\tgenerated: { as: any; type: TType };\n\t};\n};\n\nexport interface ColumnBuilderBase<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> {\n\t_: ColumnBuilderTypeConfig;\n}\n\n// To understand how to use `ColumnBuilder` and `AnyColumnBuilder`, see `Column` and `AnyColumn` documentation.\nexport abstract class ColumnBuilder<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n\tTExtraConfig extends ColumnBuilderExtraConfig = ColumnBuilderExtraConfig,\n> implements ColumnBuilderBase {\n\tstatic readonly [entityKind]: string = 'ColumnBuilder';\n\n\tdeclare _: ColumnBuilderTypeConfig;\n\n\tprotected config: ColumnBuilderRuntimeConfig;\n\n\tconstructor(name: T['name'], dataType: T['dataType'], columnType: T['columnType']) {\n\t\tthis.config = {\n\t\t\tname,\n\t\t\tnotNull: false,\n\t\t\tdefault: undefined,\n\t\t\thasDefault: false,\n\t\t\tprimaryKey: false,\n\t\t\tisUnique: false,\n\t\t\tuniqueName: undefined,\n\t\t\tuniqueType: undefined,\n\t\t\tdataType,\n\t\t\tcolumnType,\n\t\t\tgenerated: undefined,\n\t\t} as ColumnBuilderRuntimeConfig;\n\t}\n\n\t/**\n\t * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.\n\t *\n\t * @example\n\t * ```ts\n\t * const users = pgTable('users', {\n\t * \tid: integer('id').$type().primaryKey(),\n\t * \tdetails: json('details').$type().notNull(),\n\t * });\n\t * ```\n\t */\n\t$type(): $Type {\n\t\treturn this as $Type;\n\t}\n\n\t/**\n\t * Adds a `not null` clause to the column definition.\n\t *\n\t * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.\n\t */\n\tnotNull(): NotNull {\n\t\tthis.config.notNull = true;\n\t\treturn this as NotNull;\n\t}\n\n\t/**\n\t * Adds a `default ` clause to the column definition.\n\t *\n\t * Affects the `insert` model of the table - columns *with* `default` are optional on insert.\n\t *\n\t * If you need to set a dynamic default value, use {@link $defaultFn} instead.\n\t */\n\tdefault(value: (this['_'] extends { $type: infer U } ? U : this['_']['data']) | SQL): HasDefault {\n\t\tthis.config.default = value;\n\t\tthis.config.hasDefault = true;\n\t\treturn this as HasDefault;\n\t}\n\n\t/**\n\t * Adds a dynamic default value to the column.\n\t * The function will be called when the row is inserted, and the returned value will be used as the column value.\n\t *\n\t * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n\t */\n\t$defaultFn(\n\t\tfn: () => (this['_'] extends { $type: infer U } ? U : this['_']['data']) | SQL,\n\t): HasRuntimeDefault> {\n\t\tthis.config.defaultFn = fn;\n\t\tthis.config.hasDefault = true;\n\t\treturn this as HasRuntimeDefault>;\n\t}\n\n\t/**\n\t * Alias for {@link $defaultFn}.\n\t */\n\t$default = this.$defaultFn;\n\n\t/**\n\t * Adds a dynamic update value to the column.\n\t * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.\n\t * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.\n\t *\n\t * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n\t */\n\t$onUpdateFn(\n\t\tfn: () => (this['_'] extends { $type: infer U } ? U : this['_']['data']) | SQL,\n\t): HasDefault {\n\t\tthis.config.onUpdateFn = fn;\n\t\tthis.config.hasDefault = true;\n\t\treturn this as HasDefault;\n\t}\n\n\t/**\n\t * Alias for {@link $onUpdateFn}.\n\t */\n\t$onUpdate = this.$onUpdateFn;\n\n\t/**\n\t * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.\n\t *\n\t * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.\n\t */\n\tprimaryKey(): TExtraConfig['primaryKeyHasDefault'] extends true ? IsPrimaryKey>>\n\t\t: IsPrimaryKey>\n\t{\n\t\tthis.config.primaryKey = true;\n\t\tthis.config.notNull = true;\n\t\treturn this as TExtraConfig['primaryKeyHasDefault'] extends true ? IsPrimaryKey>>\n\t\t\t: IsPrimaryKey>;\n\t}\n\n\tabstract generatedAlwaysAs(\n\t\tas: SQL | T['data'] | (() => SQL),\n\t\tconfig?: Partial>,\n\t): HasGenerated;\n}\n\nexport type BuildColumn<\n\tTTableName extends string,\n\tTBuilder extends ColumnBuilderBase,\n\tTDialect extends Dialect,\n> = TDialect extends 'pg' ? PgColumn>\n\t: TDialect extends 'mysql' ? MySqlColumn>\n\t: TDialect extends 'sqlite' ? SQLiteColumn>\n\t: TDialect extends 'common' ? Column>\n\t: never;\n\nexport type BuildIndexColumn<\n\tTDialect extends Dialect,\n> = TDialect extends 'pg' ? ExtraConfigColumn : never;\n\n// TODO\n// try to make sql as well + indexRaw\n\n// optional after everything will be working as expected\n// also try to leave only needed methods for extraConfig\n// make an error if I pass .asc() to fk and so on\n\nexport type BuildColumns<\n\tTTableName extends string,\n\tTConfigMap extends Record,\n\tTDialect extends Dialect,\n> =\n\t& {\n\t\t[Key in keyof TConfigMap]: BuildColumn;\n\t}\n\t& {};\n\nexport type BuildExtraConfigColumns<\n\t_TTableName extends string,\n\tTConfigMap extends Record,\n\tTDialect extends Dialect,\n> =\n\t& {\n\t\t[Key in keyof TConfigMap]: BuildIndexColumn;\n\t}\n\t& {};\n\nexport type ChangeColumnTableName =\n\tTDialect extends 'pg' ? PgColumn>\n\t\t: TDialect extends 'mysql' ? MySqlColumn>\n\t\t: TDialect extends 'sqlite' ? SQLiteColumn>\n\t\t: never;\n", "import { entityKind } from '~/entity.ts';\nimport type { AnyPgColumn, PgColumn } from './columns/index.ts';\nimport { PgTable } from './table.ts';\n\nexport type UpdateDeleteAction = 'cascade' | 'restrict' | 'no action' | 'set null' | 'set default';\n\nexport type Reference = () => {\n\treadonly name?: string;\n\treadonly columns: PgColumn[];\n\treadonly foreignTable: PgTable;\n\treadonly foreignColumns: PgColumn[];\n};\n\nexport class ForeignKeyBuilder {\n\tstatic readonly [entityKind]: string = 'PgForeignKeyBuilder';\n\n\t/** @internal */\n\treference: Reference;\n\n\t/** @internal */\n\t_onUpdate: UpdateDeleteAction | undefined = 'no action';\n\n\t/** @internal */\n\t_onDelete: UpdateDeleteAction | undefined = 'no action';\n\n\tconstructor(\n\t\tconfig: () => {\n\t\t\tname?: string;\n\t\t\tcolumns: PgColumn[];\n\t\t\tforeignColumns: PgColumn[];\n\t\t},\n\t\tactions?: {\n\t\t\tonUpdate?: UpdateDeleteAction;\n\t\t\tonDelete?: UpdateDeleteAction;\n\t\t} | undefined,\n\t) {\n\t\tthis.reference = () => {\n\t\t\tconst { name, columns, foreignColumns } = config();\n\t\t\treturn { name, columns, foreignTable: foreignColumns[0]!.table as PgTable, foreignColumns };\n\t\t};\n\t\tif (actions) {\n\t\t\tthis._onUpdate = actions.onUpdate;\n\t\t\tthis._onDelete = actions.onDelete;\n\t\t}\n\t}\n\n\tonUpdate(action: UpdateDeleteAction): this {\n\t\tthis._onUpdate = action === undefined ? 'no action' : action;\n\t\treturn this;\n\t}\n\n\tonDelete(action: UpdateDeleteAction): this {\n\t\tthis._onDelete = action === undefined ? 'no action' : action;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(table: PgTable): ForeignKey {\n\t\treturn new ForeignKey(table, this);\n\t}\n}\n\nexport type AnyForeignKeyBuilder = ForeignKeyBuilder;\n\nexport class ForeignKey {\n\tstatic readonly [entityKind]: string = 'PgForeignKey';\n\n\treadonly reference: Reference;\n\treadonly onUpdate: UpdateDeleteAction | undefined;\n\treadonly onDelete: UpdateDeleteAction | undefined;\n\n\tconstructor(readonly table: PgTable, builder: ForeignKeyBuilder) {\n\t\tthis.reference = builder.reference;\n\t\tthis.onUpdate = builder._onUpdate;\n\t\tthis.onDelete = builder._onDelete;\n\t}\n\n\tgetName(): string {\n\t\tconst { name, columns, foreignColumns } = this.reference();\n\t\tconst columnNames = columns.map((column) => column.name);\n\t\tconst foreignColumnNames = foreignColumns.map((column) => column.name);\n\t\tconst chunks = [\n\t\t\tthis.table[PgTable.Symbol.Name],\n\t\t\t...columnNames,\n\t\t\tforeignColumns[0]!.table[PgTable.Symbol.Name],\n\t\t\t...foreignColumnNames,\n\t\t];\n\t\treturn name ?? `${chunks.join('_')}_fk`;\n\t}\n}\n\ntype ColumnsWithTable<\n\tTTableName extends string,\n\tTColumns extends PgColumn[],\n> = { [Key in keyof TColumns]: AnyPgColumn<{ tableName: TTableName }> };\n\nexport function foreignKey<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends [AnyPgColumn<{ tableName: TTableName }>, ...AnyPgColumn<{ tableName: TTableName }>[]],\n>(\n\tconfig: {\n\t\tname?: string;\n\t\tcolumns: TColumns;\n\t\tforeignColumns: ColumnsWithTable;\n\t},\n): ForeignKeyBuilder {\n\tfunction mappedConfig() {\n\t\tconst { name, columns, foreignColumns } = config;\n\t\treturn {\n\t\t\tname,\n\t\t\tcolumns,\n\t\t\tforeignColumns,\n\t\t};\n\t}\n\n\treturn new ForeignKeyBuilder(mappedConfig);\n}\n", "import type { BuildColumns, BuildExtraConfigColumns } from '~/column-builder.ts';\nimport { entityKind } from '~/entity.ts';\nimport { Table, type TableConfig as TableConfigBase, type UpdateTableConfig } from '~/table.ts';\nimport type { CheckBuilder } from './checks.ts';\nimport type { PgColumn, PgColumnBuilder, PgColumnBuilderBase } from './columns/common.ts';\nimport type { ForeignKey, ForeignKeyBuilder } from './foreign-keys.ts';\nimport type { AnyIndexBuilder } from './indexes.ts';\nimport type { PrimaryKeyBuilder } from './primary-keys.ts';\nimport type { UniqueConstraintBuilder } from './unique-constraint.ts';\n\nexport type PgTableExtraConfig = Record<\n\tstring,\n\t| AnyIndexBuilder\n\t| CheckBuilder\n\t| ForeignKeyBuilder\n\t| PrimaryKeyBuilder\n\t| UniqueConstraintBuilder\n>;\n\nexport type TableConfig = TableConfigBase;\n\n/** @internal */\nexport const InlineForeignKeys = Symbol.for('drizzle:PgInlineForeignKeys');\n\nexport class PgTable extends Table {\n\tstatic readonly [entityKind]: string = 'PgTable';\n\n\t/** @internal */\n\tstatic override readonly Symbol = Object.assign({}, Table.Symbol, {\n\t\tInlineForeignKeys: InlineForeignKeys as typeof InlineForeignKeys,\n\t});\n\n\t/**@internal */\n\t[InlineForeignKeys]: ForeignKey[] = [];\n\n\t/** @internal */\n\toverride [Table.Symbol.ExtraConfigBuilder]: ((self: Record) => PgTableExtraConfig) | undefined =\n\t\tundefined;\n}\n\nexport type AnyPgTable = {}> = PgTable>;\n\nexport type PgTableWithColumns =\n\t& PgTable\n\t& {\n\t\t[Key in keyof T['columns']]: T['columns'][Key];\n\t};\n\n/** @internal */\nexport function pgTableWithSchema<\n\tTTableName extends string,\n\tTSchemaName extends string | undefined,\n\tTColumnsMap extends Record,\n>(\n\tname: TTableName,\n\tcolumns: TColumnsMap,\n\textraConfig: ((self: BuildExtraConfigColumns) => PgTableExtraConfig) | undefined,\n\tschema: TSchemaName,\n\tbaseName = name,\n): PgTableWithColumns<{\n\tname: TTableName;\n\tschema: TSchemaName;\n\tcolumns: BuildColumns;\n\tdialect: 'pg';\n}> {\n\tconst rawTable = new PgTable<{\n\t\tname: TTableName;\n\t\tschema: TSchemaName;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>(name, schema, baseName);\n\n\tconst builtColumns = Object.fromEntries(\n\t\tObject.entries(columns).map(([name, colBuilderBase]) => {\n\t\t\tconst colBuilder = colBuilderBase as PgColumnBuilder;\n\t\t\tconst column = colBuilder.build(rawTable);\n\t\t\trawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n\t\t\treturn [name, column];\n\t\t}),\n\t) as unknown as BuildColumns;\n\n\tconst builtColumnsForExtraConfig = Object.fromEntries(\n\t\tObject.entries(columns).map(([name, colBuilderBase]) => {\n\t\t\tconst colBuilder = colBuilderBase as PgColumnBuilder;\n\t\t\tconst column = colBuilder.buildExtraConfigColumn(rawTable);\n\t\t\treturn [name, column];\n\t\t}),\n\t) as unknown as BuildExtraConfigColumns;\n\n\tconst table = Object.assign(rawTable, builtColumns);\n\n\ttable[Table.Symbol.Columns] = builtColumns;\n\ttable[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;\n\n\tif (extraConfig) {\n\t\ttable[PgTable.Symbol.ExtraConfigBuilder] = extraConfig as any;\n\t}\n\n\treturn table;\n}\n\nexport interface PgTableFn {\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: TColumnsMap,\n\t\textraConfig?: (self: BuildExtraConfigColumns) => PgTableExtraConfig,\n\t): PgTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>;\n}\n\nexport const pgTable: PgTableFn = (name, columns, extraConfig) => {\n\treturn pgTableWithSchema(name, columns, extraConfig, undefined);\n};\n\nexport function pgTableCreator(customizeTableName: (name: string) => string): PgTableFn {\n\treturn (name, columns, extraConfig) => {\n\t\treturn pgTableWithSchema(customizeTableName(name) as typeof name, columns, extraConfig, undefined, name);\n\t};\n}\n", "import type { Column, GetColumnData } from './column.ts';\nimport { entityKind } from './entity.ts';\nimport type { OptionalKeyOnly, RequiredKeyOnly } from './operations.ts';\nimport type { ExtraConfigColumn } from './pg-core/index.ts';\nimport type { SQLWrapper } from './sql/sql.ts';\nimport type { Simplify, Update } from './utils.ts';\n\nexport interface TableConfig> {\n\tname: string;\n\tschema: string | undefined;\n\tcolumns: Record;\n\tdialect: string;\n}\n\nexport type UpdateTableConfig> = Required<\n\tUpdate\n>;\n\n/** @internal */\nexport const TableName = Symbol.for('drizzle:Name');\n\n/** @internal */\nexport const Schema = Symbol.for('drizzle:Schema');\n\n/** @internal */\nexport const Columns = Symbol.for('drizzle:Columns');\n\n/** @internal */\nexport const ExtraConfigColumns = Symbol.for('drizzle:ExtraConfigColumns');\n\n/** @internal */\nexport const OriginalName = Symbol.for('drizzle:OriginalName');\n\n/** @internal */\nexport const BaseName = Symbol.for('drizzle:BaseName');\n\n/** @internal */\nexport const IsAlias = Symbol.for('drizzle:IsAlias');\n\n/** @internal */\nexport const ExtraConfigBuilder = Symbol.for('drizzle:ExtraConfigBuilder');\n\nconst IsDrizzleTable = Symbol.for('drizzle:IsDrizzleTable');\n\nexport interface Table<\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tT extends TableConfig = TableConfig,\n> extends SQLWrapper {\n\t// SQLWrapper runtime implementation is defined in 'sql/sql.ts'\n}\n\nexport class Table implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Table';\n\n\tdeclare readonly _: {\n\t\treadonly brand: 'Table';\n\t\treadonly config: T;\n\t\treadonly name: T['name'];\n\t\treadonly schema: T['schema'];\n\t\treadonly columns: T['columns'];\n\t\treadonly inferSelect: InferSelectModel>;\n\t\treadonly inferInsert: InferInsertModel>;\n\t};\n\n\tdeclare readonly $inferSelect: InferSelectModel>;\n\tdeclare readonly $inferInsert: InferInsertModel>;\n\n\t/** @internal */\n\tstatic readonly Symbol = {\n\t\tName: TableName as typeof TableName,\n\t\tSchema: Schema as typeof Schema,\n\t\tOriginalName: OriginalName as typeof OriginalName,\n\t\tColumns: Columns as typeof Columns,\n\t\tExtraConfigColumns: ExtraConfigColumns as typeof ExtraConfigColumns,\n\t\tBaseName: BaseName as typeof BaseName,\n\t\tIsAlias: IsAlias as typeof IsAlias,\n\t\tExtraConfigBuilder: ExtraConfigBuilder as typeof ExtraConfigBuilder,\n\t};\n\n\t/**\n\t * @internal\n\t * Can be changed if the table is aliased.\n\t */\n\t[TableName]: string;\n\n\t/**\n\t * @internal\n\t * Used to store the original name of the table, before any aliasing.\n\t */\n\t[OriginalName]: string;\n\n\t/** @internal */\n\t[Schema]: string | undefined;\n\n\t/** @internal */\n\t[Columns]!: T['columns'];\n\n\t/** @internal */\n\t[ExtraConfigColumns]!: Record;\n\n\t/**\n\t * @internal\n\t * Used to store the table name before the transformation via the `tableCreator` functions.\n\t */\n\t[BaseName]: string;\n\n\t/** @internal */\n\t[IsAlias] = false;\n\n\t/** @internal */\n\t[IsDrizzleTable] = true;\n\n\t/** @internal */\n\t[ExtraConfigBuilder]: ((self: any) => Record) | undefined = undefined;\n\n\tconstructor(name: string, schema: string | undefined, baseName: string) {\n\t\tthis[TableName] = this[OriginalName] = name;\n\t\tthis[Schema] = schema;\n\t\tthis[BaseName] = baseName;\n\t}\n}\n\nexport function isTable(table: unknown): table is Table {\n\treturn typeof table === 'object' && table !== null && IsDrizzleTable in table;\n}\n\n/**\n * Any table with a specified boundary.\n *\n * @example\n\t```ts\n\t// Any table with a specific name\n\ttype AnyUsersTable = AnyTable<{ name: 'users' }>;\n\t```\n *\n * To describe any table with any config, simply use `Table` without any type arguments, like this:\n *\n\t```ts\n\tfunction needsTable(table: Table) {\n\t\t...\n\t}\n\t```\n */\nexport type AnyTable> = Table>;\n\nexport function getTableName(table: T): T['_']['name'] {\n\treturn table[TableName];\n}\n\nexport function getTableUniqueName(table: T): `${T['_']['schema']}.${T['_']['name']}` {\n\treturn `${table[Schema] ?? 'public'}.${table[TableName]}`;\n}\n\nexport type MapColumnName =\n\tTDBColumNames extends true ? TColumn['_']['name']\n\t\t: TName;\n\nexport type InferModelFromColumns<\n\tTColumns extends Record,\n\tTInferMode extends 'select' | 'insert' = 'select',\n\tTConfig extends { dbColumnNames: boolean } = { dbColumnNames: false },\n> = Simplify<\n\tTInferMode extends 'insert' ?\n\t\t\t& {\n\t\t\t\t[\n\t\t\t\t\tKey in keyof TColumns & string as RequiredKeyOnly<\n\t\t\t\t\t\tMapColumnName,\n\t\t\t\t\t\tTColumns[Key]\n\t\t\t\t\t>\n\t\t\t\t]: GetColumnData;\n\t\t\t}\n\t\t\t& {\n\t\t\t\t[\n\t\t\t\t\tKey in keyof TColumns & string as OptionalKeyOnly<\n\t\t\t\t\t\tMapColumnName,\n\t\t\t\t\t\tTColumns[Key]\n\t\t\t\t\t>\n\t\t\t\t]?: GetColumnData;\n\t\t\t}\n\t\t: {\n\t\t\t[\n\t\t\t\tKey in keyof TColumns & string as MapColumnName<\n\t\t\t\t\tKey,\n\t\t\t\t\tTColumns[Key],\n\t\t\t\t\tTConfig['dbColumnNames']\n\t\t\t\t>\n\t\t\t]: GetColumnData;\n\t\t}\n>;\n\n/** @deprecated Use one of the alternatives: {@link InferSelectModel} / {@link InferInsertModel}, or `table.$inferSelect` / `table.$inferInsert`\n */\nexport type InferModel<\n\tTTable extends Table,\n\tTInferMode extends 'select' | 'insert' = 'select',\n\tTConfig extends { dbColumnNames: boolean } = { dbColumnNames: false },\n> = InferModelFromColumns;\n\nexport type InferSelectModel<\n\tTTable extends Table,\n\tTConfig extends { dbColumnNames: boolean } = { dbColumnNames: false },\n> = InferModelFromColumns;\n\nexport type InferInsertModel<\n\tTTable extends Table,\n\tTConfig extends { dbColumnNames: boolean } = { dbColumnNames: false },\n> = InferModelFromColumns;\n", "export function iife(fn: (...args: T) => U, ...args: T): U {\n\treturn fn(...args);\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { PgColumn } from './columns/index.ts';\nimport { PgTable } from './table.ts';\n\nexport function unique(name?: string): UniqueOnConstraintBuilder {\n\treturn new UniqueOnConstraintBuilder(name);\n}\n\nexport function uniqueKeyName(table: PgTable, columns: string[]) {\n\treturn `${table[PgTable.Symbol.Name]}_${columns.join('_')}_unique`;\n}\n\nexport class UniqueConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'PgUniqueConstraintBuilder';\n\n\t/** @internal */\n\tcolumns: PgColumn[];\n\t/** @internal */\n\tnullsNotDistinctConfig = false;\n\n\tconstructor(\n\t\tcolumns: PgColumn[],\n\t\tprivate name?: string,\n\t) {\n\t\tthis.columns = columns;\n\t}\n\n\tnullsNotDistinct() {\n\t\tthis.nullsNotDistinctConfig = true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(table: PgTable): UniqueConstraint {\n\t\treturn new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name);\n\t}\n}\n\nexport class UniqueOnConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'PgUniqueOnConstraintBuilder';\n\n\t/** @internal */\n\tname?: string;\n\n\tconstructor(\n\t\tname?: string,\n\t) {\n\t\tthis.name = name;\n\t}\n\n\ton(...columns: [PgColumn, ...PgColumn[]]) {\n\t\treturn new UniqueConstraintBuilder(columns, this.name);\n\t}\n}\n\nexport class UniqueConstraint {\n\tstatic readonly [entityKind]: string = 'PgUniqueConstraint';\n\n\treadonly columns: PgColumn[];\n\treadonly name?: string;\n\treadonly nullsNotDistinct: boolean = false;\n\n\tconstructor(readonly table: PgTable, columns: PgColumn[], nullsNotDistinct: boolean, name?: string) {\n\t\tthis.columns = columns;\n\t\tthis.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));\n\t\tthis.nullsNotDistinct = nullsNotDistinct;\n\t}\n\n\tgetName() {\n\t\treturn this.name;\n\t}\n}\n", "function parsePgArrayValue(arrayString: string, startFrom: number, inQuotes: boolean): [string, number] {\n\tfor (let i = startFrom; i < arrayString.length; i++) {\n\t\tconst char = arrayString[i];\n\n\t\tif (char === '\\\\') {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\treturn [arrayString.slice(startFrom, i).replace(/\\\\/g, ''), i + 1];\n\t\t}\n\n\t\tif (inQuotes) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === ',' || char === '}') {\n\t\t\treturn [arrayString.slice(startFrom, i).replace(/\\\\/g, ''), i];\n\t\t}\n\t}\n\n\treturn [arrayString.slice(startFrom).replace(/\\\\/g, ''), arrayString.length];\n}\n\nexport function parsePgNestedArray(arrayString: string, startFrom = 0): [any[], number] {\n\tconst result: any[] = [];\n\tlet i = startFrom;\n\tlet lastCharIsComma = false;\n\n\twhile (i < arrayString.length) {\n\t\tconst char = arrayString[i];\n\n\t\tif (char === ',') {\n\t\t\tif (lastCharIsComma || i === startFrom) {\n\t\t\t\tresult.push('');\n\t\t\t}\n\t\t\tlastCharIsComma = true;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlastCharIsComma = false;\n\n\t\tif (char === '\\\\') {\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tconst [value, startFrom] = parsePgArrayValue(arrayString, i + 1, true);\n\t\t\tresult.push(value);\n\t\t\ti = startFrom;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '}') {\n\t\t\treturn [result, i + 1];\n\t\t}\n\n\t\tif (char === '{') {\n\t\t\tconst [value, startFrom] = parsePgNestedArray(arrayString, i + 1);\n\t\t\tresult.push(value);\n\t\t\ti = startFrom;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);\n\t\tresult.push(value);\n\t\ti = newStartFrom;\n\t}\n\n\treturn [result, i];\n}\n\nexport function parsePgArray(arrayString: string): any[] {\n\tconst [result] = parsePgNestedArray(arrayString, 1);\n\treturn result;\n}\n\nexport function makePgArray(array: any[]): string {\n\treturn `{${\n\t\tarray.map((item) => {\n\t\t\tif (Array.isArray(item)) {\n\t\t\t\treturn makePgArray(item);\n\t\t\t}\n\n\t\t\tif (typeof item === 'string') {\n\t\t\t\treturn `\"${item.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n\t\t\t}\n\n\t\t\treturn `${item}`;\n\t\t}).join(',')\n\t}}`;\n}\n", "import { entityKind } from './entity.ts';\nimport type { SQL, SQLWrapper } from './sql/sql.ts';\n\nexport interface Subquery<\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTAlias extends string = string,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTSelectedFields extends Record = Record,\n> extends SQLWrapper {\n\t// SQLWrapper runtime implementation is defined in 'sql/sql.ts'\n}\nexport class Subquery<\n\tTAlias extends string = string,\n\tTSelectedFields extends Record = Record,\n> implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Subquery';\n\n\tdeclare _: {\n\t\tbrand: 'Subquery';\n\t\tsql: SQL;\n\t\tselectedFields: TSelectedFields;\n\t\talias: TAlias;\n\t\tisWith: boolean;\n\t};\n\n\tconstructor(sql: SQL, selection: Record, alias: string, isWith = false) {\n\t\tthis._ = {\n\t\t\tbrand: 'Subquery',\n\t\t\tsql,\n\t\t\tselectedFields: selection as TSelectedFields,\n\t\t\talias: alias as TAlias,\n\t\t\tisWith,\n\t\t};\n\t}\n\n\t// getSQL(): SQL {\n\t// \treturn new SQL([this]);\n\t// }\n}\n\nexport class WithSubquery<\n\tTAlias extends string = string,\n\tTSelection extends Record = Record,\n> extends Subquery {\n\tstatic readonly [entityKind]: string = 'WithSubquery';\n}\n", "import type { Span, Tracer } from '@opentelemetry/api';\nimport { iife } from '~/tracing-utils.ts';\nimport { npmVersion } from '~/version.ts';\n\nlet otel: typeof import('@opentelemetry/api') | undefined;\nlet rawTracer: Tracer | undefined;\n// try {\n// \totel = await import('@opentelemetry/api');\n// } catch (err: any) {\n// \tif (err.code !== 'MODULE_NOT_FOUND' && err.code !== 'ERR_MODULE_NOT_FOUND') {\n// \t\tthrow err;\n// \t}\n// }\n\ntype SpanName =\n\t| 'drizzle.operation'\n\t| 'drizzle.prepareQuery'\n\t| 'drizzle.buildSQL'\n\t| 'drizzle.execute'\n\t| 'drizzle.driver.execute'\n\t| 'drizzle.mapResponse';\n\n/** @internal */\nexport const tracer = {\n\tstartActiveSpan unknown>(name: SpanName, fn: F): ReturnType {\n\t\tif (!otel) {\n\t\t\treturn fn() as ReturnType;\n\t\t}\n\n\t\tif (!rawTracer) {\n\t\t\trawTracer = otel.trace.getTracer('drizzle-orm', npmVersion);\n\t\t}\n\n\t\treturn iife(\n\t\t\t(otel, rawTracer) =>\n\t\t\t\trawTracer.startActiveSpan(\n\t\t\t\t\tname,\n\t\t\t\t\t((span: Span) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn fn(span);\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tspan.setStatus({\n\t\t\t\t\t\t\t\tcode: otel.SpanStatusCode.ERROR,\n\t\t\t\t\t\t\t\tmessage: e instanceof Error ? e.message : 'Unknown error', // eslint-disable-line no-instanceof/no-instanceof\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tspan.end();\n\t\t\t\t\t\t}\n\t\t\t\t\t}) as F,\n\t\t\t\t),\n\t\t\totel,\n\t\t\trawTracer,\n\t\t);\n\t},\n};\n", "// package.json\nvar version = \"0.33.0\";\n\n// src/version.ts\nvar compatibilityVersion = 7;\nexport {\n compatibilityVersion,\n version as npmVersion\n};\n", "export const ViewBaseConfig = Symbol.for('drizzle:ViewBaseConfig');\n", "import { entityKind } from '~/entity.ts';\n\nexport class DrizzleError extends Error {\n\tstatic readonly [entityKind]: string = 'DrizzleError';\n\n\tconstructor({ message, cause }: { message?: string; cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = 'DrizzleError';\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class TransactionRollbackError extends DrizzleError {\n\tstatic readonly [entityKind]: string = 'TransactionRollbackError';\n\n\tconstructor() {\n\t\tsuper({ message: 'Rollback' });\n\t}\n}\n", "import { type AnyColumn, Column, type GetColumnData } from '~/column.ts';\nimport { is } from '~/entity.ts';\nimport { Table } from '~/table.ts';\nimport {\n\tisDriverValueEncoder,\n\tisSQLWrapper,\n\tParam,\n\tPlaceholder,\n\tSQL,\n\tsql,\n\ttype SQLChunk,\n\ttype SQLWrapper,\n\tStringChunk,\n\tView,\n} from '../sql.ts';\n\nexport function bindIfParam(value: unknown, column: SQLWrapper): SQLChunk {\n\tif (\n\t\tisDriverValueEncoder(column)\n\t\t&& !isSQLWrapper(value)\n\t\t&& !is(value, Param)\n\t\t&& !is(value, Placeholder)\n\t\t&& !is(value, Column)\n\t\t&& !is(value, Table)\n\t\t&& !is(value, View)\n\t) {\n\t\treturn new Param(value, column);\n\t}\n\treturn value as SQLChunk;\n}\n\nexport interface BinaryOperator {\n\t(\n\t\tleft: TColumn,\n\t\tright: GetColumnData | SQLWrapper,\n\t): SQL;\n\t(left: SQL.Aliased, right: T | SQLWrapper): SQL;\n\t(\n\t\tleft: Exclude,\n\t\tright: unknown,\n\t): SQL;\n}\n\n/**\n * Test that two values are equal.\n *\n * Remember that the SQL standard dictates that\n * two NULL values are not equal, so if you want to test\n * whether a value is null, you may want to use\n * `isNull` instead.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made by Ford\n * db.select().from(cars)\n * .where(eq(cars.make, 'Ford'))\n * ```\n *\n * @see isNull for a way to test equality to NULL.\n */\nexport const eq: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} = ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that two values are not equal.\n *\n * Remember that the SQL standard dictates that\n * two NULL values are not equal, so if you want to test\n * whether a value is not null, you may want to use\n * `isNotNull` instead.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars not made by Ford\n * db.select().from(cars)\n * .where(ne(cars.make, 'Ford'))\n * ```\n *\n * @see isNotNull for a way to test whether a value is not null.\n */\nexport const ne: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} <> ${bindIfParam(right, left)}`;\n};\n\n/**\n * Combine a list of conditions with the `and` operator. Conditions\n * that are equal `undefined` are automatically ignored.\n *\n * ## Examples\n *\n * ```ts\n * db.select().from(cars)\n * .where(\n * and(\n * eq(cars.make, 'Volvo'),\n * eq(cars.year, 1950),\n * )\n * )\n * ```\n */\nexport function and(...conditions: (SQLWrapper | undefined)[]): SQL | undefined;\nexport function and(\n\t...unfilteredConditions: (SQLWrapper | undefined)[]\n): SQL | undefined {\n\tconst conditions = unfilteredConditions.filter(\n\t\t(c): c is Exclude => c !== undefined,\n\t);\n\n\tif (conditions.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tif (conditions.length === 1) {\n\t\treturn new SQL(conditions);\n\t}\n\n\treturn new SQL([\n\t\tnew StringChunk('('),\n\t\tsql.join(conditions, new StringChunk(' and ')),\n\t\tnew StringChunk(')'),\n\t]);\n}\n\n/**\n * Combine a list of conditions with the `or` operator. Conditions\n * that are equal `undefined` are automatically ignored.\n *\n * ## Examples\n *\n * ```ts\n * db.select().from(cars)\n * .where(\n * or(\n * eq(cars.make, 'GM'),\n * eq(cars.make, 'Ford'),\n * )\n * )\n * ```\n */\nexport function or(...conditions: (SQLWrapper | undefined)[]): SQL | undefined;\nexport function or(\n\t...unfilteredConditions: (SQLWrapper | undefined)[]\n): SQL | undefined {\n\tconst conditions = unfilteredConditions.filter(\n\t\t(c): c is Exclude => c !== undefined,\n\t);\n\n\tif (conditions.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tif (conditions.length === 1) {\n\t\treturn new SQL(conditions);\n\t}\n\n\treturn new SQL([\n\t\tnew StringChunk('('),\n\t\tsql.join(conditions, new StringChunk(' or ')),\n\t\tnew StringChunk(')'),\n\t]);\n}\n\n/**\n * Negate the meaning of an expression using the `not` keyword.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars _not_ made by GM or Ford.\n * db.select().from(cars)\n * .where(not(inArray(cars.make, ['GM', 'Ford'])))\n * ```\n */\nexport function not(condition: SQLWrapper): SQL {\n\treturn sql`not ${condition}`;\n}\n\n/**\n * Test that the first expression passed is greater than\n * the second expression.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made after 2000.\n * db.select().from(cars)\n * .where(gt(cars.year, 2000))\n * ```\n *\n * @see gte for greater-than-or-equal\n */\nexport const gt: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} > ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that the first expression passed is greater than\n * or equal to the second expression. Use `gt` to\n * test whether an expression is strictly greater\n * than another.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made on or after 2000.\n * db.select().from(cars)\n * .where(gte(cars.year, 2000))\n * ```\n *\n * @see gt for a strictly greater-than condition\n */\nexport const gte: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} >= ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that the first expression passed is less than\n * the second expression.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made before 2000.\n * db.select().from(cars)\n * .where(lt(cars.year, 2000))\n * ```\n *\n * @see lte for less-than-or-equal\n */\nexport const lt: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} < ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that the first expression passed is less than\n * or equal to the second expression.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made before 2000.\n * db.select().from(cars)\n * .where(lte(cars.year, 2000))\n * ```\n *\n * @see lt for a strictly less-than condition\n */\nexport const lte: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} <= ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test whether the first parameter, a column or expression,\n * has a value from a list passed as the second argument.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made by Ford or GM.\n * db.select().from(cars)\n * .where(inArray(cars.make, ['Ford', 'GM']))\n * ```\n *\n * @see notInArray for the inverse of this test\n */\nexport function inArray(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function inArray(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function inArray(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function inArray(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\treturn sql`false`;\n\t\t}\n\t\treturn sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;\n\t}\n\n\treturn sql`${column} in ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test whether the first parameter, a column or expression,\n * has a value that is not present in a list passed as the\n * second argument.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made by any company except Ford or GM.\n * db.select().from(cars)\n * .where(notInArray(cars.make, ['Ford', 'GM']))\n * ```\n *\n * @see inArray for the inverse of this test\n */\nexport function notInArray(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function notInArray(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function notInArray(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function notInArray(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\treturn sql`true`;\n\t\t}\n\t\treturn sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;\n\t}\n\n\treturn sql`${column} not in ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test whether an expression is NULL. By the SQL standard,\n * NULL is neither equal nor not equal to itself, so\n * it's recommended to use `isNull` and `notIsNull` for\n * comparisons to NULL.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars that have no discontinuedAt date.\n * db.select().from(cars)\n * .where(isNull(cars.discontinuedAt))\n * ```\n *\n * @see isNotNull for the inverse of this test\n */\nexport function isNull(value: SQLWrapper): SQL {\n\treturn sql`${value} is null`;\n}\n\n/**\n * Test whether an expression is not NULL. By the SQL standard,\n * NULL is neither equal nor not equal to itself, so\n * it's recommended to use `isNull` and `notIsNull` for\n * comparisons to NULL.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars that have been discontinued.\n * db.select().from(cars)\n * .where(isNotNull(cars.discontinuedAt))\n * ```\n *\n * @see isNull for the inverse of this test\n */\nexport function isNotNull(value: SQLWrapper): SQL {\n\treturn sql`${value} is not null`;\n}\n\n/**\n * Test whether a subquery evaluates to have any rows.\n *\n * ## Examples\n *\n * ```ts\n * // Users whose `homeCity` column has a match in a cities\n * // table.\n * db\n * .select()\n * .from(users)\n * .where(\n * exists(db.select()\n * .from(cities)\n * .where(eq(users.homeCity, cities.id))),\n * );\n * ```\n *\n * @see notExists for the inverse of this test\n */\nexport function exists(subquery: SQLWrapper): SQL {\n\treturn sql`exists ${subquery}`;\n}\n\n/**\n * Test whether a subquery doesn't include any result\n * rows.\n *\n * ## Examples\n *\n * ```ts\n * // Users whose `homeCity` column doesn't match\n * // a row in the cities table.\n * db\n * .select()\n * .from(users)\n * .where(\n * notExists(db.select()\n * .from(cities)\n * .where(eq(users.homeCity, cities.id))),\n * );\n * ```\n *\n * @see exists for the inverse of this test\n */\nexport function notExists(subquery: SQLWrapper): SQL {\n\treturn sql`not exists ${subquery}`;\n}\n\n/**\n * Test whether an expression is between two values. This\n * is an easier way to express range tests, which would be\n * expressed mathematically as `x <= a <= y` but in SQL\n * would have to be like `a >= x AND a <= y`.\n *\n * Between is inclusive of the endpoints: if `column`\n * is equal to `min` or `max`, it will be TRUE.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made between 1990 and 2000\n * db.select().from(cars)\n * .where(between(cars.year, 1990, 2000))\n * ```\n *\n * @see notBetween for the inverse of this test\n */\nexport function between(\n\tcolumn: SQL.Aliased,\n\tmin: T | SQLWrapper,\n\tmax: T | SQLWrapper,\n): SQL;\nexport function between(\n\tcolumn: TColumn,\n\tmin: GetColumnData | SQLWrapper,\n\tmax: GetColumnData | SQLWrapper,\n): SQL;\nexport function between(\n\tcolumn: Exclude,\n\tmin: unknown,\n\tmax: unknown,\n): SQL;\nexport function between(column: SQLWrapper, min: unknown, max: unknown): SQL {\n\treturn sql`${column} between ${bindIfParam(min, column)} and ${\n\t\tbindIfParam(\n\t\t\tmax,\n\t\t\tcolumn,\n\t\t)\n\t}`;\n}\n\n/**\n * Test whether an expression is not between two values.\n *\n * This, like `between`, includes its endpoints, so if\n * the `column` is equal to `min` or `max`, in this case\n * it will evaluate to FALSE.\n *\n * ## Examples\n *\n * ```ts\n * // Exclude cars made in the 1970s\n * db.select().from(cars)\n * .where(notBetween(cars.year, 1970, 1979))\n * ```\n *\n * @see between for the inverse of this test\n */\nexport function notBetween(\n\tcolumn: SQL.Aliased,\n\tmin: T | SQLWrapper,\n\tmax: T | SQLWrapper,\n): SQL;\nexport function notBetween(\n\tcolumn: TColumn,\n\tmin: GetColumnData | SQLWrapper,\n\tmax: GetColumnData | SQLWrapper,\n): SQL;\nexport function notBetween(\n\tcolumn: Exclude,\n\tmin: unknown,\n\tmax: unknown,\n): SQL;\nexport function notBetween(\n\tcolumn: SQLWrapper,\n\tmin: unknown,\n\tmax: unknown,\n): SQL {\n\treturn sql`${column} not between ${\n\t\tbindIfParam(\n\t\t\tmin,\n\t\t\tcolumn,\n\t\t)\n\t} and ${bindIfParam(max, column)}`;\n}\n\n/**\n * Compare a column to a pattern, which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars with 'Turbo' in their names.\n * db.select().from(cars)\n * .where(like(cars.name, '%Turbo%'))\n * ```\n *\n * @see ilike for a case-insensitive version of this condition\n */\nexport function like(column: Column, value: string | SQLWrapper): SQL {\n\treturn sql`${column} like ${value}`;\n}\n\n/**\n * The inverse of like - this tests that a given column\n * does not match a pattern, which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars that don't have \"ROver\" in their name.\n * db.select().from(cars)\n * .where(notLike(cars.name, '%Rover%'))\n * ```\n *\n * @see like for the inverse condition\n * @see notIlike for a case-insensitive version of this condition\n */\nexport function notLike(column: Column, value: string | SQLWrapper): SQL {\n\treturn sql`${column} not like ${value}`;\n}\n\n/**\n * Case-insensitively compare a column to a pattern,\n * which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * Unlike like, this performs a case-insensitive comparison.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars with 'Turbo' in their names.\n * db.select().from(cars)\n * .where(ilike(cars.name, '%Turbo%'))\n * ```\n *\n * @see like for a case-sensitive version of this condition\n */\nexport function ilike(column: Column, value: string | SQLWrapper): SQL {\n\treturn sql`${column} ilike ${value}`;\n}\n\n/**\n * The inverse of ilike - this case-insensitively tests that a given column\n * does not match a pattern, which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars that don't have \"Rover\" in their name.\n * db.select().from(cars)\n * .where(notLike(cars.name, '%Rover%'))\n * ```\n *\n * @see ilike for the inverse condition\n * @see notLike for a case-sensitive version of this condition\n */\nexport function notIlike(column: Column, value: string | SQLWrapper): SQL {\n\treturn sql`${column} not ilike ${value}`;\n}\n\n/**\n * Test that a column or expression contains all elements of\n * the list passed as the second argument.\n *\n * ## Throws\n *\n * The argument passed in the second array can't be empty:\n * if an empty is provided, this method will throw.\n *\n * ## Examples\n *\n * ```ts\n * // Select posts where its tags contain \"Typescript\" and \"ORM\".\n * db.select().from(posts)\n * .where(arrayContains(posts.tags, ['Typescript', 'ORM']))\n * ```\n *\n * @see arrayContained to find if an array contains all elements of a column or expression\n * @see arrayOverlaps to find if a column or expression contains any elements of an array\n */\nexport function arrayContains(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContains(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContains(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function arrayContains(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('arrayContains requires at least one value');\n\t\t}\n\t\tconst array = sql`${bindIfParam(values, column)}`;\n\t\treturn sql`${column} @> ${array}`;\n\t}\n\n\treturn sql`${column} @> ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test that the list passed as the second argument contains\n * all elements of a column or expression.\n *\n * ## Throws\n *\n * The argument passed in the second array can't be empty:\n * if an empty is provided, this method will throw.\n *\n * ## Examples\n *\n * ```ts\n * // Select posts where its tags contain \"Typescript\", \"ORM\" or both,\n * // but filtering posts that have additional tags.\n * db.select().from(posts)\n * .where(arrayContained(posts.tags, ['Typescript', 'ORM']))\n * ```\n *\n * @see arrayContains to find if a column or expression contains all elements of an array\n * @see arrayOverlaps to find if a column or expression contains any elements of an array\n */\nexport function arrayContained(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContained(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContained(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function arrayContained(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('arrayContained requires at least one value');\n\t\t}\n\t\tconst array = sql`${bindIfParam(values, column)}`;\n\t\treturn sql`${column} <@ ${array}`;\n\t}\n\n\treturn sql`${column} <@ ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test that a column or expression contains any elements of\n * the list passed as the second argument.\n *\n * ## Throws\n *\n * The argument passed in the second array can't be empty:\n * if an empty is provided, this method will throw.\n *\n * ## Examples\n *\n * ```ts\n * // Select posts where its tags contain \"Typescript\", \"ORM\" or both.\n * db.select().from(posts)\n * .where(arrayOverlaps(posts.tags, ['Typescript', 'ORM']))\n * ```\n *\n * @see arrayContains to find if a column or expression contains all elements of an array\n * @see arrayContained to find if an array contains all elements of a column or expression\n */\nexport function arrayOverlaps(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayOverlaps(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayOverlaps(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function arrayOverlaps(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('arrayOverlaps requires at least one value');\n\t\t}\n\t\tconst array = sql`${bindIfParam(values, column)}`;\n\t\treturn sql`${column} && ${array}`;\n\t}\n\n\treturn sql`${column} && ${bindIfParam(values, column)}`;\n}\n", "import type { AnyColumn } from '../../column.ts';\nimport type { SQL, SQLWrapper } from '../sql.ts';\nimport { sql } from '../sql.ts';\n\n/**\n * Used in sorting, this specifies that the given\n * column or expression should be sorted in ascending\n * order. By the SQL standard, ascending order is the\n * default, so it is not usually necessary to specify\n * ascending sort order.\n *\n * ## Examples\n *\n * ```ts\n * // Return cars, starting with the oldest models\n * // and going in ascending order to the newest.\n * db.select().from(cars)\n * .orderBy(asc(cars.year));\n * ```\n *\n * @see desc to sort in descending order\n */\nexport function asc(column: AnyColumn | SQLWrapper): SQL {\n\treturn sql`${column} asc`;\n}\n\n/**\n * Used in sorting, this specifies that the given\n * column or expression should be sorted in descending\n * order.\n *\n * ## Examples\n *\n * ```ts\n * // Select users, with the most recently created\n * // records coming first.\n * db.select().from(users)\n * .orderBy(desc(users.createdAt));\n * ```\n *\n * @see asc to sort in ascending order\n */\nexport function desc(column: AnyColumn | SQLWrapper): SQL {\n\treturn sql`${column} desc`;\n}\n", "import { entityKind } from '~/entity.ts';\n\nexport interface Logger {\n\tlogQuery(query: string, params: unknown[]): void;\n}\n\nexport interface LogWriter {\n\twrite(message: string): void;\n}\n\nexport class ConsoleLogWriter implements LogWriter {\n\tstatic readonly [entityKind]: string = 'ConsoleLogWriter';\n\n\twrite(message: string) {\n\t\tconsole.log(message);\n\t}\n}\n\nexport class DefaultLogger implements Logger {\n\tstatic readonly [entityKind]: string = 'DefaultLogger';\n\n\treadonly writer: LogWriter;\n\n\tconstructor(config?: { writer: LogWriter }) {\n\t\tthis.writer = config?.writer ?? new ConsoleLogWriter();\n\t}\n\n\tlogQuery(query: string, params: unknown[]): void {\n\t\tconst stringifiedParams = params.map((p) => {\n\t\t\ttry {\n\t\t\t\treturn JSON.stringify(p);\n\t\t\t} catch {\n\t\t\t\treturn String(p);\n\t\t\t}\n\t\t});\n\t\tconst paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(', ')}]` : '';\n\t\tthis.writer.write(`Query: ${query}${paramsStr}`);\n\t}\n}\n\nexport class NoopLogger implements Logger {\n\tstatic readonly [entityKind]: string = 'NoopLogger';\n\n\tlogQuery(): void {\n\t\t// noop\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\n\nexport abstract class QueryPromise implements Promise {\n\tstatic readonly [entityKind]: string = 'QueryPromise';\n\n\t[Symbol.toStringTag] = 'QueryPromise';\n\n\tcatch(\n\t\tonRejected?: ((reason: any) => TResult | PromiseLike) | null | undefined,\n\t): Promise {\n\t\treturn this.then(undefined, onRejected);\n\t}\n\n\tfinally(onFinally?: (() => void) | null | undefined): Promise {\n\t\treturn this.then(\n\t\t\t(value) => {\n\t\t\t\tonFinally?.();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(reason) => {\n\t\t\t\tonFinally?.();\n\t\t\t\tthrow reason;\n\t\t\t},\n\t\t);\n\t}\n\n\tthen(\n\t\tonFulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null,\n\t\tonRejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null,\n\t): Promise {\n\t\treturn this.execute().then(onFulfilled, onRejected);\n\t}\n\n\tabstract execute(): Promise;\n}\n", "import { type AnyTable, getTableUniqueName, type InferModelFromColumns, Table } from '~/table.ts';\nimport { type AnyColumn, Column } from './column.ts';\nimport { entityKind, is } from './entity.ts';\nimport { PrimaryKeyBuilder } from './pg-core/primary-keys.ts';\nimport {\n\tand,\n\tasc,\n\tbetween,\n\tdesc,\n\teq,\n\texists,\n\tgt,\n\tgte,\n\tilike,\n\tinArray,\n\tisNotNull,\n\tisNull,\n\tlike,\n\tlt,\n\tlte,\n\tne,\n\tnot,\n\tnotBetween,\n\tnotExists,\n\tnotIlike,\n\tnotInArray,\n\tnotLike,\n\tor,\n} from './sql/expressions/index.ts';\nimport { type Placeholder, SQL, sql } from './sql/sql.ts';\nimport type { Assume, ColumnsWithTable, Equal, Simplify, ValueOrArray } from './utils.ts';\n\nexport abstract class Relation {\n\tstatic readonly [entityKind]: string = 'Relation';\n\n\tdeclare readonly $brand: 'Relation';\n\treadonly referencedTableName: TTableName;\n\tfieldName!: string;\n\n\tconstructor(\n\t\treadonly sourceTable: Table,\n\t\treadonly referencedTable: AnyTable<{ name: TTableName }>,\n\t\treadonly relationName: string | undefined,\n\t) {\n\t\tthis.referencedTableName = referencedTable[Table.Symbol.Name] as TTableName;\n\t}\n\n\tabstract withFieldName(fieldName: string): Relation;\n}\n\nexport class Relations<\n\tTTableName extends string = string,\n\tTConfig extends Record = Record,\n> {\n\tstatic readonly [entityKind]: string = 'Relations';\n\n\tdeclare readonly $brand: 'Relations';\n\n\tconstructor(\n\t\treadonly table: AnyTable<{ name: TTableName }>,\n\t\treadonly config: (helpers: TableRelationsHelpers) => TConfig,\n\t) {}\n}\n\nexport class One<\n\tTTableName extends string = string,\n\tTIsNullable extends boolean = boolean,\n> extends Relation {\n\tstatic readonly [entityKind]: string = 'One';\n\n\tdeclare protected $relationBrand: 'One';\n\n\tconstructor(\n\t\tsourceTable: Table,\n\t\treferencedTable: AnyTable<{ name: TTableName }>,\n\t\treadonly config:\n\t\t\t| RelationConfig<\n\t\t\t\tTTableName,\n\t\t\t\tstring,\n\t\t\t\tAnyColumn<{ tableName: TTableName }>[]\n\t\t\t>\n\t\t\t| undefined,\n\t\treadonly isNullable: TIsNullable,\n\t) {\n\t\tsuper(sourceTable, referencedTable, config?.relationName);\n\t}\n\n\twithFieldName(fieldName: string): One {\n\t\tconst relation = new One(\n\t\t\tthis.sourceTable,\n\t\t\tthis.referencedTable,\n\t\t\tthis.config,\n\t\t\tthis.isNullable,\n\t\t);\n\t\trelation.fieldName = fieldName;\n\t\treturn relation;\n\t}\n}\n\nexport class Many extends Relation {\n\tstatic readonly [entityKind]: string = 'Many';\n\n\tdeclare protected $relationBrand: 'Many';\n\n\tconstructor(\n\t\tsourceTable: Table,\n\t\treferencedTable: AnyTable<{ name: TTableName }>,\n\t\treadonly config: { relationName: string } | undefined,\n\t) {\n\t\tsuper(sourceTable, referencedTable, config?.relationName);\n\t}\n\n\twithFieldName(fieldName: string): Many {\n\t\tconst relation = new Many(\n\t\t\tthis.sourceTable,\n\t\t\tthis.referencedTable,\n\t\t\tthis.config,\n\t\t);\n\t\trelation.fieldName = fieldName;\n\t\treturn relation;\n\t}\n}\n\nexport type TableRelationsKeysOnly<\n\tTSchema extends Record,\n\tTTableName extends string,\n\tK extends keyof TSchema,\n> = TSchema[K] extends Relations ? K : never;\n\nexport type ExtractTableRelationsFromSchema<\n\tTSchema extends Record,\n\tTTableName extends string,\n> = ExtractObjectValues<\n\t{\n\t\t[\n\t\t\tK in keyof TSchema as TableRelationsKeysOnly<\n\t\t\t\tTSchema,\n\t\t\t\tTTableName,\n\t\t\t\tK\n\t\t\t>\n\t\t]: TSchema[K] extends Relations ? TConfig : never;\n\t}\n>;\n\nexport type ExtractObjectValues = T[keyof T];\n\nexport type ExtractRelationsFromTableExtraConfigSchema<\n\tTConfig extends unknown[],\n> = ExtractObjectValues<\n\t{\n\t\t[\n\t\t\tK in keyof TConfig as TConfig[K] extends Relations ? K\n\t\t\t\t: never\n\t\t]: TConfig[K] extends Relations ? TRelationConfig\n\t\t\t: never;\n\t}\n>;\n\nexport function getOperators() {\n\treturn {\n\t\tand,\n\t\tbetween,\n\t\teq,\n\t\texists,\n\t\tgt,\n\t\tgte,\n\t\tilike,\n\t\tinArray,\n\t\tisNull,\n\t\tisNotNull,\n\t\tlike,\n\t\tlt,\n\t\tlte,\n\t\tne,\n\t\tnot,\n\t\tnotBetween,\n\t\tnotExists,\n\t\tnotLike,\n\t\tnotIlike,\n\t\tnotInArray,\n\t\tor,\n\t\tsql,\n\t};\n}\n\nexport type Operators = ReturnType;\n\nexport function getOrderByOperators() {\n\treturn {\n\t\tsql,\n\t\tasc,\n\t\tdesc,\n\t};\n}\n\nexport type OrderByOperators = ReturnType;\n\nexport type FindTableByDBName<\n\tTSchema extends TablesRelationalConfig,\n\tTTableName extends string,\n> = ExtractObjectValues<\n\t{\n\t\t[\n\t\t\tK in keyof TSchema as TSchema[K]['dbName'] extends TTableName ? K\n\t\t\t\t: never\n\t\t]: TSchema[K];\n\t}\n>;\n\nexport type DBQueryConfig<\n\tTRelationType extends 'one' | 'many' = 'one' | 'many',\n\tTIsRoot extends boolean = boolean,\n\tTSchema extends TablesRelationalConfig = TablesRelationalConfig,\n\tTTableConfig extends TableRelationalConfig = TableRelationalConfig,\n> =\n\t& {\n\t\tcolumns?: {\n\t\t\t[K in keyof TTableConfig['columns']]?: boolean;\n\t\t};\n\t\twith?: {\n\t\t\t[K in keyof TTableConfig['relations']]?:\n\t\t\t\t| true\n\t\t\t\t| DBQueryConfig<\n\t\t\t\t\tTTableConfig['relations'][K] extends One ? 'one' : 'many',\n\t\t\t\t\tfalse,\n\t\t\t\t\tTSchema,\n\t\t\t\t\tFindTableByDBName<\n\t\t\t\t\t\tTSchema,\n\t\t\t\t\t\tTTableConfig['relations'][K]['referencedTableName']\n\t\t\t\t\t>\n\t\t\t\t>;\n\t\t};\n\t\textras?:\n\t\t\t| Record\n\t\t\t| ((\n\t\t\t\tfields: Simplify<\n\t\t\t\t\t[TTableConfig['columns']] extends [never] ? {}\n\t\t\t\t\t\t: TTableConfig['columns']\n\t\t\t\t>,\n\t\t\t\toperators: { sql: Operators['sql'] },\n\t\t\t) => Record);\n\t}\n\t& (TRelationType extends 'many' ?\n\t\t\t& {\n\t\t\t\twhere?:\n\t\t\t\t\t| SQL\n\t\t\t\t\t| undefined\n\t\t\t\t\t| ((\n\t\t\t\t\t\tfields: Simplify<\n\t\t\t\t\t\t\t[TTableConfig['columns']] extends [never] ? {}\n\t\t\t\t\t\t\t\t: TTableConfig['columns']\n\t\t\t\t\t\t>,\n\t\t\t\t\t\toperators: Operators,\n\t\t\t\t\t) => SQL | undefined);\n\t\t\t\torderBy?:\n\t\t\t\t\t| ValueOrArray\n\t\t\t\t\t| ((\n\t\t\t\t\t\tfields: Simplify<\n\t\t\t\t\t\t\t[TTableConfig['columns']] extends [never] ? {}\n\t\t\t\t\t\t\t\t: TTableConfig['columns']\n\t\t\t\t\t\t>,\n\t\t\t\t\t\toperators: OrderByOperators,\n\t\t\t\t\t) => ValueOrArray);\n\t\t\t\tlimit?: number | Placeholder;\n\t\t\t}\n\t\t\t& (TIsRoot extends true ? {\n\t\t\t\t\toffset?: number | Placeholder;\n\t\t\t\t}\n\t\t\t\t: {})\n\t\t: {});\n\nexport interface TableRelationalConfig {\n\ttsName: string;\n\tdbName: string;\n\tcolumns: Record;\n\trelations: Record;\n\tprimaryKey: AnyColumn[];\n\tschema?: string;\n}\n\nexport type TablesRelationalConfig = Record;\n\nexport interface RelationalSchemaConfig<\n\tTSchema extends TablesRelationalConfig,\n> {\n\tfullSchema: Record;\n\tschema: TSchema;\n\ttableNamesMap: Record;\n}\n\nexport type ExtractTablesWithRelations<\n\tTSchema extends Record,\n> = {\n\t[\n\t\tK in keyof TSchema as TSchema[K] extends Table ? K\n\t\t\t: never\n\t]: TSchema[K] extends Table ? {\n\t\t\ttsName: K & string;\n\t\t\tdbName: TSchema[K]['_']['name'];\n\t\t\tcolumns: TSchema[K]['_']['columns'];\n\t\t\trelations: ExtractTableRelationsFromSchema<\n\t\t\t\tTSchema,\n\t\t\t\tTSchema[K]['_']['name']\n\t\t\t>;\n\t\t\tprimaryKey: AnyColumn[];\n\t\t}\n\t\t: never;\n};\n\nexport type ReturnTypeOrValue = T extends (...args: any[]) => infer R ? R\n\t: T;\n\nexport type BuildRelationResult<\n\tTSchema extends TablesRelationalConfig,\n\tTInclude,\n\tTRelations extends Record,\n> = {\n\t[\n\t\tK in\n\t\t\t& NonUndefinedKeysOnly\n\t\t\t& keyof TRelations\n\t]: TRelations[K] extends infer TRel extends Relation ? BuildQueryResult<\n\t\t\tTSchema,\n\t\t\tFindTableByDBName,\n\t\t\tAssume>\n\t\t> extends infer TResult ? TRel extends One ?\n\t\t\t\t\t| TResult\n\t\t\t\t\t| (Equal extends true ? null : never)\n\t\t\t: TResult[]\n\t\t: never\n\t\t: never;\n};\n\nexport type NonUndefinedKeysOnly =\n\t& ExtractObjectValues<\n\t\t{\n\t\t\t[K in keyof T as T[K] extends undefined ? never : K]: K;\n\t\t}\n\t>\n\t& keyof T;\n\nexport type BuildQueryResult<\n\tTSchema extends TablesRelationalConfig,\n\tTTableConfig extends TableRelationalConfig,\n\tTFullSelection extends true | Record,\n> = Equal extends true ? InferModelFromColumns\n\t: TFullSelection extends Record ? Simplify<\n\t\t\t& (TFullSelection['columns'] extends Record ? InferModelFromColumns<\n\t\t\t\t\t{\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\tK in Equal<\n\t\t\t\t\t\t\t\tExclude<\n\t\t\t\t\t\t\t\t\tTFullSelection['columns'][\n\t\t\t\t\t\t\t\t\t\t& keyof TFullSelection['columns']\n\t\t\t\t\t\t\t\t\t\t& keyof TTableConfig['columns']\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tundefined\n\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\tfalse\n\t\t\t\t\t\t\t> extends true ? Exclude<\n\t\t\t\t\t\t\t\t\tkeyof TTableConfig['columns'],\n\t\t\t\t\t\t\t\t\tNonUndefinedKeysOnly\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t:\n\t\t\t\t\t\t\t\t\t& {\n\t\t\t\t\t\t\t\t\t\t[K in keyof TFullSelection['columns']]: Equal<\n\t\t\t\t\t\t\t\t\t\t\tTFullSelection['columns'][K],\n\t\t\t\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t\t\t\t> extends true ? K\n\t\t\t\t\t\t\t\t\t\t\t: never;\n\t\t\t\t\t\t\t\t\t}[keyof TFullSelection['columns']]\n\t\t\t\t\t\t\t\t\t& keyof TTableConfig['columns']\n\t\t\t\t\t\t]: TTableConfig['columns'][K];\n\t\t\t\t\t}\n\t\t\t\t>\n\t\t\t\t: InferModelFromColumns)\n\t\t\t& (TFullSelection['extras'] extends\n\t\t\t\t| Record\n\t\t\t\t| ((...args: any[]) => Record) ? {\n\t\t\t\t\t[\n\t\t\t\t\t\tK in NonUndefinedKeysOnly<\n\t\t\t\t\t\t\tReturnTypeOrValue\n\t\t\t\t\t\t>\n\t\t\t\t\t]: Assume<\n\t\t\t\t\t\tReturnTypeOrValue[K],\n\t\t\t\t\t\tSQL.Aliased\n\t\t\t\t\t>['_']['type'];\n\t\t\t\t}\n\t\t\t\t: {})\n\t\t\t& (TFullSelection['with'] extends Record ? BuildRelationResult<\n\t\t\t\t\tTSchema,\n\t\t\t\t\tTFullSelection['with'],\n\t\t\t\t\tTTableConfig['relations']\n\t\t\t\t>\n\t\t\t\t: {})\n\t\t>\n\t: never;\n\nexport interface RelationConfig<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends AnyColumn<{ tableName: TTableName }>[],\n> {\n\trelationName?: string;\n\tfields: TColumns;\n\treferences: ColumnsWithTable;\n}\n\nexport function extractTablesRelationalConfig<\n\tTTables extends TablesRelationalConfig,\n>(\n\tschema: Record,\n\tconfigHelpers: (table: Table) => any,\n): { tables: TTables; tableNamesMap: Record } {\n\tif (\n\t\tObject.keys(schema).length === 1\n\t\t&& 'default' in schema\n\t\t&& !is(schema['default'], Table)\n\t) {\n\t\tschema = schema['default'] as Record;\n\t}\n\n\t// table DB name -> schema table key\n\tconst tableNamesMap: Record = {};\n\t// Table relations found before their tables - need to buffer them until we know the schema table key\n\tconst relationsBuffer: Record<\n\t\tstring,\n\t\t{ relations: Record; primaryKey?: AnyColumn[] }\n\t> = {};\n\tconst tablesConfig: TablesRelationalConfig = {};\n\tfor (const [key, value] of Object.entries(schema)) {\n\t\tif (is(value, Table)) {\n\t\t\tconst dbName = getTableUniqueName(value);\n\t\t\tconst bufferedRelations = relationsBuffer[dbName];\n\t\t\ttableNamesMap[dbName] = key;\n\t\t\ttablesConfig[key] = {\n\t\t\t\ttsName: key,\n\t\t\t\tdbName: value[Table.Symbol.Name],\n\t\t\t\tschema: value[Table.Symbol.Schema],\n\t\t\t\tcolumns: value[Table.Symbol.Columns],\n\t\t\t\trelations: bufferedRelations?.relations ?? {},\n\t\t\t\tprimaryKey: bufferedRelations?.primaryKey ?? [],\n\t\t\t};\n\n\t\t\t// Fill in primary keys\n\t\t\tfor (\n\t\t\t\tconst column of Object.values(\n\t\t\t\t\t(value as Table)[Table.Symbol.Columns],\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tif (column.primary) {\n\t\t\t\t\ttablesConfig[key]!.primaryKey.push(column);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.((value as Table)[Table.Symbol.ExtraConfigColumns]);\n\t\t\tif (extraConfig) {\n\t\t\t\tfor (const configEntry of Object.values(extraConfig)) {\n\t\t\t\t\tif (is(configEntry, PrimaryKeyBuilder)) {\n\t\t\t\t\t\ttablesConfig[key]!.primaryKey.push(...configEntry.columns);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (is(value, Relations)) {\n\t\t\tconst dbName = getTableUniqueName(value.table);\n\t\t\tconst tableName = tableNamesMap[dbName];\n\t\t\tconst relations: Record = value.config(\n\t\t\t\tconfigHelpers(value.table),\n\t\t\t);\n\t\t\tlet primaryKey: AnyColumn[] | undefined;\n\n\t\t\tfor (const [relationName, relation] of Object.entries(relations)) {\n\t\t\t\tif (tableName) {\n\t\t\t\t\tconst tableConfig = tablesConfig[tableName]!;\n\t\t\t\t\ttableConfig.relations[relationName] = relation;\n\t\t\t\t\tif (primaryKey) {\n\t\t\t\t\t\ttableConfig.primaryKey.push(...primaryKey);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!(dbName in relationsBuffer)) {\n\t\t\t\t\t\trelationsBuffer[dbName] = {\n\t\t\t\t\t\t\trelations: {},\n\t\t\t\t\t\t\tprimaryKey,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\trelationsBuffer[dbName]!.relations[relationName] = relation;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { tables: tablesConfig as TTables, tableNamesMap };\n}\n\nexport function relations<\n\tTTableName extends string,\n\tTRelations extends Record>,\n>(\n\ttable: AnyTable<{ name: TTableName }>,\n\trelations: (helpers: TableRelationsHelpers) => TRelations,\n): Relations {\n\treturn new Relations(\n\t\ttable,\n\t\t(helpers: TableRelationsHelpers) =>\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(relations(helpers)).map(([key, value]) => [\n\t\t\t\t\tkey,\n\t\t\t\t\tvalue.withFieldName(key),\n\t\t\t\t]),\n\t\t\t) as TRelations,\n\t);\n}\n\nexport function createOne(sourceTable: Table) {\n\treturn function one<\n\t\tTForeignTable extends Table,\n\t\tTColumns extends [\n\t\t\tAnyColumn<{ tableName: TTableName }>,\n\t\t\t...AnyColumn<{ tableName: TTableName }>[],\n\t\t],\n\t>(\n\t\ttable: TForeignTable,\n\t\tconfig?: RelationConfig,\n\t): One<\n\t\tTForeignTable['_']['name'],\n\t\tEqual\n\t> {\n\t\treturn new One(\n\t\t\tsourceTable,\n\t\t\ttable,\n\t\t\tconfig,\n\t\t\t(config?.fields.reduce((res, f) => res && f.notNull, true)\n\t\t\t\t?? false) as Equal,\n\t\t);\n\t};\n}\n\nexport function createMany(sourceTable: Table) {\n\treturn function many(\n\t\treferencedTable: TForeignTable,\n\t\tconfig?: { relationName: string },\n\t): Many {\n\t\treturn new Many(sourceTable, referencedTable, config);\n\t};\n}\n\nexport interface NormalizedRelation {\n\tfields: AnyColumn[];\n\treferences: AnyColumn[];\n}\n\nexport function normalizeRelation(\n\tschema: TablesRelationalConfig,\n\ttableNamesMap: Record,\n\trelation: Relation,\n): NormalizedRelation {\n\tif (is(relation, One) && relation.config) {\n\t\treturn {\n\t\t\tfields: relation.config.fields,\n\t\t\treferences: relation.config.references,\n\t\t};\n\t}\n\n\tconst referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];\n\tif (!referencedTableTsName) {\n\t\tthrow new Error(\n\t\t\t`Table \"${relation.referencedTable[Table.Symbol.Name]}\" not found in schema`,\n\t\t);\n\t}\n\n\tconst referencedTableConfig = schema[referencedTableTsName];\n\tif (!referencedTableConfig) {\n\t\tthrow new Error(`Table \"${referencedTableTsName}\" not found in schema`);\n\t}\n\n\tconst sourceTable = relation.sourceTable;\n\tconst sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];\n\tif (!sourceTableTsName) {\n\t\tthrow new Error(\n\t\t\t`Table \"${sourceTable[Table.Symbol.Name]}\" not found in schema`,\n\t\t);\n\t}\n\n\tconst reverseRelations: Relation[] = [];\n\tfor (\n\t\tconst referencedTableRelation of Object.values(\n\t\t\treferencedTableConfig.relations,\n\t\t)\n\t) {\n\t\tif (\n\t\t\t(relation.relationName\n\t\t\t\t&& relation !== referencedTableRelation\n\t\t\t\t&& referencedTableRelation.relationName === relation.relationName)\n\t\t\t|| (!relation.relationName\n\t\t\t\t&& referencedTableRelation.referencedTable === relation.sourceTable)\n\t\t) {\n\t\t\treverseRelations.push(referencedTableRelation);\n\t\t}\n\t}\n\n\tif (reverseRelations.length > 1) {\n\t\tthrow relation.relationName\n\t\t\t? new Error(\n\t\t\t\t`There are multiple relations with name \"${relation.relationName}\" in table \"${referencedTableTsName}\"`,\n\t\t\t)\n\t\t\t: new Error(\n\t\t\t\t`There are multiple relations between \"${referencedTableTsName}\" and \"${\n\t\t\t\t\trelation.sourceTable[Table.Symbol.Name]\n\t\t\t\t}\". Please specify relation name`,\n\t\t\t);\n\t}\n\n\tif (\n\t\treverseRelations[0]\n\t\t&& is(reverseRelations[0], One)\n\t\t&& reverseRelations[0].config\n\t) {\n\t\treturn {\n\t\t\tfields: reverseRelations[0].config.references,\n\t\t\treferences: reverseRelations[0].config.fields,\n\t\t};\n\t}\n\n\tthrow new Error(\n\t\t`There is not enough information to infer relation \"${sourceTableTsName}.${relation.fieldName}\"`,\n\t);\n}\n\nexport function createTableRelationsHelpers(\n\tsourceTable: AnyTable<{ name: TTableName }>,\n) {\n\treturn {\n\t\tone: createOne(sourceTable),\n\t\tmany: createMany(sourceTable),\n\t};\n}\n\nexport type TableRelationsHelpers = ReturnType<\n\ttypeof createTableRelationsHelpers\n>;\n\nexport interface BuildRelationalQueryResult<\n\tTTable extends Table = Table,\n\tTColumn extends Column = Column,\n> {\n\ttableTsKey: string;\n\tselection: {\n\t\tdbKey: string;\n\t\ttsKey: string;\n\t\tfield: TColumn | SQL | SQL.Aliased;\n\t\trelationTableTsKey: string | undefined;\n\t\tisJson: boolean;\n\t\tisExtra?: boolean;\n\t\tselection: BuildRelationalQueryResult['selection'];\n\t}[];\n\tsql: TTable | SQL;\n}\n\nexport function mapRelationalRow(\n\ttablesConfig: TablesRelationalConfig,\n\ttableConfig: TableRelationalConfig,\n\trow: unknown[],\n\tbuildQueryResultSelection: BuildRelationalQueryResult['selection'],\n\tmapColumnValue: (value: unknown) => unknown = (value) => value,\n): Record {\n\tconst result: Record = {};\n\n\tfor (\n\t\tconst [\n\t\t\tselectionItemIndex,\n\t\t\tselectionItem,\n\t\t] of buildQueryResultSelection.entries()\n\t) {\n\t\tif (selectionItem.isJson) {\n\t\t\tconst relation = tableConfig.relations[selectionItem.tsKey]!;\n\t\t\tconst rawSubRows = row[selectionItemIndex] as\n\t\t\t\t| unknown[]\n\t\t\t\t| null\n\t\t\t\t| [null]\n\t\t\t\t| string;\n\t\t\tconst subRows = typeof rawSubRows === 'string'\n\t\t\t\t? (JSON.parse(rawSubRows) as unknown[])\n\t\t\t\t: rawSubRows;\n\t\t\tresult[selectionItem.tsKey] = is(relation, One)\n\t\t\t\t? subRows\n\t\t\t\t\t&& mapRelationalRow(\n\t\t\t\t\t\ttablesConfig,\n\t\t\t\t\t\ttablesConfig[selectionItem.relationTableTsKey!]!,\n\t\t\t\t\t\tsubRows,\n\t\t\t\t\t\tselectionItem.selection,\n\t\t\t\t\t\tmapColumnValue,\n\t\t\t\t\t)\n\t\t\t\t: (subRows as unknown[][]).map((subRow) =>\n\t\t\t\t\tmapRelationalRow(\n\t\t\t\t\t\ttablesConfig,\n\t\t\t\t\t\ttablesConfig[selectionItem.relationTableTsKey!]!,\n\t\t\t\t\t\tsubRow,\n\t\t\t\t\t\tselectionItem.selection,\n\t\t\t\t\t\tmapColumnValue,\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t} else {\n\t\t\tconst value = mapColumnValue(row[selectionItemIndex]);\n\t\t\tconst field = selectionItem.field!;\n\t\t\tlet decoder;\n\t\t\tif (is(field, Column)) {\n\t\t\t\tdecoder = field;\n\t\t\t} else if (is(field, SQL)) {\n\t\t\t\tdecoder = field.decoder;\n\t\t\t} else {\n\t\t\t\tdecoder = field.sql.decoder;\n\t\t\t}\n\t\t\tresult[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);\n\t\t}\n\t}\n\n\treturn result;\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { AnyPgColumn, PgColumn } from './columns/index.ts';\nimport { PgTable } from './table.ts';\n\nexport function primaryKey<\n\tTTableName extends string,\n\tTColumn extends AnyPgColumn<{ tableName: TTableName }>,\n\tTColumns extends AnyPgColumn<{ tableName: TTableName }>[],\n>(config: { name?: string; columns: [TColumn, ...TColumns] }): PrimaryKeyBuilder;\n/**\n * @deprecated: Please use primaryKey({ columns: [] }) instead of this function\n * @param columns\n */\nexport function primaryKey<\n\tTTableName extends string,\n\tTColumns extends AnyPgColumn<{ tableName: TTableName }>[],\n>(...columns: TColumns): PrimaryKeyBuilder;\nexport function primaryKey(...config: any) {\n\tif (config[0].columns) {\n\t\treturn new PrimaryKeyBuilder(config[0].columns, config[0].name);\n\t}\n\treturn new PrimaryKeyBuilder(config);\n}\n\nexport class PrimaryKeyBuilder {\n\tstatic readonly [entityKind]: string = 'PgPrimaryKeyBuilder';\n\n\t/** @internal */\n\tcolumns: PgColumn[];\n\n\t/** @internal */\n\tname?: string;\n\n\tconstructor(\n\t\tcolumns: PgColumn[],\n\t\tname?: string,\n\t) {\n\t\tthis.columns = columns;\n\t\tthis.name = name;\n\t}\n\n\t/** @internal */\n\tbuild(table: PgTable): PrimaryKey {\n\t\treturn new PrimaryKey(table, this.columns, this.name);\n\t}\n}\n\nexport class PrimaryKey {\n\tstatic readonly [entityKind]: string = 'PgPrimaryKey';\n\n\treadonly columns: AnyPgColumn<{}>[];\n\treadonly name?: string;\n\n\tconstructor(readonly table: PgTable, columns: AnyPgColumn<{}>[], name?: string) {\n\t\tthis.columns = columns;\n\t\tthis.name = name;\n\t}\n\n\tgetName(): string {\n\t\treturn this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join('_')}_pk`;\n\t}\n}\n", "import type { AnyColumn } from './column.ts';\nimport { Column } from './column.ts';\nimport { is } from './entity.ts';\nimport type { Logger } from './logger.ts';\nimport type { SelectedFieldsOrdered } from './operations.ts';\nimport type { TableLike } from './query-builders/select.types.ts';\nimport { Param, SQL, View } from './sql/sql.ts';\nimport type { DriverValueDecoder } from './sql/sql.ts';\nimport { Subquery } from './subquery.ts';\nimport { getTableName, Table } from './table.ts';\nimport { ViewBaseConfig } from './view-common.ts';\n\n/** @internal */\nexport function mapResultRow(\n\tcolumns: SelectedFieldsOrdered,\n\trow: unknown[],\n\tjoinsNotNullableMap: Record | undefined,\n): TResult {\n\t// Key -> nested object key, value -> table name if all fields in the nested object are from the same table, false otherwise\n\tconst nullifyMap: Record = {};\n\n\tconst result = columns.reduce>(\n\t\t(result, { path, field }, columnIndex) => {\n\t\t\tlet decoder: DriverValueDecoder;\n\t\t\tif (is(field, Column)) {\n\t\t\t\tdecoder = field;\n\t\t\t} else if (is(field, SQL)) {\n\t\t\t\tdecoder = field.decoder;\n\t\t\t} else {\n\t\t\t\tdecoder = field.sql.decoder;\n\t\t\t}\n\t\t\tlet node = result;\n\t\t\tfor (const [pathChunkIndex, pathChunk] of path.entries()) {\n\t\t\t\tif (pathChunkIndex < path.length - 1) {\n\t\t\t\t\tif (!(pathChunk in node)) {\n\t\t\t\t\t\tnode[pathChunk] = {};\n\t\t\t\t\t}\n\t\t\t\t\tnode = node[pathChunk];\n\t\t\t\t} else {\n\t\t\t\t\tconst rawValue = row[columnIndex]!;\n\t\t\t\t\tconst value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);\n\n\t\t\t\t\tif (joinsNotNullableMap && is(field, Column) && path.length === 2) {\n\t\t\t\t\t\tconst objectName = path[0]!;\n\t\t\t\t\t\tif (!(objectName in nullifyMap)) {\n\t\t\t\t\t\t\tnullifyMap[objectName] = value === null ? getTableName(field.table) : false;\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\ttypeof nullifyMap[objectName] === 'string' && nullifyMap[objectName] !== getTableName(field.table)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tnullifyMap[objectName] = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t\t{},\n\t);\n\n\t// Nullify all nested objects from nullifyMap that are nullable\n\tif (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {\n\t\tfor (const [objectName, tableName] of Object.entries(nullifyMap)) {\n\t\t\tif (typeof tableName === 'string' && !joinsNotNullableMap[tableName]) {\n\t\t\t\tresult[objectName] = null;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result as TResult;\n}\n\n/** @internal */\nexport function orderSelectedFields(\n\tfields: Record,\n\tpathPrefix?: string[],\n): SelectedFieldsOrdered {\n\treturn Object.entries(fields).reduce>((result, [name, field]) => {\n\t\tif (typeof name !== 'string') {\n\t\t\treturn result;\n\t\t}\n\n\t\tconst newPath = pathPrefix ? [...pathPrefix, name] : [name];\n\t\tif (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {\n\t\t\tresult.push({ path: newPath, field });\n\t\t} else if (is(field, Table)) {\n\t\t\tresult.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));\n\t\t} else {\n\t\t\tresult.push(...orderSelectedFields(field as Record, newPath));\n\t\t}\n\t\treturn result;\n\t}, []) as SelectedFieldsOrdered;\n}\n\nexport function haveSameKeys(left: Record, right: Record) {\n\tconst leftKeys = Object.keys(left);\n\tconst rightKeys = Object.keys(right);\n\n\tif (leftKeys.length !== rightKeys.length) {\n\t\treturn false;\n\t}\n\n\tfor (const [index, key] of leftKeys.entries()) {\n\t\tif (key !== rightKeys[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n/** @internal */\nexport function mapUpdateSet(table: Table, values: Record): UpdateSet {\n\tconst entries: [string, UpdateSet[string]][] = Object.entries(values)\n\t\t.filter(([, value]) => value !== undefined)\n\t\t.map(([key, value]) => {\n\t\t\t// eslint-disable-next-line unicorn/prefer-ternary\n\t\t\tif (is(value, SQL)) {\n\t\t\t\treturn [key, value];\n\t\t\t} else {\n\t\t\t\treturn [key, new Param(value, table[Table.Symbol.Columns][key])];\n\t\t\t}\n\t\t});\n\n\tif (entries.length === 0) {\n\t\tthrow new Error('No values to set');\n\t}\n\n\treturn Object.fromEntries(entries);\n}\n\nexport type UpdateSet = Record;\n\nexport type OneOrMany = T | T[];\n\nexport type Update =\n\t& {\n\t\t[K in Exclude]: T[K];\n\t}\n\t& TUpdate;\n\nexport type Simplify =\n\t& {\n\t\t// @ts-ignore - \"Type parameter 'K' has a circular constraint\", not sure why\n\t\t[K in keyof T]: T[K];\n\t}\n\t& {};\n\nexport type SimplifyMappedType = [T] extends [unknown] ? T : never;\n\nexport type ShallowRecord = SimplifyMappedType<{ [P in K]: T }>;\n\nexport type Assume = T extends U ? T : U;\n\nexport type Equal = (() => T extends X ? 1 : 2) extends (() => T extends Y ? 1 : 2) ? true : false;\n\nexport interface DrizzleTypeError {\n\t$drizzleTypeError: T;\n}\n\nexport type ValueOrArray = T | T[];\n\n/** @internal */\nexport function applyMixins(baseClass: any, extendedClasses: any[]) {\n\tfor (const extendedClass of extendedClasses) {\n\t\tfor (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {\n\t\t\tif (name === 'constructor') continue;\n\n\t\t\tObject.defineProperty(\n\t\t\t\tbaseClass.prototype,\n\t\t\t\tname,\n\t\t\t\tObject.getOwnPropertyDescriptor(extendedClass.prototype, name) || Object.create(null),\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport type Or = T1 extends true ? true : T2 extends true ? true : false;\n\nexport type IfThenElse = If extends true ? Then : Else;\n\nexport type PromiseOf = T extends Promise ? U : T;\n\nexport type Writable = {\n\t-readonly [P in keyof T]: T[P];\n};\n\nexport function getTableColumns(table: T): T['_']['columns'] {\n\treturn table[Table.Symbol.Columns];\n}\n\n/** @internal */\nexport function getTableLikeName(table: TableLike): string | undefined {\n\treturn is(table, Subquery)\n\t\t? table._.alias\n\t\t: is(table, View)\n\t\t? table[ViewBaseConfig].name\n\t\t: is(table, SQL)\n\t\t? undefined\n\t\t: table[Table.Symbol.IsAlias]\n\t\t? table[Table.Symbol.Name]\n\t\t: table[Table.Symbol.BaseName];\n}\n\nexport type ColumnsWithTable<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends AnyColumn<{ tableName: TTableName }>[],\n> = { [Key in keyof TColumns]: AnyColumn<{ tableName: TForeignTableName }> };\n\nexport interface DrizzleConfig = Record> {\n\tlogger?: boolean | Logger;\n\tschema?: TSchema;\n}\nexport type ValidateShape = T extends ValidShape\n\t? Exclude extends never ? TResult\n\t: DrizzleTypeError<\n\t\t`Invalid key(s): ${Exclude<(keyof T) & (string | number | bigint | boolean | null | undefined), keyof ValidShape>}`\n\t>\n\t: never;\n\nexport type KnownKeysOnly = {\n\t[K in keyof T]: K extends keyof U ? T[K] : never;\n};\n\nexport type IsAny = 0 extends (1 & T) ? true : false;\n", "import type {\n\tColumnBuilderBaseConfig,\n\tColumnDataType,\n\tGeneratedIdentityConfig,\n\tIsIdentityByDefault,\n} from '~/column-builder.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { PgSequenceOptions } from '../sequence.ts';\nimport { PgColumnBuilder } from './common.ts';\n\nexport abstract class PgIntColumnBaseBuilder<\n\tT extends ColumnBuilderBaseConfig,\n> extends PgColumnBuilder<\n\tT,\n\t{ generatedIdentity: GeneratedIdentityConfig }\n> {\n\tstatic readonly [entityKind]: string = 'PgIntColumnBaseBuilder';\n\n\tgeneratedAlwaysAsIdentity(\n\t\tsequence?: PgSequenceOptions & { name?: string },\n\t): IsIdentityByDefault {\n\t\tif (sequence) {\n\t\t\tconst { name, ...options } = sequence;\n\t\t\tthis.config.generatedIdentity = {\n\t\t\t\ttype: 'always',\n\t\t\t\tsequenceName: name,\n\t\t\t\tsequenceOptions: options,\n\t\t\t};\n\t\t} else {\n\t\t\tthis.config.generatedIdentity = {\n\t\t\t\ttype: 'always',\n\t\t\t};\n\t\t}\n\n\t\tthis.config.hasDefault = true;\n\t\tthis.config.notNull = true;\n\n\t\treturn this as any;\n\t}\n\n\tgeneratedByDefaultAsIdentity(\n\t\tsequence?: PgSequenceOptions & { name?: string },\n\t): IsIdentityByDefault {\n\t\tif (sequence) {\n\t\t\tconst { name, ...options } = sequence;\n\t\t\tthis.config.generatedIdentity = {\n\t\t\t\ttype: 'byDefault',\n\t\t\t\tsequenceName: name,\n\t\t\t\tsequenceOptions: options,\n\t\t\t};\n\t\t} else {\n\t\t\tthis.config.generatedIdentity = {\n\t\t\t\ttype: 'byDefault',\n\t\t\t};\n\t\t}\n\n\t\tthis.config.hasDefault = true;\n\t\tthis.config.notNull = true;\n\n\t\treturn this as any;\n\t}\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport { PgColumn } from './common.ts';\nimport { PgDateColumnBaseBuilder } from './date.common.ts';\n\nexport type PgDateBuilderInitial = PgDateBuilder<{\n\tname: TName;\n\tdataType: 'date';\n\tcolumnType: 'PgDate';\n\tdata: Date;\n\tdriverParam: string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgDateBuilder> extends PgDateColumnBaseBuilder {\n\tstatic readonly [entityKind]: string = 'PgDateBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'date', 'PgDate');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgDate> {\n\t\treturn new PgDate>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgDate> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgDate';\n\n\tgetSQLType(): string {\n\t\treturn 'date';\n\t}\n\n\toverride mapFromDriverValue(value: string): Date {\n\t\treturn new Date(value);\n\t}\n\n\toverride mapToDriverValue(value: Date): string {\n\t\treturn value.toISOString();\n\t}\n}\n\nexport type PgDateStringBuilderInitial = PgDateStringBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'PgDateString';\n\tdata: string;\n\tdriverParam: string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgDateStringBuilder>\n\textends PgDateColumnBaseBuilder\n{\n\tstatic readonly [entityKind]: string = 'PgDateStringBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'string', 'PgDateString');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgDateString> {\n\t\treturn new PgDateString>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class PgDateString> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgDateString';\n\n\tgetSQLType(): string {\n\t\treturn 'date';\n\t}\n}\n\nexport function date(\n\tname: TName,\n\tconfig?: { mode: 'string' },\n): PgDateStringBuilderInitial;\nexport function date(TName: TName, config?: { mode: 'date' }): PgDateBuilderInitial;\nexport function date(name: TName, config?: { mode: 'date' | 'string' }) {\n\tif (config?.mode === 'date') {\n\t\treturn new PgDateBuilder(name);\n\t}\n\treturn new PgDateStringBuilder(name);\n}\n", "import type { ColumnBuilderBaseConfig, ColumnDataType } from '~/column-builder.ts';\nimport { entityKind } from '~/entity.ts';\nimport { sql } from '~/sql/sql.ts';\nimport { PgColumnBuilder } from './common.ts';\n\nexport abstract class PgDateColumnBaseBuilder<\n\tT extends ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n> extends PgColumnBuilder {\n\tstatic readonly [entityKind]: string = 'PgDateColumnBaseBuilder';\n\n\tdefaultNow() {\n\t\treturn this.default(sql`now()`);\n\t}\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '../table.ts';\nimport { PgColumn } from './common.ts';\nimport { PgIntColumnBaseBuilder } from './int.common.ts';\n\ntype PgIntegerBuilderInitial = PgIntegerBuilder<{\n\tname: TName;\n\tdataType: 'number';\n\tcolumnType: 'PgInteger';\n\tdata: number;\n\tdriverParam: number | string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgIntegerBuilder>\n\textends PgIntColumnBaseBuilder\n{\n\tstatic readonly [entityKind]: string = 'PgIntegerBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'number', 'PgInteger');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgInteger> {\n\t\treturn new PgInteger>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgInteger> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgInteger';\n\n\tgetSQLType(): string {\n\t\treturn 'integer';\n\t}\n\n\toverride mapFromDriverValue(value: number | string): number {\n\t\tif (typeof value === 'string') {\n\t\t\treturn Number.parseInt(value);\n\t\t}\n\t\treturn value;\n\t}\n}\n\nexport function integer(name: TName): PgIntegerBuilderInitial {\n\treturn new PgIntegerBuilder(name);\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport { PgColumn, PgColumnBuilder } from './common.ts';\n\nexport type PgJsonBuilderInitial = PgJsonBuilder<{\n\tname: TName;\n\tdataType: 'json';\n\tcolumnType: 'PgJson';\n\tdata: unknown;\n\tdriverParam: unknown;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgJsonBuilder> extends PgColumnBuilder<\n\tT\n> {\n\tstatic readonly [entityKind]: string = 'PgJsonBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'json', 'PgJson');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgJson> {\n\t\treturn new PgJson>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgJson> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgJson';\n\n\tconstructor(table: AnyPgTable<{ name: T['tableName'] }>, config: PgJsonBuilder['config']) {\n\t\tsuper(table, config);\n\t}\n\n\tgetSQLType(): string {\n\t\treturn 'json';\n\t}\n\n\toverride mapToDriverValue(value: T['data']): string {\n\t\treturn JSON.stringify(value);\n\t}\n\n\toverride mapFromDriverValue(value: T['data'] | string): T['data'] {\n\t\tif (typeof value === 'string') {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(value);\n\t\t\t} catch {\n\t\t\t\treturn value as T['data'];\n\t\t\t}\n\t\t}\n\t\treturn value;\n\t}\n}\n\nexport function json(name: TName): PgJsonBuilderInitial {\n\treturn new PgJsonBuilder(name);\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport { PgColumn, PgColumnBuilder } from './common.ts';\n\nexport type PgJsonbBuilderInitial = PgJsonbBuilder<{\n\tname: TName;\n\tdataType: 'json';\n\tcolumnType: 'PgJsonb';\n\tdata: unknown;\n\tdriverParam: unknown;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgJsonbBuilder> extends PgColumnBuilder {\n\tstatic readonly [entityKind]: string = 'PgJsonbBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'json', 'PgJsonb');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgJsonb> {\n\t\treturn new PgJsonb>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgJsonb> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgJsonb';\n\n\tconstructor(table: AnyPgTable<{ name: T['tableName'] }>, config: PgJsonbBuilder['config']) {\n\t\tsuper(table, config);\n\t}\n\n\tgetSQLType(): string {\n\t\treturn 'jsonb';\n\t}\n\n\toverride mapToDriverValue(value: T['data']): string {\n\t\treturn JSON.stringify(value);\n\t}\n\n\toverride mapFromDriverValue(value: T['data'] | string): T['data'] {\n\t\tif (typeof value === 'string') {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(value);\n\t\t\t} catch {\n\t\t\t\treturn value as T['data'];\n\t\t\t}\n\t\t}\n\t\treturn value;\n\t}\n}\n\nexport function jsonb(name: TName): PgJsonbBuilderInitial {\n\treturn new PgJsonbBuilder(name);\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport { PgColumn, PgColumnBuilder } from './common.ts';\n\nexport type PgNumericBuilderInitial = PgNumericBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'PgNumeric';\n\tdata: string;\n\tdriverParam: string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgNumericBuilder> extends PgColumnBuilder<\n\tT,\n\t{\n\t\tprecision: number | undefined;\n\t\tscale: number | undefined;\n\t}\n> {\n\tstatic readonly [entityKind]: string = 'PgNumericBuilder';\n\n\tconstructor(name: string, precision?: number, scale?: number) {\n\t\tsuper(name, 'string', 'PgNumeric');\n\t\tthis.config.precision = precision;\n\t\tthis.config.scale = scale;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgNumeric> {\n\t\treturn new PgNumeric>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgNumeric> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgNumeric';\n\n\treadonly precision: number | undefined;\n\treadonly scale: number | undefined;\n\n\tconstructor(table: AnyPgTable<{ name: T['tableName'] }>, config: PgNumericBuilder['config']) {\n\t\tsuper(table, config);\n\t\tthis.precision = config.precision;\n\t\tthis.scale = config.scale;\n\t}\n\n\tgetSQLType(): string {\n\t\tif (this.precision !== undefined && this.scale !== undefined) {\n\t\t\treturn `numeric(${this.precision}, ${this.scale})`;\n\t\t} else if (this.precision === undefined) {\n\t\t\treturn 'numeric';\n\t\t} else {\n\t\t\treturn `numeric(${this.precision})`;\n\t\t}\n\t}\n}\n\nexport function numeric(\n\tname: TName,\n\tconfig?:\n\t\t| { precision: number; scale?: number }\n\t\t| { precision?: number; scale: number }\n\t\t| { precision: number; scale: number },\n): PgNumericBuilderInitial {\n\treturn new PgNumericBuilder(name, config?.precision, config?.scale);\n}\n\nexport const decimal = numeric;\n", "import type {\n\tColumnBuilderBaseConfig,\n\tColumnBuilderRuntimeConfig,\n\tHasDefault,\n\tMakeColumnConfig,\n\tNotNull,\n} from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport { PgColumn, PgColumnBuilder } from './common.ts';\n\nexport type PgSerialBuilderInitial = NotNull<\n\tHasDefault<\n\t\tPgSerialBuilder<{\n\t\t\tname: TName;\n\t\t\tdataType: 'number';\n\t\t\tcolumnType: 'PgSerial';\n\t\t\tdata: number;\n\t\t\tdriverParam: number;\n\t\t\tenumValues: undefined;\n\t\t\tgenerated: undefined;\n\t\t}>\n\t>\n>;\n\nexport class PgSerialBuilder> extends PgColumnBuilder {\n\tstatic readonly [entityKind]: string = 'PgSerialBuilder';\n\n\tconstructor(name: string) {\n\t\tsuper(name, 'number', 'PgSerial');\n\t\tthis.config.hasDefault = true;\n\t\tthis.config.notNull = true;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgSerial> {\n\t\treturn new PgSerial>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgSerial> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgSerial';\n\n\tgetSQLType(): string {\n\t\treturn 'serial';\n\t}\n}\n\nexport function serial(name: TName): PgSerialBuilderInitial {\n\treturn new PgSerialBuilder(name) as PgSerialBuilderInitial;\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport type { Writable } from '~/utils.ts';\nimport { PgColumn, PgColumnBuilder } from './common.ts';\n\ntype PgTextBuilderInitial = PgTextBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'PgText';\n\tdata: TEnum[number];\n\tenumValues: TEnum;\n\tdriverParam: string;\n\tgenerated: undefined;\n}>;\n\nexport class PgTextBuilder<\n\tT extends ColumnBuilderBaseConfig<'string', 'PgText'>,\n> extends PgColumnBuilder {\n\tstatic readonly [entityKind]: string = 'PgTextBuilder';\n\n\tconstructor(\n\t\tname: T['name'],\n\t\tconfig: PgTextConfig,\n\t) {\n\t\tsuper(name, 'string', 'PgText');\n\t\tthis.config.enumValues = config.enum;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgText> {\n\t\treturn new PgText>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgText>\n\textends PgColumn\n{\n\tstatic readonly [entityKind]: string = 'PgText';\n\n\toverride readonly enumValues = this.config.enumValues;\n\n\tgetSQLType(): string {\n\t\treturn 'text';\n\t}\n}\n\nexport interface PgTextConfig {\n\tenum?: TEnum;\n}\n\nexport function text>(\n\tname: TName,\n\tconfig: PgTextConfig> = {},\n): PgTextBuilderInitial> {\n\treturn new PgTextBuilder(name, config);\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport { PgColumn } from './common.ts';\nimport { PgDateColumnBaseBuilder } from './date.common.ts';\nimport type { Precision } from './timestamp.ts';\n\nexport type PgTimeBuilderInitial = PgTimeBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'PgTime';\n\tdata: string;\n\tdriverParam: string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgTimeBuilder> extends PgDateColumnBaseBuilder<\n\tT,\n\t{ withTimezone: boolean; precision: number | undefined }\n> {\n\tstatic readonly [entityKind]: string = 'PgTimeBuilder';\n\n\tconstructor(\n\t\tname: T['name'],\n\t\treadonly withTimezone: boolean,\n\t\treadonly precision: number | undefined,\n\t) {\n\t\tsuper(name, 'string', 'PgTime');\n\t\tthis.config.withTimezone = withTimezone;\n\t\tthis.config.precision = precision;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgTime> {\n\t\treturn new PgTime>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgTime> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgTime';\n\n\treadonly withTimezone: boolean;\n\treadonly precision: number | undefined;\n\n\tconstructor(table: AnyPgTable<{ name: T['tableName'] }>, config: PgTimeBuilder['config']) {\n\t\tsuper(table, config);\n\t\tthis.withTimezone = config.withTimezone;\n\t\tthis.precision = config.precision;\n\t}\n\n\tgetSQLType(): string {\n\t\tconst precision = this.precision === undefined ? '' : `(${this.precision})`;\n\t\treturn `time${precision}${this.withTimezone ? ' with time zone' : ''}`;\n\t}\n}\n\nexport interface TimeConfig {\n\tprecision?: Precision;\n\twithTimezone?: boolean;\n}\n\nexport function time(name: TName, config: TimeConfig = {}): PgTimeBuilderInitial {\n\treturn new PgTimeBuilder(name, config.withTimezone ?? false, config.precision);\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport type { Equal } from '~/utils.ts';\nimport { PgColumn } from './common.ts';\nimport { PgDateColumnBaseBuilder } from './date.common.ts';\n\nexport type PgTimestampBuilderInitial = PgTimestampBuilder<{\n\tname: TName;\n\tdataType: 'date';\n\tcolumnType: 'PgTimestamp';\n\tdata: Date;\n\tdriverParam: string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgTimestampBuilder>\n\textends PgDateColumnBaseBuilder<\n\t\tT,\n\t\t{ withTimezone: boolean; precision: number | undefined }\n\t>\n{\n\tstatic readonly [entityKind]: string = 'PgTimestampBuilder';\n\n\tconstructor(\n\t\tname: string,\n\t\twithTimezone: boolean,\n\t\tprecision: number | undefined,\n\t) {\n\t\tsuper(name, 'date', 'PgTimestamp');\n\t\tthis.config.withTimezone = withTimezone;\n\t\tthis.config.precision = precision;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgTimestamp> {\n\t\treturn new PgTimestamp>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgTimestamp> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgTimestamp';\n\n\treadonly withTimezone: boolean;\n\treadonly precision: number | undefined;\n\n\tconstructor(table: AnyPgTable<{ name: T['tableName'] }>, config: PgTimestampBuilder['config']) {\n\t\tsuper(table, config);\n\t\tthis.withTimezone = config.withTimezone;\n\t\tthis.precision = config.precision;\n\t}\n\n\tgetSQLType(): string {\n\t\tconst precision = this.precision === undefined ? '' : ` (${this.precision})`;\n\t\treturn `timestamp${precision}${this.withTimezone ? ' with time zone' : ''}`;\n\t}\n\n\toverride mapFromDriverValue = (value: string): Date | null => {\n\t\treturn new Date(this.withTimezone ? value : value + '+0000');\n\t};\n\n\toverride mapToDriverValue = (value: Date): string => {\n\t\treturn value.toISOString();\n\t};\n}\n\nexport type PgTimestampStringBuilderInitial = PgTimestampStringBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'PgTimestampString';\n\tdata: string;\n\tdriverParam: string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgTimestampStringBuilder>\n\textends PgDateColumnBaseBuilder<\n\t\tT,\n\t\t{ withTimezone: boolean; precision: number | undefined }\n\t>\n{\n\tstatic readonly [entityKind]: string = 'PgTimestampStringBuilder';\n\n\tconstructor(\n\t\tname: string,\n\t\twithTimezone: boolean,\n\t\tprecision: number | undefined,\n\t) {\n\t\tsuper(name, 'string', 'PgTimestampString');\n\t\tthis.config.withTimezone = withTimezone;\n\t\tthis.config.precision = precision;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgTimestampString> {\n\t\treturn new PgTimestampString>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class PgTimestampString> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgTimestampString';\n\n\treadonly withTimezone: boolean;\n\treadonly precision: number | undefined;\n\n\tconstructor(table: AnyPgTable<{ name: T['tableName'] }>, config: PgTimestampStringBuilder['config']) {\n\t\tsuper(table, config);\n\t\tthis.withTimezone = config.withTimezone;\n\t\tthis.precision = config.precision;\n\t}\n\n\tgetSQLType(): string {\n\t\tconst precision = this.precision === undefined ? '' : `(${this.precision})`;\n\t\treturn `timestamp${precision}${this.withTimezone ? ' with time zone' : ''}`;\n\t}\n}\n\nexport type Precision = 0 | 1 | 2 | 3 | 4 | 5 | 6;\n\nexport interface PgTimestampConfig {\n\tmode?: TMode;\n\tprecision?: Precision;\n\twithTimezone?: boolean;\n}\n\nexport function timestamp(\n\tname: TName,\n\tconfig?: PgTimestampConfig,\n): Equal extends true ? PgTimestampStringBuilderInitial : PgTimestampBuilderInitial;\nexport function timestamp(\n\tname: string,\n\tconfig: PgTimestampConfig = {},\n) {\n\tif (config.mode === 'string') {\n\t\treturn new PgTimestampStringBuilder(name, config.withTimezone ?? false, config.precision);\n\t}\n\treturn new PgTimestampBuilder(name, config.withTimezone ?? false, config.precision);\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport { sql } from '~/sql/sql.ts';\nimport { PgColumn, PgColumnBuilder } from './common.ts';\n\nexport type PgUUIDBuilderInitial = PgUUIDBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'PgUUID';\n\tdata: string;\n\tdriverParam: string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class PgUUIDBuilder> extends PgColumnBuilder {\n\tstatic readonly [entityKind]: string = 'PgUUIDBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'string', 'PgUUID');\n\t}\n\n\t/**\n\t * Adds `default gen_random_uuid()` to the column definition.\n\t */\n\tdefaultRandom(): ReturnType {\n\t\treturn this.default(sql`gen_random_uuid()`) as ReturnType;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgUUID> {\n\t\treturn new PgUUID>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class PgUUID> extends PgColumn {\n\tstatic readonly [entityKind]: string = 'PgUUID';\n\n\tgetSQLType(): string {\n\t\treturn 'uuid';\n\t}\n}\n\nexport function uuid(name: TName): PgUUIDBuilderInitial {\n\treturn new PgUUIDBuilder(name);\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { PgDialect } from '~/pg-core/dialect.ts';\nimport {\n\tPgDeleteBase,\n\tPgInsertBuilder,\n\tPgSelectBuilder,\n\tPgUpdateBuilder,\n\tQueryBuilder,\n} from '~/pg-core/query-builders/index.ts';\nimport type {\n\tPgQueryResultHKT,\n\tPgQueryResultKind,\n\tPgSession,\n\tPgTransaction,\n\tPgTransactionConfig,\n\tPreparedQueryConfig,\n} from '~/pg-core/session.ts';\nimport type { PgTable } from '~/pg-core/table.ts';\nimport type { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport type { ExtractTablesWithRelations, RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport type { ColumnsSelection, SQLWrapper } from '~/sql/sql.ts';\nimport { WithSubquery } from '~/subquery.ts';\nimport type { DrizzleTypeError } from '~/utils.ts';\nimport type { PgColumn } from './columns/index.ts';\nimport { RelationalQueryBuilder } from './query-builders/query.ts';\nimport { PgRaw } from './query-builders/raw.ts';\nimport { PgRefreshMaterializedView } from './query-builders/refresh-materialized-view.ts';\nimport type { SelectedFields } from './query-builders/select.types.ts';\nimport type { WithSubqueryWithSelection } from './subquery.ts';\nimport type { PgMaterializedView } from './view.ts';\n\nexport class PgDatabase<\n\tTQueryResult extends PgQueryResultHKT,\n\tTFullSchema extends Record = Record,\n\tTSchema extends TablesRelationalConfig = ExtractTablesWithRelations,\n> {\n\tstatic readonly [entityKind]: string = 'PgDatabase';\n\n\tdeclare readonly _: {\n\t\treadonly schema: TSchema | undefined;\n\t\treadonly fullSchema: TFullSchema;\n\t\treadonly tableNamesMap: Record;\n\t\treadonly session: PgSession;\n\t};\n\n\tquery: TFullSchema extends Record\n\t\t? DrizzleTypeError<'Seems like the schema generic is missing - did you forget to add it to your DB type?'>\n\t\t: {\n\t\t\t[K in keyof TSchema]: RelationalQueryBuilder;\n\t\t};\n\n\tconstructor(\n\t\t/** @internal */\n\t\treadonly dialect: PgDialect,\n\t\t/** @internal */\n\t\treadonly session: PgSession,\n\t\tschema: RelationalSchemaConfig | undefined,\n\t) {\n\t\tthis._ = schema\n\t\t\t? {\n\t\t\t\tschema: schema.schema,\n\t\t\t\tfullSchema: schema.fullSchema as TFullSchema,\n\t\t\t\ttableNamesMap: schema.tableNamesMap,\n\t\t\t\tsession,\n\t\t\t}\n\t\t\t: {\n\t\t\t\tschema: undefined,\n\t\t\t\tfullSchema: {} as TFullSchema,\n\t\t\t\ttableNamesMap: {},\n\t\t\t\tsession,\n\t\t\t};\n\t\tthis.query = {} as typeof this['query'];\n\t\tif (this._.schema) {\n\t\t\tfor (const [tableName, columns] of Object.entries(this._.schema)) {\n\t\t\t\t(this.query as PgDatabase>['query'])[tableName] = new RelationalQueryBuilder(\n\t\t\t\t\tschema!.fullSchema,\n\t\t\t\t\tthis._.schema,\n\t\t\t\t\tthis._.tableNamesMap,\n\t\t\t\t\tschema!.fullSchema[tableName] as PgTable,\n\t\t\t\t\tcolumns,\n\t\t\t\t\tdialect,\n\t\t\t\t\tsession,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a subquery that defines a temporary named result set as a CTE.\n\t *\n\t * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}\n\t *\n\t * @param alias The alias for the subquery.\n\t *\n\t * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Create a subquery with alias 'sq' and use it in the select query\n\t * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));\n\t *\n\t * const result = await db.with(sq).select().from(sq);\n\t * ```\n\t *\n\t * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:\n\t *\n\t * ```ts\n\t * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query\n\t * const sq = db.$with('sq').as(db.select({\n\t * name: sql`upper(${users.name})`.as('name'),\n\t * })\n\t * .from(users));\n\t *\n\t * const result = await db.with(sq).select({ name: sq.name }).from(sq);\n\t * ```\n\t */\n\t$with(alias: TAlias) {\n\t\treturn {\n\t\t\tas(\n\t\t\t\tqb: TypedQueryBuilder | ((qb: QueryBuilder) => TypedQueryBuilder),\n\t\t\t): WithSubqueryWithSelection {\n\t\t\t\tif (typeof qb === 'function') {\n\t\t\t\t\tqb = qb(new QueryBuilder());\n\t\t\t\t}\n\n\t\t\t\treturn new Proxy(\n\t\t\t\t\tnew WithSubquery(qb.getSQL(), qb.getSelectedFields() as SelectedFields, alias, true),\n\t\t\t\t\tnew SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t\t\t) as WithSubqueryWithSelection;\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Incorporates a previously defined CTE (using `$with`) into the main query.\n\t *\n\t * This method allows the main query to reference a temporary named result set.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}\n\t *\n\t * @param queries The CTEs to incorporate into the main query.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Define a subquery 'sq' as a CTE using $with\n\t * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));\n\t *\n\t * // Incorporate the CTE 'sq' into the main query and select from it\n\t * const result = await db.with(sq).select().from(sq);\n\t * ```\n\t */\n\twith(...queries: WithSubquery[]) {\n\t\tconst self = this;\n\n\t\t/**\n\t\t * Creates a select query.\n\t\t *\n\t\t * Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.\n\t\t *\n\t\t * Use `.from()` method to specify which table to select from.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/select}\n\t\t *\n\t\t * @param fields The selection object.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Select all columns and all rows from the 'cars' table\n\t\t * const allCars: Car[] = await db.select().from(cars);\n\t\t *\n\t\t * // Select specific columns and all rows from the 'cars' table\n\t\t * const carsIdsAndBrands: { id: number; brand: string }[] = await db.select({\n\t\t * id: cars.id,\n\t\t * brand: cars.brand\n\t\t * })\n\t\t * .from(cars);\n\t\t * ```\n\t\t *\n\t\t * Like in SQL, you can use arbitrary expressions as selection fields, not just table columns:\n\t\t *\n\t\t * ```ts\n\t\t * // Select specific columns along with expression and all rows from the 'cars' table\n\t\t * const carsIdsAndLowerNames: { id: number; lowerBrand: string }[] = await db.select({\n\t\t * id: cars.id,\n\t\t * lowerBrand: sql`lower(${cars.brand})`,\n\t\t * })\n\t\t * .from(cars);\n\t\t * ```\n\t\t */\n\t\tfunction select(): PgSelectBuilder;\n\t\tfunction select(fields: TSelection): PgSelectBuilder;\n\t\tfunction select(fields?: SelectedFields): PgSelectBuilder {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Adds `distinct` expression to the select query.\n\t\t *\n\t\t * Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.\n\t\t *\n\t\t * Use `.from()` method to specify which table to select from.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/select#distinct}\n\t\t *\n\t\t * @param fields The selection object.\n\t\t *\n\t\t * @example\n\t\t * ```ts\n\t\t * // Select all unique rows from the 'cars' table\n\t\t * await db.selectDistinct()\n\t\t * .from(cars)\n\t\t * .orderBy(cars.id, cars.brand, cars.color);\n\t\t *\n\t\t * // Select all unique brands from the 'cars' table\n\t\t * await db.selectDistinct({ brand: cars.brand })\n\t\t * .from(cars)\n\t\t * .orderBy(cars.brand);\n\t\t * ```\n\t\t */\n\t\tfunction selectDistinct(): PgSelectBuilder;\n\t\tfunction selectDistinct(fields: TSelection): PgSelectBuilder;\n\t\tfunction selectDistinct(fields?: SelectedFields): PgSelectBuilder {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t\tdistinct: true,\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Adds `distinct on` expression to the select query.\n\t\t *\n\t\t * Calling this method will specify how the unique rows are determined.\n\t\t *\n\t\t * Use `.from()` method to specify which table to select from.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/select#distinct}\n\t\t *\n\t\t * @param on The expression defining uniqueness.\n\t\t * @param fields The selection object.\n\t\t *\n\t\t * @example\n\t\t * ```ts\n\t\t * // Select the first row for each unique brand from the 'cars' table\n\t\t * await db.selectDistinctOn([cars.brand])\n\t\t * .from(cars)\n\t\t * .orderBy(cars.brand);\n\t\t *\n\t\t * // Selects the first occurrence of each unique car brand along with its color from the 'cars' table\n\t\t * await db.selectDistinctOn([cars.brand], { brand: cars.brand, color: cars.color })\n\t\t * .from(cars)\n\t\t * .orderBy(cars.brand, cars.color);\n\t\t * ```\n\t\t */\n\t\tfunction selectDistinctOn(on: (PgColumn | SQLWrapper)[]): PgSelectBuilder;\n\t\tfunction selectDistinctOn(\n\t\t\ton: (PgColumn | SQLWrapper)[],\n\t\t\tfields: TSelection,\n\t\t): PgSelectBuilder;\n\t\tfunction selectDistinctOn(\n\t\t\ton: (PgColumn | SQLWrapper)[],\n\t\t\tfields?: SelectedFields,\n\t\t): PgSelectBuilder {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t\tdistinct: { on },\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Creates an update query.\n\t\t *\n\t\t * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.\n\t\t *\n\t\t * Use `.set()` method to specify which values to update.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/update}\n\t\t *\n\t\t * @param table The table to update.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Update all rows in the 'cars' table\n\t\t * await db.update(cars).set({ color: 'red' });\n\t\t *\n\t\t * // Update rows with filters and conditions\n\t\t * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));\n\t\t *\n\t\t * // Update with returning clause\n\t\t * const updatedCar: Car[] = await db.update(cars)\n\t\t * .set({ color: 'red' })\n\t\t * .where(eq(cars.id, 1))\n\t\t * .returning();\n\t\t * ```\n\t\t */\n\t\tfunction update(table: TTable): PgUpdateBuilder {\n\t\t\treturn new PgUpdateBuilder(table, self.session, self.dialect, queries);\n\t\t}\n\n\t\t/**\n\t\t * Creates an insert query.\n\t\t *\n\t\t * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/insert}\n\t\t *\n\t\t * @param table The table to insert into.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Insert one row\n\t\t * await db.insert(cars).values({ brand: 'BMW' });\n\t\t *\n\t\t * // Insert multiple rows\n\t\t * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);\n\t\t *\n\t\t * // Insert with returning clause\n\t\t * const insertedCar: Car[] = await db.insert(cars)\n\t\t * .values({ brand: 'BMW' })\n\t\t * .returning();\n\t\t * ```\n\t\t */\n\t\tfunction insert(table: TTable): PgInsertBuilder {\n\t\t\treturn new PgInsertBuilder(table, self.session, self.dialect, queries);\n\t\t}\n\n\t\t/**\n\t\t * Creates a delete query.\n\t\t *\n\t\t * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/delete}\n\t\t *\n\t\t * @param table The table to delete from.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Delete all rows in the 'cars' table\n\t\t * await db.delete(cars);\n\t\t *\n\t\t * // Delete rows with filters and conditions\n\t\t * await db.delete(cars).where(eq(cars.color, 'green'));\n\t\t *\n\t\t * // Delete with returning clause\n\t\t * const deletedCar: Car[] = await db.delete(cars)\n\t\t * .where(eq(cars.id, 1))\n\t\t * .returning();\n\t\t * ```\n\t\t */\n\t\tfunction delete_(table: TTable): PgDeleteBase {\n\t\t\treturn new PgDeleteBase(table, self.session, self.dialect, queries);\n\t\t}\n\n\t\treturn { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };\n\t}\n\n\t/**\n\t * Creates a select query.\n\t *\n\t * Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.\n\t *\n\t * Use `.from()` method to specify which table to select from.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select}\n\t *\n\t * @param fields The selection object.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all columns and all rows from the 'cars' table\n\t * const allCars: Car[] = await db.select().from(cars);\n\t *\n\t * // Select specific columns and all rows from the 'cars' table\n\t * const carsIdsAndBrands: { id: number; brand: string }[] = await db.select({\n\t * id: cars.id,\n\t * brand: cars.brand\n\t * })\n\t * .from(cars);\n\t * ```\n\t *\n\t * Like in SQL, you can use arbitrary expressions as selection fields, not just table columns:\n\t *\n\t * ```ts\n\t * // Select specific columns along with expression and all rows from the 'cars' table\n\t * const carsIdsAndLowerNames: { id: number; lowerBrand: string }[] = await db.select({\n\t * id: cars.id,\n\t * lowerBrand: sql`lower(${cars.brand})`,\n\t * })\n\t * .from(cars);\n\t * ```\n\t */\n\tselect(): PgSelectBuilder;\n\tselect(fields: TSelection): PgSelectBuilder;\n\tselect(fields?: SelectedFields): PgSelectBuilder {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t});\n\t}\n\n\t/**\n\t * Adds `distinct` expression to the select query.\n\t *\n\t * Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.\n\t *\n\t * Use `.from()` method to specify which table to select from.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#distinct}\n\t *\n\t * @param fields The selection object.\n\t *\n\t * @example\n\t * ```ts\n\t * // Select all unique rows from the 'cars' table\n\t * await db.selectDistinct()\n\t * .from(cars)\n\t * .orderBy(cars.id, cars.brand, cars.color);\n\t *\n\t * // Select all unique brands from the 'cars' table\n\t * await db.selectDistinct({ brand: cars.brand })\n\t * .from(cars)\n\t * .orderBy(cars.brand);\n\t * ```\n\t */\n\tselectDistinct(): PgSelectBuilder;\n\tselectDistinct(fields: TSelection): PgSelectBuilder;\n\tselectDistinct(fields?: SelectedFields): PgSelectBuilder {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\tdistinct: true,\n\t\t});\n\t}\n\n\t/**\n\t * Adds `distinct on` expression to the select query.\n\t *\n\t * Calling this method will specify how the unique rows are determined.\n\t *\n\t * Use `.from()` method to specify which table to select from.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#distinct}\n\t *\n\t * @param on The expression defining uniqueness.\n\t * @param fields The selection object.\n\t *\n\t * @example\n\t * ```ts\n\t * // Select the first row for each unique brand from the 'cars' table\n\t * await db.selectDistinctOn([cars.brand])\n\t * .from(cars)\n\t * .orderBy(cars.brand);\n\t *\n\t * // Selects the first occurrence of each unique car brand along with its color from the 'cars' table\n\t * await db.selectDistinctOn([cars.brand], { brand: cars.brand, color: cars.color })\n\t * .from(cars)\n\t * .orderBy(cars.brand, cars.color);\n\t * ```\n\t */\n\tselectDistinctOn(on: (PgColumn | SQLWrapper)[]): PgSelectBuilder;\n\tselectDistinctOn(\n\t\ton: (PgColumn | SQLWrapper)[],\n\t\tfields: TSelection,\n\t): PgSelectBuilder;\n\tselectDistinctOn(\n\t\ton: (PgColumn | SQLWrapper)[],\n\t\tfields?: SelectedFields,\n\t): PgSelectBuilder {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\tdistinct: { on },\n\t\t});\n\t}\n\n\t/**\n\t * Creates an update query.\n\t *\n\t * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.\n\t *\n\t * Use `.set()` method to specify which values to update.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/update}\n\t *\n\t * @param table The table to update.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Update all rows in the 'cars' table\n\t * await db.update(cars).set({ color: 'red' });\n\t *\n\t * // Update rows with filters and conditions\n\t * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));\n\t *\n\t * // Update with returning clause\n\t * const updatedCar: Car[] = await db.update(cars)\n\t * .set({ color: 'red' })\n\t * .where(eq(cars.id, 1))\n\t * .returning();\n\t * ```\n\t */\n\tupdate(table: TTable): PgUpdateBuilder {\n\t\treturn new PgUpdateBuilder(table, this.session, this.dialect);\n\t}\n\n\t/**\n\t * Creates an insert query.\n\t *\n\t * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert}\n\t *\n\t * @param table The table to insert into.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Insert one row\n\t * await db.insert(cars).values({ brand: 'BMW' });\n\t *\n\t * // Insert multiple rows\n\t * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);\n\t *\n\t * // Insert with returning clause\n\t * const insertedCar: Car[] = await db.insert(cars)\n\t * .values({ brand: 'BMW' })\n\t * .returning();\n\t * ```\n\t */\n\tinsert(table: TTable): PgInsertBuilder {\n\t\treturn new PgInsertBuilder(table, this.session, this.dialect);\n\t}\n\n\t/**\n\t * Creates a delete query.\n\t *\n\t * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/delete}\n\t *\n\t * @param table The table to delete from.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Delete all rows in the 'cars' table\n\t * await db.delete(cars);\n\t *\n\t * // Delete rows with filters and conditions\n\t * await db.delete(cars).where(eq(cars.color, 'green'));\n\t *\n\t * // Delete with returning clause\n\t * const deletedCar: Car[] = await db.delete(cars)\n\t * .where(eq(cars.id, 1))\n\t * .returning();\n\t * ```\n\t */\n\tdelete(table: TTable): PgDeleteBase {\n\t\treturn new PgDeleteBase(table, this.session, this.dialect);\n\t}\n\n\trefreshMaterializedView(view: TView): PgRefreshMaterializedView {\n\t\treturn new PgRefreshMaterializedView(view, this.session, this.dialect);\n\t}\n\n\texecute = Record>(\n\t\tquery: SQLWrapper,\n\t): PgRaw> {\n\t\tconst sql = query.getSQL();\n\t\tconst builtQuery = this.dialect.sqlToQuery(sql);\n\t\tconst prepared = this.session.prepareQuery<\n\t\t\tPreparedQueryConfig & { execute: PgQueryResultKind }\n\t\t>(\n\t\t\tbuiltQuery,\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tfalse,\n\t\t);\n\t\treturn new PgRaw(\n\t\t\t() => prepared.execute(),\n\t\t\tsql,\n\t\t\tbuiltQuery,\n\t\t\t(result) => prepared.mapResult(result, true),\n\t\t);\n\t}\n\n\ttransaction(\n\t\ttransaction: (tx: PgTransaction) => Promise,\n\t\tconfig?: PgTransactionConfig,\n\t): Promise {\n\t\treturn this.session.transaction(transaction, config);\n\t}\n}\n\nexport type PgWithReplicas = Q & { $primary: Q };\n\nexport const withReplicas = <\n\tHKT extends PgQueryResultHKT,\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n\tQ extends PgDatabase,\n>(\n\tprimary: Q,\n\treplicas: [Q, ...Q[]],\n\tgetReplica: (replicas: Q[]) => Q = () => replicas[Math.floor(Math.random() * replicas.length)]!,\n): PgWithReplicas => {\n\tconst select: Q['select'] = (...args: []) => getReplica(replicas).select(...args);\n\tconst selectDistinct: Q['selectDistinct'] = (...args: []) => getReplica(replicas).selectDistinct(...args);\n\tconst selectDistinctOn: Q['selectDistinctOn'] = (...args: [any]) => getReplica(replicas).selectDistinctOn(...args);\n\tconst $with: Q['with'] = (...args: any) => getReplica(replicas).with(...args);\n\n\tconst update: Q['update'] = (...args: [any]) => primary.update(...args);\n\tconst insert: Q['insert'] = (...args: [any]) => primary.insert(...args);\n\tconst $delete: Q['delete'] = (...args: [any]) => primary.delete(...args);\n\tconst execute: Q['execute'] = (...args: [any]) => primary.execute(...args);\n\tconst transaction: Q['transaction'] = (...args: [any]) => primary.transaction(...args);\n\tconst refreshMaterializedView: Q['refreshMaterializedView'] = (...args: [any]) =>\n\t\tprimary.refreshMaterializedView(...args);\n\n\treturn {\n\t\t...primary,\n\t\tupdate,\n\t\tinsert,\n\t\tdelete: $delete,\n\t\texecute,\n\t\ttransaction,\n\t\trefreshMaterializedView,\n\t\t$primary: primary,\n\t\tselect,\n\t\tselectDistinct,\n\t\tselectDistinctOn,\n\t\twith: $with,\n\t\tget query() {\n\t\t\treturn getReplica(replicas).query;\n\t\t},\n\t};\n};\n", "import { entityKind } from '~/entity.ts';\nimport type { PgDialect } from '~/pg-core/dialect.ts';\nimport type {\n\tPgPreparedQuery,\n\tPgQueryResultHKT,\n\tPgQueryResultKind,\n\tPgSession,\n\tPreparedQueryConfig,\n} from '~/pg-core/session.ts';\nimport type { PgTable } from '~/pg-core/table.ts';\nimport type { SelectResultFields } from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Query, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport { tracer } from '~/tracing.ts';\nimport { orderSelectedFields } from '~/utils.ts';\nimport type { PgColumn } from '../columns/common.ts';\nimport type { SelectedFieldsFlat, SelectedFieldsOrdered } from './select.types.ts';\n\nexport type PgDeleteWithout<\n\tT extends AnyPgDeleteBase,\n\tTDynamic extends boolean,\n\tK extends keyof T & string,\n> = TDynamic extends true ? T\n\t: Omit<\n\t\tPgDeleteBase<\n\t\t\tT['_']['table'],\n\t\t\tT['_']['queryResult'],\n\t\t\tT['_']['returning'],\n\t\t\tTDynamic,\n\t\t\tT['_']['excludedMethods'] | K\n\t\t>,\n\t\tT['_']['excludedMethods'] | K\n\t>;\n\nexport type PgDelete<\n\tTTable extends PgTable = PgTable,\n\tTQueryResult extends PgQueryResultHKT = PgQueryResultHKT,\n\tTReturning extends Record | undefined = Record | undefined,\n> = PgDeleteBase;\n\nexport interface PgDeleteConfig {\n\twhere?: SQL | undefined;\n\ttable: PgTable;\n\treturning?: SelectedFieldsOrdered;\n\twithList?: Subquery[];\n}\n\nexport type PgDeleteReturningAll<\n\tT extends AnyPgDeleteBase,\n\tTDynamic extends boolean,\n> = PgDeleteWithout<\n\tPgDeleteBase<\n\t\tT['_']['table'],\n\t\tT['_']['queryResult'],\n\t\tT['_']['table']['$inferSelect'],\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type PgDeleteReturning<\n\tT extends AnyPgDeleteBase,\n\tTDynamic extends boolean,\n\tTSelectedFields extends SelectedFieldsFlat,\n> = PgDeleteWithout<\n\tPgDeleteBase<\n\t\tT['_']['table'],\n\t\tT['_']['queryResult'],\n\t\tSelectResultFields,\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type PgDeletePrepare = PgPreparedQuery<\n\tPreparedQueryConfig & {\n\t\texecute: T['_']['returning'] extends undefined ? PgQueryResultKind\n\t\t\t: T['_']['returning'][];\n\t}\n>;\n\nexport type PgDeleteDynamic = PgDelete<\n\tT['_']['table'],\n\tT['_']['queryResult'],\n\tT['_']['returning']\n>;\n\nexport type AnyPgDeleteBase = PgDeleteBase;\n\nexport interface PgDeleteBase<\n\tTTable extends PgTable,\n\tTQueryResult extends PgQueryResultHKT,\n\tTReturning extends Record | undefined = undefined,\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n> extends\n\tQueryPromise : TReturning[]>,\n\tRunnableQuery : TReturning[], 'pg'>,\n\tSQLWrapper\n{\n\treadonly _: {\n\t\tdialect: 'pg';\n\t\treadonly table: TTable;\n\t\treadonly queryResult: TQueryResult;\n\t\treadonly returning: TReturning;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TReturning extends undefined ? PgQueryResultKind : TReturning[];\n\t};\n}\n\nexport class PgDeleteBase<\n\tTTable extends PgTable,\n\tTQueryResult extends PgQueryResultHKT,\n\tTReturning extends Record | undefined = undefined,\n\tTDynamic extends boolean = false,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTExcludedMethods extends string = never,\n> extends QueryPromise : TReturning[]>\n\timplements\n\t\tRunnableQuery : TReturning[], 'pg'>,\n\t\tSQLWrapper\n{\n\tstatic readonly [entityKind]: string = 'PgDelete';\n\n\tprivate config: PgDeleteConfig;\n\n\tconstructor(\n\t\ttable: TTable,\n\t\tprivate session: PgSession,\n\t\tprivate dialect: PgDialect,\n\t\twithList?: Subquery[],\n\t) {\n\t\tsuper();\n\t\tthis.config = { table, withList };\n\t}\n\n\t/**\n\t * Adds a `where` clause to the query.\n\t *\n\t * Calling this method will delete only those rows that fulfill a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/delete}\n\t *\n\t * @param where the `where` clause.\n\t *\n\t * @example\n\t * You can use conditional operators and `sql function` to filter the rows to be deleted.\n\t *\n\t * ```ts\n\t * // Delete all cars with green color\n\t * await db.delete(cars).where(eq(cars.color, 'green'));\n\t * // or\n\t * await db.delete(cars).where(sql`${cars.color} = 'green'`)\n\t * ```\n\t *\n\t * You can logically combine conditional operators with `and()` and `or()` operators:\n\t *\n\t * ```ts\n\t * // Delete all BMW cars with a green color\n\t * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t *\n\t * // Delete all cars with the green or blue color\n\t * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t * ```\n\t */\n\twhere(where: SQL | undefined): PgDeleteWithout {\n\t\tthis.config.where = where;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `returning` clause to the query.\n\t *\n\t * Calling this method will return the specified fields of the deleted rows. If no fields are specified, all fields will be returned.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/delete#delete-with-return}\n\t *\n\t * @example\n\t * ```ts\n\t * // Delete all cars with the green color and return all fields\n\t * const deletedCars: Car[] = await db.delete(cars)\n\t * .where(eq(cars.color, 'green'))\n\t * .returning();\n\t *\n\t * // Delete all cars with the green color and return only their id and brand fields\n\t * const deletedCarsIdsAndBrands: { id: number, brand: string }[] = await db.delete(cars)\n\t * .where(eq(cars.color, 'green'))\n\t * .returning({ id: cars.id, brand: cars.brand });\n\t * ```\n\t */\n\treturning(): PgDeleteReturningAll;\n\treturning(\n\t\tfields: TSelectedFields,\n\t): PgDeleteReturning;\n\treturning(\n\t\tfields: SelectedFieldsFlat = this.config.table[Table.Symbol.Columns],\n\t): PgDeleteReturning {\n\t\tthis.config.returning = orderSelectedFields(fields);\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildDeleteQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(name?: string): PgDeletePrepare {\n\t\treturn tracer.startActiveSpan('drizzle.prepareQuery', () => {\n\t\t\treturn this.session.prepareQuery<\n\t\t\t\tPreparedQueryConfig & {\n\t\t\t\t\texecute: TReturning extends undefined ? PgQueryResultKind : TReturning[];\n\t\t\t\t}\n\t\t\t>(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);\n\t\t});\n\t}\n\n\tprepare(name: string): PgDeletePrepare {\n\t\treturn this._prepare(name);\n\t}\n\n\toverride execute: ReturnType['execute'] = (placeholderValues) => {\n\t\treturn tracer.startActiveSpan('drizzle.operation', () => {\n\t\t\treturn this._prepare().execute(placeholderValues);\n\t\t});\n\t};\n\n\t$dynamic(): PgDeleteDynamic {\n\t\treturn this as any;\n\t}\n}\n", "import { entityKind, is } from '~/entity.ts';\nimport type { PgDialect } from '~/pg-core/dialect.ts';\nimport type { IndexColumn } from '~/pg-core/indexes.ts';\nimport type {\n\tPgPreparedQuery,\n\tPgQueryResultHKT,\n\tPgQueryResultKind,\n\tPgSession,\n\tPreparedQueryConfig,\n} from '~/pg-core/session.ts';\nimport type { PgTable } from '~/pg-core/table.ts';\nimport type { SelectResultFields } from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Placeholder, Query, SQLWrapper } from '~/sql/sql.ts';\nimport { Param, SQL, sql } from '~/sql/sql.ts';\nimport type { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport { tracer } from '~/tracing.ts';\nimport { mapUpdateSet, orderSelectedFields } from '~/utils.ts';\nimport type { PgColumn } from '../columns/common.ts';\nimport type { SelectedFieldsFlat, SelectedFieldsOrdered } from './select.types.ts';\nimport type { PgUpdateSetSource } from './update.ts';\n\nexport interface PgInsertConfig {\n\ttable: TTable;\n\tvalues: Record[];\n\twithList?: Subquery[];\n\tonConflict?: SQL;\n\treturning?: SelectedFieldsOrdered;\n}\n\nexport type PgInsertValue =\n\t& {\n\t\t[Key in keyof TTable['$inferInsert']]: TTable['$inferInsert'][Key] | SQL | Placeholder;\n\t}\n\t& {};\n\nexport class PgInsertBuilder {\n\tstatic readonly [entityKind]: string = 'PgInsertBuilder';\n\n\tconstructor(\n\t\tprivate table: TTable,\n\t\tprivate session: PgSession,\n\t\tprivate dialect: PgDialect,\n\t\tprivate withList?: Subquery[],\n\t) {}\n\n\tvalues(value: PgInsertValue): PgInsertBase;\n\tvalues(values: PgInsertValue[]): PgInsertBase;\n\tvalues(values: PgInsertValue | PgInsertValue[]): PgInsertBase {\n\t\tvalues = Array.isArray(values) ? values : [values];\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('values() must be called with at least one value');\n\t\t}\n\t\tconst mappedValues = values.map((entry) => {\n\t\t\tconst result: Record = {};\n\t\t\tconst cols = this.table[Table.Symbol.Columns];\n\t\t\tfor (const colKey of Object.keys(entry)) {\n\t\t\t\tconst colValue = entry[colKey as keyof typeof entry];\n\t\t\t\tresult[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\n\t\treturn new PgInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);\n\t}\n}\n\nexport type PgInsertWithout =\n\tTDynamic extends true ? T\n\t\t: Omit<\n\t\t\tPgInsertBase<\n\t\t\t\tT['_']['table'],\n\t\t\t\tT['_']['queryResult'],\n\t\t\t\tT['_']['returning'],\n\t\t\t\tTDynamic,\n\t\t\t\tT['_']['excludedMethods'] | K\n\t\t\t>,\n\t\t\tT['_']['excludedMethods'] | K\n\t\t>;\n\nexport type PgInsertReturning<\n\tT extends AnyPgInsert,\n\tTDynamic extends boolean,\n\tTSelectedFields extends SelectedFieldsFlat,\n> = PgInsertBase<\n\tT['_']['table'],\n\tT['_']['queryResult'],\n\tSelectResultFields,\n\tTDynamic,\n\tT['_']['excludedMethods']\n>;\n\nexport type PgInsertReturningAll = PgInsertBase<\n\tT['_']['table'],\n\tT['_']['queryResult'],\n\tT['_']['table']['$inferSelect'],\n\tTDynamic,\n\tT['_']['excludedMethods']\n>;\n\nexport interface PgInsertOnConflictDoUpdateConfig {\n\ttarget: IndexColumn | IndexColumn[];\n\t/** @deprecated use either `targetWhere` or `setWhere` */\n\twhere?: SQL;\n\t// TODO: add tests for targetWhere and setWhere\n\ttargetWhere?: SQL;\n\tsetWhere?: SQL;\n\tset: PgUpdateSetSource;\n}\n\nexport type PgInsertPrepare = PgPreparedQuery<\n\tPreparedQueryConfig & {\n\t\texecute: T['_']['returning'] extends undefined ? PgQueryResultKind\n\t\t\t: T['_']['returning'][];\n\t}\n>;\n\nexport type PgInsertDynamic = PgInsert<\n\tT['_']['table'],\n\tT['_']['queryResult'],\n\tT['_']['returning']\n>;\n\nexport type AnyPgInsert = PgInsertBase;\n\nexport type PgInsert<\n\tTTable extends PgTable = PgTable,\n\tTQueryResult extends PgQueryResultHKT = PgQueryResultHKT,\n\tTReturning extends Record | undefined = Record | undefined,\n> = PgInsertBase;\n\nexport interface PgInsertBase<\n\tTTable extends PgTable,\n\tTQueryResult extends PgQueryResultHKT,\n\tTReturning extends Record | undefined = undefined,\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n> extends\n\tQueryPromise : TReturning[]>,\n\tRunnableQuery : TReturning[], 'pg'>,\n\tSQLWrapper\n{\n\treadonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly table: TTable;\n\t\treadonly queryResult: TQueryResult;\n\t\treadonly returning: TReturning;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TReturning extends undefined ? PgQueryResultKind : TReturning[];\n\t};\n}\n\nexport class PgInsertBase<\n\tTTable extends PgTable,\n\tTQueryResult extends PgQueryResultHKT,\n\tTReturning extends Record | undefined = undefined,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTDynamic extends boolean = false,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTExcludedMethods extends string = never,\n> extends QueryPromise : TReturning[]>\n\timplements\n\t\tRunnableQuery : TReturning[], 'pg'>,\n\t\tSQLWrapper\n{\n\tstatic readonly [entityKind]: string = 'PgInsert';\n\n\tprivate config: PgInsertConfig;\n\n\tconstructor(\n\t\ttable: TTable,\n\t\tvalues: PgInsertConfig['values'],\n\t\tprivate session: PgSession,\n\t\tprivate dialect: PgDialect,\n\t\twithList?: Subquery[],\n\t) {\n\t\tsuper();\n\t\tthis.config = { table, values, withList };\n\t}\n\n\t/**\n\t * Adds a `returning` clause to the query.\n\t *\n\t * Calling this method will return the specified fields of the inserted rows. If no fields are specified, all fields will be returned.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert#insert-returning}\n\t *\n\t * @example\n\t * ```ts\n\t * // Insert one row and return all fields\n\t * const insertedCar: Car[] = await db.insert(cars)\n\t * .values({ brand: 'BMW' })\n\t * .returning();\n\t *\n\t * // Insert one row and return only the id\n\t * const insertedCarId: { id: number }[] = await db.insert(cars)\n\t * .values({ brand: 'BMW' })\n\t * .returning({ id: cars.id });\n\t * ```\n\t */\n\treturning(): PgInsertWithout, TDynamic, 'returning'>;\n\treturning(\n\t\tfields: TSelectedFields,\n\t): PgInsertWithout, TDynamic, 'returning'>;\n\treturning(\n\t\tfields: SelectedFieldsFlat = this.config.table[Table.Symbol.Columns],\n\t): PgInsertWithout {\n\t\tthis.config.returning = orderSelectedFields(fields);\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `on conflict do nothing` clause to the query.\n\t *\n\t * Calling this method simply avoids inserting a row as its alternative action.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}\n\t *\n\t * @param config The `target` and `where` clauses.\n\t *\n\t * @example\n\t * ```ts\n\t * // Insert one row and cancel the insert if there's a conflict\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoNothing();\n\t *\n\t * // Explicitly specify conflict target\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoNothing({ target: cars.id });\n\t * ```\n\t */\n\tonConflictDoNothing(\n\t\tconfig: { target?: IndexColumn | IndexColumn[]; where?: SQL } = {},\n\t): PgInsertWithout {\n\t\tif (config.target === undefined) {\n\t\t\tthis.config.onConflict = sql`do nothing`;\n\t\t} else {\n\t\t\tlet targetColumn = '';\n\t\t\ttargetColumn = Array.isArray(config.target)\n\t\t\t\t? config.target.map((it) => this.dialect.escapeName(it.name)).join(',')\n\t\t\t\t: this.dialect.escapeName(config.target.name);\n\n\t\t\tconst whereSql = config.where ? sql` where ${config.where}` : undefined;\n\t\t\tthis.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `on conflict do update` clause to the query.\n\t *\n\t * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}\n\t *\n\t * @param config The `target`, `set` and `where` clauses.\n\t *\n\t * @example\n\t * ```ts\n\t * // Update the row if there's a conflict\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoUpdate({\n\t * target: cars.id,\n\t * set: { brand: 'Porsche' }\n\t * });\n\t *\n\t * // Upsert with 'where' clause\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoUpdate({\n\t * target: cars.id,\n\t * set: { brand: 'newBMW' },\n\t * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,\n\t * });\n\t * ```\n\t */\n\tonConflictDoUpdate(\n\t\tconfig: PgInsertOnConflictDoUpdateConfig,\n\t): PgInsertWithout {\n\t\tif (config.where && (config.targetWhere || config.setWhere)) {\n\t\t\tthrow new Error(\n\t\t\t\t'You cannot use both \"where\" and \"targetWhere\"/\"setWhere\" at the same time - \"where\" is deprecated, use \"targetWhere\" or \"setWhere\" instead.',\n\t\t\t);\n\t\t}\n\t\tconst whereSql = config.where ? sql` where ${config.where}` : undefined;\n\t\tconst targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;\n\t\tconst setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;\n\t\tconst setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));\n\t\tlet targetColumn = '';\n\t\ttargetColumn = Array.isArray(config.target)\n\t\t\t? config.target.map((it) => this.dialect.escapeName(it.name)).join(',')\n\t\t\t: this.dialect.escapeName(config.target.name);\n\t\tthis.config.onConflict = sql`(${\n\t\t\tsql.raw(targetColumn)\n\t\t})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildInsertQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(name?: string): PgInsertPrepare {\n\t\treturn tracer.startActiveSpan('drizzle.prepareQuery', () => {\n\t\t\treturn this.session.prepareQuery<\n\t\t\t\tPreparedQueryConfig & {\n\t\t\t\t\texecute: TReturning extends undefined ? PgQueryResultKind : TReturning[];\n\t\t\t\t}\n\t\t\t>(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);\n\t\t});\n\t}\n\n\tprepare(name: string): PgInsertPrepare {\n\t\treturn this._prepare(name);\n\t}\n\n\toverride execute: ReturnType['execute'] = (placeholderValues) => {\n\t\treturn tracer.startActiveSpan('drizzle.operation', () => {\n\t\t\treturn this._prepare().execute(placeholderValues);\n\t\t});\n\t};\n\n\t$dynamic(): PgInsertDynamic {\n\t\treturn this as any;\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { PgDialect } from '~/pg-core/dialect.ts';\nimport type { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport type { ColumnsSelection, SQLWrapper } from '~/sql/sql.ts';\nimport { WithSubquery } from '~/subquery.ts';\nimport type { PgColumn } from '../columns/index.ts';\nimport type { WithSubqueryWithSelection } from '../subquery.ts';\nimport { PgSelectBuilder } from './select.ts';\nimport type { SelectedFields } from './select.types.ts';\n\nexport class QueryBuilder {\n\tstatic readonly [entityKind]: string = 'PgQueryBuilder';\n\n\tprivate dialect: PgDialect | undefined;\n\n\t$with(alias: TAlias) {\n\t\tconst queryBuilder = this;\n\n\t\treturn {\n\t\t\tas(\n\t\t\t\tqb: TypedQueryBuilder | ((qb: QueryBuilder) => TypedQueryBuilder),\n\t\t\t): WithSubqueryWithSelection {\n\t\t\t\tif (typeof qb === 'function') {\n\t\t\t\t\tqb = qb(queryBuilder);\n\t\t\t\t}\n\n\t\t\t\treturn new Proxy(\n\t\t\t\t\tnew WithSubquery(qb.getSQL(), qb.getSelectedFields() as SelectedFields, alias, true),\n\t\t\t\t\tnew SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t\t\t) as WithSubqueryWithSelection;\n\t\t\t},\n\t\t};\n\t}\n\n\twith(...queries: WithSubquery[]) {\n\t\tconst self = this;\n\n\t\tfunction select(): PgSelectBuilder;\n\t\tfunction select(fields: TSelection): PgSelectBuilder;\n\t\tfunction select(\n\t\t\tfields?: TSelection,\n\t\t): PgSelectBuilder {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: undefined,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\twithList: queries,\n\t\t\t});\n\t\t}\n\n\t\tfunction selectDistinct(): PgSelectBuilder;\n\t\tfunction selectDistinct(fields: TSelection): PgSelectBuilder;\n\t\tfunction selectDistinct(fields?: SelectedFields): PgSelectBuilder {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: undefined,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\tdistinct: true,\n\t\t\t});\n\t\t}\n\n\t\tfunction selectDistinctOn(on: (PgColumn | SQLWrapper)[]): PgSelectBuilder;\n\t\tfunction selectDistinctOn(\n\t\t\ton: (PgColumn | SQLWrapper)[],\n\t\t\tfields: TSelection,\n\t\t): PgSelectBuilder;\n\t\tfunction selectDistinctOn(\n\t\t\ton: (PgColumn | SQLWrapper)[],\n\t\t\tfields?: SelectedFields,\n\t\t): PgSelectBuilder {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: undefined,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\tdistinct: { on },\n\t\t\t});\n\t\t}\n\n\t\treturn { select, selectDistinct, selectDistinctOn };\n\t}\n\n\tselect(): PgSelectBuilder;\n\tselect(fields: TSelection): PgSelectBuilder;\n\tselect(fields?: TSelection): PgSelectBuilder {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: undefined,\n\t\t\tdialect: this.getDialect(),\n\t\t});\n\t}\n\n\tselectDistinct(): PgSelectBuilder;\n\tselectDistinct(fields: TSelection): PgSelectBuilder;\n\tselectDistinct(fields?: SelectedFields): PgSelectBuilder {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: undefined,\n\t\t\tdialect: this.getDialect(),\n\t\t\tdistinct: true,\n\t\t});\n\t}\n\n\tselectDistinctOn(on: (PgColumn | SQLWrapper)[]): PgSelectBuilder;\n\tselectDistinctOn(\n\t\ton: (PgColumn | SQLWrapper)[],\n\t\tfields: TSelection,\n\t): PgSelectBuilder;\n\tselectDistinctOn(\n\t\ton: (PgColumn | SQLWrapper)[],\n\t\tfields?: SelectedFields,\n\t): PgSelectBuilder {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: undefined,\n\t\t\tdialect: this.getDialect(),\n\t\t\tdistinct: { on },\n\t\t});\n\t}\n\n\t// Lazy load dialect to avoid circular dependency\n\tprivate getDialect() {\n\t\tif (!this.dialect) {\n\t\t\tthis.dialect = new PgDialect();\n\t\t}\n\n\t\treturn this.dialect;\n\t}\n}\n", "import { aliasedTable, aliasedTableColumn, mapColumnsInAliasedSQLToAlias, mapColumnsInSQLToAlias } from '~/alias.ts';\nimport { Column } from '~/column.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { DrizzleError } from '~/errors.ts';\nimport type { MigrationConfig, MigrationMeta } from '~/migrator.ts';\nimport {\n\tPgColumn,\n\tPgDate,\n\tPgDateString,\n\tPgJson,\n\tPgJsonb,\n\tPgNumeric,\n\tPgTime,\n\tPgTimestamp,\n\tPgTimestampString,\n\tPgUUID,\n} from '~/pg-core/columns/index.ts';\nimport type {\n\tPgDeleteConfig,\n\tPgInsertConfig,\n\tPgSelectJoinConfig,\n\tPgUpdateConfig,\n} from '~/pg-core/query-builders/index.ts';\nimport type { PgSelectConfig, SelectedFieldsOrdered } from '~/pg-core/query-builders/select.types.ts';\nimport { PgTable } from '~/pg-core/table.ts';\nimport {\n\ttype BuildRelationalQueryResult,\n\ttype DBQueryConfig,\n\tgetOperators,\n\tgetOrderByOperators,\n\tMany,\n\tnormalizeRelation,\n\tOne,\n\ttype Relation,\n\ttype TableRelationalConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport { and, eq, View } from '~/sql/index.ts';\nimport {\n\ttype DriverValueEncoder,\n\ttype Name,\n\tParam,\n\ttype QueryTypingsValue,\n\ttype QueryWithTypings,\n\tSQL,\n\tsql,\n\ttype SQLChunk,\n} from '~/sql/sql.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { getTableName, getTableUniqueName, Table } from '~/table.ts';\nimport { orderSelectedFields, type UpdateSet } from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type { PgSession } from './session.ts';\nimport { PgViewBase } from './view-base.ts';\nimport type { PgMaterializedView } from './view.ts';\n\nexport class PgDialect {\n\tstatic readonly [entityKind]: string = 'PgDialect';\n\n\tasync migrate(migrations: MigrationMeta[], session: PgSession, config: string | MigrationConfig): Promise {\n\t\tconst migrationsTable = typeof config === 'string'\n\t\t\t? '__drizzle_migrations'\n\t\t\t: config.migrationsTable ?? '__drizzle_migrations';\n\t\tconst migrationsSchema = typeof config === 'string' ? 'drizzle' : config.migrationsSchema ?? 'drizzle';\n\t\tconst migrationTableCreate = sql`\n\t\t\tCREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (\n\t\t\t\tid SERIAL PRIMARY KEY,\n\t\t\t\thash text NOT NULL,\n\t\t\t\tcreated_at bigint\n\t\t\t)\n\t\t`;\n\t\tawait session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);\n\t\tawait session.execute(migrationTableCreate);\n\n\t\tconst dbMigrations = await session.all<{ id: number; hash: string; created_at: string }>(\n\t\t\tsql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${\n\t\t\t\tsql.identifier(migrationsTable)\n\t\t\t} order by created_at desc limit 1`,\n\t\t);\n\n\t\tconst lastDbMigration = dbMigrations[0];\n\t\tawait session.transaction(async (tx) => {\n\t\t\tfor await (const migration of migrations) {\n\t\t\t\tif (\n\t\t\t\t\t!lastDbMigration\n\t\t\t\t\t|| Number(lastDbMigration.created_at) < migration.folderMillis\n\t\t\t\t) {\n\t\t\t\t\tfor (const stmt of migration.sql) {\n\t\t\t\t\t\tawait tx.execute(sql.raw(stmt));\n\t\t\t\t\t}\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\tsql`insert into ${sql.identifier(migrationsSchema)}.${\n\t\t\t\t\t\t\tsql.identifier(migrationsTable)\n\t\t\t\t\t\t} (\"hash\", \"created_at\") values(${migration.hash}, ${migration.folderMillis})`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tescapeName(name: string): string {\n\t\treturn `\"${name}\"`;\n\t}\n\n\tescapeParam(num: number): string {\n\t\treturn `$${num + 1}`;\n\t}\n\n\tescapeString(str: string): string {\n\t\treturn `'${str.replace(/'/g, \"''\")}'`;\n\t}\n\n\tprivate buildWithCTE(queries: Subquery[] | undefined): SQL | undefined {\n\t\tif (!queries?.length) return undefined;\n\n\t\tconst withSqlChunks = [sql`with `];\n\t\tfor (const [i, w] of queries.entries()) {\n\t\t\twithSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);\n\t\t\tif (i < queries.length - 1) {\n\t\t\t\twithSqlChunks.push(sql`, `);\n\t\t\t}\n\t\t}\n\t\twithSqlChunks.push(sql` `);\n\t\treturn sql.join(withSqlChunks);\n\t}\n\n\tbuildDeleteQuery({ table, where, returning, withList }: PgDeleteConfig): SQL {\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\treturn sql`${withSql}delete from ${table}${whereSql}${returningSql}`;\n\t}\n\n\tbuildUpdateSet(table: PgTable, set: UpdateSet): SQL {\n\t\tconst tableColumns = table[Table.Symbol.Columns];\n\n\t\tconst columnNames = Object.keys(tableColumns).filter((colName) =>\n\t\t\tset[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined\n\t\t);\n\n\t\tconst setSize = columnNames.length;\n\t\treturn sql.join(columnNames.flatMap((colName, i) => {\n\t\t\tconst col = tableColumns[colName]!;\n\n\t\t\tconst value = set[colName] ?? sql.param(col.onUpdateFn!(), col);\n\t\t\tconst res = sql`${sql.identifier(col.name)} = ${value}`;\n\n\t\t\tif (i < setSize - 1) {\n\t\t\t\treturn [res, sql.raw(', ')];\n\t\t\t}\n\t\t\treturn [res];\n\t\t}));\n\t}\n\n\tbuildUpdateQuery({ table, set, where, returning, withList }: PgUpdateConfig): SQL {\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst setSql = this.buildUpdateSet(table, set);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\treturn sql`${withSql}update ${table} set ${setSql}${whereSql}${returningSql}`;\n\t}\n\n\t/**\n\t * Builds selection SQL with provided fields/expressions\n\t *\n\t * Examples:\n\t *\n\t * `select from`\n\t *\n\t * `insert ... returning `\n\t *\n\t * If `isSingleTable` is true, then columns won't be prefixed with table name\n\t */\n\tprivate buildSelection(\n\t\tfields: SelectedFieldsOrdered,\n\t\t{ isSingleTable = false }: { isSingleTable?: boolean } = {},\n\t): SQL {\n\t\tconst columnsLen = fields.length;\n\n\t\tconst chunks = fields\n\t\t\t.flatMap(({ field }, i) => {\n\t\t\t\tconst chunk: SQLChunk[] = [];\n\n\t\t\t\tif (is(field, SQL.Aliased) && field.isSelectionField) {\n\t\t\t\t\tchunk.push(sql.identifier(field.fieldAlias));\n\t\t\t\t} else if (is(field, SQL.Aliased) || is(field, SQL)) {\n\t\t\t\t\tconst query = is(field, SQL.Aliased) ? field.sql : field;\n\n\t\t\t\t\tif (isSingleTable) {\n\t\t\t\t\t\tchunk.push(\n\t\t\t\t\t\t\tnew SQL(\n\t\t\t\t\t\t\t\tquery.queryChunks.map((c) => {\n\t\t\t\t\t\t\t\t\tif (is(c, PgColumn)) {\n\t\t\t\t\t\t\t\t\t\treturn sql.identifier(c.name);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn c;\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchunk.push(query);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (is(field, SQL.Aliased)) {\n\t\t\t\t\t\tchunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);\n\t\t\t\t\t}\n\t\t\t\t} else if (is(field, Column)) {\n\t\t\t\t\tif (isSingleTable) {\n\t\t\t\t\t\tchunk.push(sql.identifier(field.name));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchunk.push(field);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (i < columnsLen - 1) {\n\t\t\t\t\tchunk.push(sql`, `);\n\t\t\t\t}\n\n\t\t\t\treturn chunk;\n\t\t\t});\n\n\t\treturn sql.join(chunks);\n\t}\n\n\tbuildSelectQuery(\n\t\t{\n\t\t\twithList,\n\t\t\tfields,\n\t\t\tfieldsFlat,\n\t\t\twhere,\n\t\t\thaving,\n\t\t\ttable,\n\t\t\tjoins,\n\t\t\torderBy,\n\t\t\tgroupBy,\n\t\t\tlimit,\n\t\t\toffset,\n\t\t\tlockingClause,\n\t\t\tdistinct,\n\t\t\tsetOperators,\n\t\t}: PgSelectConfig,\n\t): SQL {\n\t\tconst fieldsList = fieldsFlat ?? orderSelectedFields(fields);\n\t\tfor (const f of fieldsList) {\n\t\t\tif (\n\t\t\t\tis(f.field, Column)\n\t\t\t\t&& getTableName(f.field.table)\n\t\t\t\t\t!== (is(table, Subquery)\n\t\t\t\t\t\t? table._.alias\n\t\t\t\t\t\t: is(table, PgViewBase)\n\t\t\t\t\t\t? table[ViewBaseConfig].name\n\t\t\t\t\t\t: is(table, SQL)\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: getTableName(table))\n\t\t\t\t&& !((table) =>\n\t\t\t\t\tjoins?.some(({ alias }) =>\n\t\t\t\t\t\talias === (table[Table.Symbol.IsAlias] ? getTableName(table) : table[Table.Symbol.BaseName])\n\t\t\t\t\t))(f.field.table)\n\t\t\t) {\n\t\t\t\tconst tableName = getTableName(f.field.table);\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Your \"${\n\t\t\t\t\t\tf.path.join('->')\n\t\t\t\t\t}\" field references a column \"${tableName}\".\"${f.field.name}\", but the table \"${tableName}\" is not part of the query! Did you forget to join it?`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst isSingleTable = !joins || joins.length === 0;\n\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tlet distinctSql: SQL | undefined;\n\t\tif (distinct) {\n\t\t\tdistinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;\n\t\t}\n\n\t\tconst selection = this.buildSelection(fieldsList, { isSingleTable });\n\n\t\tconst tableSql = (() => {\n\t\t\tif (is(table, Table) && table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]) {\n\t\t\t\tlet fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`;\n\t\t\t\tif (table[Table.Symbol.Schema]) {\n\t\t\t\t\tfullName = sql`${sql.identifier(table[Table.Symbol.Schema]!)}.${fullName}`;\n\t\t\t\t}\n\t\t\t\treturn sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;\n\t\t\t}\n\n\t\t\treturn table;\n\t\t})();\n\n\t\tconst joinsArray: SQL[] = [];\n\n\t\tif (joins) {\n\t\t\tfor (const [index, joinMeta] of joins.entries()) {\n\t\t\t\tif (index === 0) {\n\t\t\t\t\tjoinsArray.push(sql` `);\n\t\t\t\t}\n\t\t\t\tconst table = joinMeta.table;\n\t\t\t\tconst lateralSql = joinMeta.lateral ? sql` lateral` : undefined;\n\n\t\t\t\tif (is(table, PgTable)) {\n\t\t\t\t\tconst tableName = table[PgTable.Symbol.Name];\n\t\t\t\t\tconst tableSchema = table[PgTable.Symbol.Schema];\n\t\t\t\t\tconst origTableName = table[PgTable.Symbol.OriginalName];\n\t\t\t\t\tconst alias = tableName === origTableName ? undefined : joinMeta.alias;\n\t\t\t\t\tjoinsArray.push(\n\t\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${\n\t\t\t\t\t\t\ttableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined\n\t\t\t\t\t\t}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`,\n\t\t\t\t\t);\n\t\t\t\t} else if (is(table, View)) {\n\t\t\t\t\tconst viewName = table[ViewBaseConfig].name;\n\t\t\t\t\tconst viewSchema = table[ViewBaseConfig].schema;\n\t\t\t\t\tconst origViewName = table[ViewBaseConfig].originalName;\n\t\t\t\t\tconst alias = viewName === origViewName ? undefined : joinMeta.alias;\n\t\t\t\t\tjoinsArray.push(\n\t\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${\n\t\t\t\t\t\t\tviewSchema ? sql`${sql.identifier(viewSchema)}.` : undefined\n\t\t\t\t\t\t}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tjoinsArray.push(\n\t\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table} on ${joinMeta.on}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (index < joins.length - 1) {\n\t\t\t\t\tjoinsArray.push(sql` `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst joinsSql = sql.join(joinsArray);\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\tconst havingSql = having ? sql` having ${having}` : undefined;\n\n\t\tlet orderBySql;\n\t\tif (orderBy && orderBy.length > 0) {\n\t\t\torderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;\n\t\t}\n\n\t\tlet groupBySql;\n\t\tif (groupBy && groupBy.length > 0) {\n\t\t\tgroupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;\n\t\t}\n\n\t\tconst limitSql = typeof limit === 'object' || (typeof limit === 'number' && limit >= 0)\n\t\t\t? sql` limit ${limit}`\n\t\t\t: undefined;\n\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : undefined;\n\n\t\tconst lockingClauseSql = sql.empty();\n\t\tif (lockingClause) {\n\t\t\tconst clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;\n\t\t\tif (lockingClause.config.of) {\n\t\t\t\tclauseSql.append(\n\t\t\t\t\tsql` of ${\n\t\t\t\t\t\tsql.join(\n\t\t\t\t\t\t\tArray.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of],\n\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t)\n\t\t\t\t\t}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (lockingClause.config.noWait) {\n\t\t\t\tclauseSql.append(sql` no wait`);\n\t\t\t} else if (lockingClause.config.skipLocked) {\n\t\t\t\tclauseSql.append(sql` skip locked`);\n\t\t\t}\n\t\t\tlockingClauseSql.append(clauseSql);\n\t\t}\n\t\tconst finalQuery =\n\t\t\tsql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;\n\n\t\tif (setOperators.length > 0) {\n\t\t\treturn this.buildSetOperations(finalQuery, setOperators);\n\t\t}\n\n\t\treturn finalQuery;\n\t}\n\n\tbuildSetOperations(leftSelect: SQL, setOperators: PgSelectConfig['setOperators']): SQL {\n\t\tconst [setOperator, ...rest] = setOperators;\n\n\t\tif (!setOperator) {\n\t\t\tthrow new Error('Cannot pass undefined values to any set operator');\n\t\t}\n\n\t\tif (rest.length === 0) {\n\t\t\treturn this.buildSetOperationQuery({ leftSelect, setOperator });\n\t\t}\n\n\t\t// Some recursive magic here\n\t\treturn this.buildSetOperations(\n\t\t\tthis.buildSetOperationQuery({ leftSelect, setOperator }),\n\t\t\trest,\n\t\t);\n\t}\n\n\tbuildSetOperationQuery({\n\t\tleftSelect,\n\t\tsetOperator: { type, isAll, rightSelect, limit, orderBy, offset },\n\t}: { leftSelect: SQL; setOperator: PgSelectConfig['setOperators'][number] }): SQL {\n\t\tconst leftChunk = sql`(${leftSelect.getSQL()}) `;\n\t\tconst rightChunk = sql`(${rightSelect.getSQL()})`;\n\n\t\tlet orderBySql;\n\t\tif (orderBy && orderBy.length > 0) {\n\t\t\tconst orderByValues: (SQL | Name)[] = [];\n\n\t\t\t// The next bit is necessary because the sql operator replaces ${table.column} with `table`.`column`\n\t\t\t// which is invalid Sql syntax, Table from one of the SELECTs cannot be used in global ORDER clause\n\t\t\tfor (const singleOrderBy of orderBy) {\n\t\t\t\tif (is(singleOrderBy, PgColumn)) {\n\t\t\t\t\torderByValues.push(sql.identifier(singleOrderBy.name));\n\t\t\t\t} else if (is(singleOrderBy, SQL)) {\n\t\t\t\t\tfor (let i = 0; i < singleOrderBy.queryChunks.length; i++) {\n\t\t\t\t\t\tconst chunk = singleOrderBy.queryChunks[i];\n\n\t\t\t\t\t\tif (is(chunk, PgColumn)) {\n\t\t\t\t\t\t\tsingleOrderBy.queryChunks[i] = sql.identifier(chunk.name);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\torderByValues.push(sql`${singleOrderBy}`);\n\t\t\t\t} else {\n\t\t\t\t\torderByValues.push(sql`${singleOrderBy}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\torderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;\n\t\t}\n\n\t\tconst limitSql = typeof limit === 'object' || (typeof limit === 'number' && limit >= 0)\n\t\t\t? sql` limit ${limit}`\n\t\t\t: undefined;\n\n\t\tconst operatorChunk = sql.raw(`${type} ${isAll ? 'all ' : ''}`);\n\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : undefined;\n\n\t\treturn sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;\n\t}\n\n\tbuildInsertQuery({ table, values, onConflict, returning, withList }: PgInsertConfig): SQL {\n\t\tconst valuesSqlList: ((SQLChunk | SQL)[] | SQL)[] = [];\n\t\tconst columns: Record = table[Table.Symbol.Columns];\n\n\t\tconst colEntries: [string, PgColumn][] = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());\n\n\t\tconst insertOrder = colEntries.map(([, column]) => sql.identifier(column.name));\n\n\t\tfor (const [valueIndex, value] of values.entries()) {\n\t\t\tconst valueList: (SQLChunk | SQL)[] = [];\n\t\t\tfor (const [fieldName, col] of colEntries) {\n\t\t\t\tconst colValue = value[fieldName];\n\t\t\t\tif (colValue === undefined || (is(colValue, Param) && colValue.value === undefined)) {\n\t\t\t\t\t// eslint-disable-next-line unicorn/no-negated-condition\n\t\t\t\t\tif (col.defaultFn !== undefined) {\n\t\t\t\t\t\tconst defaultFnResult = col.defaultFn();\n\t\t\t\t\t\tconst defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);\n\t\t\t\t\t\tvalueList.push(defaultValue);\n\t\t\t\t\t\t// eslint-disable-next-line unicorn/no-negated-condition\n\t\t\t\t\t} else if (!col.default && col.onUpdateFn !== undefined) {\n\t\t\t\t\t\tconst onUpdateFnResult = col.onUpdateFn();\n\t\t\t\t\t\tconst newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);\n\t\t\t\t\t\tvalueList.push(newValue);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalueList.push(sql`default`);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvalueList.push(colValue);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvaluesSqlList.push(valueList);\n\t\t\tif (valueIndex < values.length - 1) {\n\t\t\t\tvaluesSqlList.push(sql`, `);\n\t\t\t}\n\t\t}\n\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst valuesSql = sql.join(valuesSqlList);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst onConflictSql = onConflict ? sql` on conflict ${onConflict}` : undefined;\n\n\t\treturn sql`${withSql}insert into ${table} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;\n\t}\n\n\tbuildRefreshMaterializedViewQuery(\n\t\t{ view, concurrently, withNoData }: { view: PgMaterializedView; concurrently?: boolean; withNoData?: boolean },\n\t): SQL {\n\t\tconst concurrentlySql = concurrently ? sql` concurrently` : undefined;\n\t\tconst withNoDataSql = withNoData ? sql` with no data` : undefined;\n\n\t\treturn sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`;\n\t}\n\n\tprepareTyping(encoder: DriverValueEncoder): QueryTypingsValue {\n\t\tif (is(encoder, PgJsonb) || is(encoder, PgJson)) {\n\t\t\treturn 'json';\n\t\t} else if (is(encoder, PgNumeric)) {\n\t\t\treturn 'decimal';\n\t\t} else if (is(encoder, PgTime)) {\n\t\t\treturn 'time';\n\t\t} else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {\n\t\t\treturn 'timestamp';\n\t\t} else if (is(encoder, PgDate) || is(encoder, PgDateString)) {\n\t\t\treturn 'date';\n\t\t} else if (is(encoder, PgUUID)) {\n\t\t\treturn 'uuid';\n\t\t} else {\n\t\t\treturn 'none';\n\t\t}\n\t}\n\n\tsqlToQuery(sql: SQL, invokeSource?: 'indexes' | undefined): QueryWithTypings {\n\t\treturn sql.toQuery({\n\t\t\tescapeName: this.escapeName,\n\t\t\tescapeParam: this.escapeParam,\n\t\t\tescapeString: this.escapeString,\n\t\t\tprepareTyping: this.prepareTyping,\n\t\t\tinvokeSource,\n\t\t});\n\t}\n\n\t// buildRelationalQueryWithPK({\n\t// \tfullSchema,\n\t// \tschema,\n\t// \ttableNamesMap,\n\t// \ttable,\n\t// \ttableConfig,\n\t// \tqueryConfig: config,\n\t// \ttableAlias,\n\t// \tisRoot = false,\n\t// \tjoinOn,\n\t// }: {\n\t// \tfullSchema: Record;\n\t// \tschema: TablesRelationalConfig;\n\t// \ttableNamesMap: Record;\n\t// \ttable: PgTable;\n\t// \ttableConfig: TableRelationalConfig;\n\t// \tqueryConfig: true | DBQueryConfig<'many', true>;\n\t// \ttableAlias: string;\n\t// \tisRoot?: boolean;\n\t// \tjoinOn?: SQL;\n\t// }): BuildRelationalQueryResult {\n\t// \t// For { \"\": true }, return a table with selection of all columns\n\t// \tif (config === true) {\n\t// \t\tconst selectionEntries = Object.entries(tableConfig.columns);\n\t// \t\tconst selection: BuildRelationalQueryResult['selection'] = selectionEntries.map((\n\t// \t\t\t[key, value],\n\t// \t\t) => ({\n\t// \t\t\tdbKey: value.name,\n\t// \t\t\ttsKey: key,\n\t// \t\t\tfield: value as PgColumn,\n\t// \t\t\trelationTableTsKey: undefined,\n\t// \t\t\tisJson: false,\n\t// \t\t\tselection: [],\n\t// \t\t}));\n\n\t// \t\treturn {\n\t// \t\t\ttableTsKey: tableConfig.tsName,\n\t// \t\t\tsql: table,\n\t// \t\t\tselection,\n\t// \t\t};\n\t// \t}\n\n\t// \t// let selection: BuildRelationalQueryResult['selection'] = [];\n\t// \t// let selectionForBuild = selection;\n\n\t// \tconst aliasedColumns = Object.fromEntries(\n\t// \t\tObject.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),\n\t// \t);\n\n\t// \tconst aliasedRelations = Object.fromEntries(\n\t// \t\tObject.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),\n\t// \t);\n\n\t// \tconst aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);\n\n\t// \tlet where, hasUserDefinedWhere;\n\t// \tif (config.where) {\n\t// \t\tconst whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;\n\t// \t\twhere = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);\n\t// \t\thasUserDefinedWhere = !!where;\n\t// \t}\n\t// \twhere = and(joinOn, where);\n\n\t// \t// const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = [];\n\t// \tlet joins: Join[] = [];\n\t// \tlet selectedColumns: string[] = [];\n\n\t// \t// Figure out which columns to select\n\t// \tif (config.columns) {\n\t// \t\tlet isIncludeMode = false;\n\n\t// \t\tfor (const [field, value] of Object.entries(config.columns)) {\n\t// \t\t\tif (value === undefined) {\n\t// \t\t\t\tcontinue;\n\t// \t\t\t}\n\n\t// \t\t\tif (field in tableConfig.columns) {\n\t// \t\t\t\tif (!isIncludeMode && value === true) {\n\t// \t\t\t\t\tisIncludeMode = true;\n\t// \t\t\t\t}\n\t// \t\t\t\tselectedColumns.push(field);\n\t// \t\t\t}\n\t// \t\t}\n\n\t// \t\tif (selectedColumns.length > 0) {\n\t// \t\t\tselectedColumns = isIncludeMode\n\t// \t\t\t\t? selectedColumns.filter((c) => config.columns?.[c] === true)\n\t// \t\t\t\t: Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));\n\t// \t\t}\n\t// \t} else {\n\t// \t\t// Select all columns if selection is not specified\n\t// \t\tselectedColumns = Object.keys(tableConfig.columns);\n\t// \t}\n\n\t// \t// for (const field of selectedColumns) {\n\t// \t// \tconst column = tableConfig.columns[field]! as PgColumn;\n\t// \t// \tfieldsSelection.push({ tsKey: field, value: column });\n\t// \t// }\n\n\t// \tlet initiallySelectedRelations: {\n\t// \t\ttsKey: string;\n\t// \t\tqueryConfig: true | DBQueryConfig<'many', false>;\n\t// \t\trelation: Relation;\n\t// \t}[] = [];\n\n\t// \t// let selectedRelations: BuildRelationalQueryResult['selection'] = [];\n\n\t// \t// Figure out which relations to select\n\t// \tif (config.with) {\n\t// \t\tinitiallySelectedRelations = Object.entries(config.with)\n\t// \t\t\t.filter((entry): entry is [typeof entry[0], NonNullable] => !!entry[1])\n\t// \t\t\t.map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));\n\t// \t}\n\n\t// \tconst manyRelations = initiallySelectedRelations.filter((r) =>\n\t// \t\tis(r.relation, Many)\n\t// \t\t&& (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0\n\t// \t);\n\t// \t// If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level\n\t// \tconst isInnermostQuery = manyRelations.length < 2;\n\n\t// \tconst selectedExtras: {\n\t// \t\ttsKey: string;\n\t// \t\tvalue: SQL.Aliased;\n\t// \t}[] = [];\n\n\t// \t// Figure out which extras to select\n\t// \tif (isInnermostQuery && config.extras) {\n\t// \t\tconst extras = typeof config.extras === 'function'\n\t// \t\t\t? config.extras(aliasedFields, { sql })\n\t// \t\t\t: config.extras;\n\t// \t\tfor (const [tsKey, value] of Object.entries(extras)) {\n\t// \t\t\tselectedExtras.push({\n\t// \t\t\t\ttsKey,\n\t// \t\t\t\tvalue: mapColumnsInAliasedSQLToAlias(value, tableAlias),\n\t// \t\t\t});\n\t// \t\t}\n\t// \t}\n\n\t// \t// Transform `fieldsSelection` into `selection`\n\t// \t// `fieldsSelection` shouldn't be used after this point\n\t// \t// for (const { tsKey, value, isExtra } of fieldsSelection) {\n\t// \t// \tselection.push({\n\t// \t// \t\tdbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,\n\t// \t// \t\ttsKey,\n\t// \t// \t\tfield: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,\n\t// \t// \t\trelationTableTsKey: undefined,\n\t// \t// \t\tisJson: false,\n\t// \t// \t\tisExtra,\n\t// \t// \t\tselection: [],\n\t// \t// \t});\n\t// \t// }\n\n\t// \tlet orderByOrig = typeof config.orderBy === 'function'\n\t// \t\t? config.orderBy(aliasedFields, orderByOperators)\n\t// \t\t: config.orderBy ?? [];\n\t// \tif (!Array.isArray(orderByOrig)) {\n\t// \t\torderByOrig = [orderByOrig];\n\t// \t}\n\t// \tconst orderBy = orderByOrig.map((orderByValue) => {\n\t// \t\tif (is(orderByValue, Column)) {\n\t// \t\t\treturn aliasedTableColumn(orderByValue, tableAlias) as PgColumn;\n\t// \t\t}\n\t// \t\treturn mapColumnsInSQLToAlias(orderByValue, tableAlias);\n\t// \t});\n\n\t// \tconst limit = isInnermostQuery ? config.limit : undefined;\n\t// \tconst offset = isInnermostQuery ? config.offset : undefined;\n\n\t// \t// For non-root queries without additional config except columns, return a table with selection\n\t// \tif (\n\t// \t\t!isRoot\n\t// \t\t&& initiallySelectedRelations.length === 0\n\t// \t\t&& selectedExtras.length === 0\n\t// \t\t&& !where\n\t// \t\t&& orderBy.length === 0\n\t// \t\t&& limit === undefined\n\t// \t\t&& offset === undefined\n\t// \t) {\n\t// \t\treturn {\n\t// \t\t\ttableTsKey: tableConfig.tsName,\n\t// \t\t\tsql: table,\n\t// \t\t\tselection: selectedColumns.map((key) => ({\n\t// \t\t\t\tdbKey: tableConfig.columns[key]!.name,\n\t// \t\t\t\ttsKey: key,\n\t// \t\t\t\tfield: tableConfig.columns[key] as PgColumn,\n\t// \t\t\t\trelationTableTsKey: undefined,\n\t// \t\t\t\tisJson: false,\n\t// \t\t\t\tselection: [],\n\t// \t\t\t})),\n\t// \t\t};\n\t// \t}\n\n\t// \tconst selectedRelationsWithoutPK:\n\n\t// \t// Process all relations without primary keys, because they need to be joined differently and will all be on the same query level\n\t// \tfor (\n\t// \t\tconst {\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tqueryConfig: selectedRelationConfigValue,\n\t// \t\t\trelation,\n\t// \t\t} of initiallySelectedRelations\n\t// \t) {\n\t// \t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t// \t\tconst relationTableName = relation.referencedTable[Table.Symbol.Name];\n\t// \t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t// \t\tconst relationTable = schema[relationTableTsName]!;\n\n\t// \t\tif (relationTable.primaryKey.length > 0) {\n\t// \t\t\tcontinue;\n\t// \t\t}\n\n\t// \t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t// \t\tconst joinOn = and(\n\t// \t\t\t...normalizedRelation.fields.map((field, i) =>\n\t// \t\t\t\teq(\n\t// \t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t// \t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t// \t\t\t\t)\n\t// \t\t\t),\n\t// \t\t);\n\t// \t\tconst builtRelation = this.buildRelationalQueryWithoutPK({\n\t// \t\t\tfullSchema,\n\t// \t\t\tschema,\n\t// \t\t\ttableNamesMap,\n\t// \t\t\ttable: fullSchema[relationTableTsName] as PgTable,\n\t// \t\t\ttableConfig: schema[relationTableTsName]!,\n\t// \t\t\tqueryConfig: selectedRelationConfigValue,\n\t// \t\t\ttableAlias: relationTableAlias,\n\t// \t\t\tjoinOn,\n\t// \t\t\tnestedQueryRelation: relation,\n\t// \t\t});\n\t// \t\tconst field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);\n\t// \t\tjoins.push({\n\t// \t\t\ton: sql`true`,\n\t// \t\t\ttable: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),\n\t// \t\t\talias: relationTableAlias,\n\t// \t\t\tjoinType: 'left',\n\t// \t\t\tlateral: true,\n\t// \t\t});\n\t// \t\tselectedRelations.push({\n\t// \t\t\tdbKey: selectedRelationTsKey,\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tfield,\n\t// \t\t\trelationTableTsKey: relationTableTsName,\n\t// \t\t\tisJson: true,\n\t// \t\t\tselection: builtRelation.selection,\n\t// \t\t});\n\t// \t}\n\n\t// \tconst oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>\n\t// \t\tis(r.relation, One)\n\t// \t);\n\n\t// \t// Process all One relations with PKs, because they can all be joined on the same level\n\t// \tfor (\n\t// \t\tconst {\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tqueryConfig: selectedRelationConfigValue,\n\t// \t\t\trelation,\n\t// \t\t} of oneRelations\n\t// \t) {\n\t// \t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t// \t\tconst relationTableName = relation.referencedTable[Table.Symbol.Name];\n\t// \t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t// \t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t// \t\tconst relationTable = schema[relationTableTsName]!;\n\n\t// \t\tif (relationTable.primaryKey.length === 0) {\n\t// \t\t\tcontinue;\n\t// \t\t}\n\n\t// \t\tconst joinOn = and(\n\t// \t\t\t...normalizedRelation.fields.map((field, i) =>\n\t// \t\t\t\teq(\n\t// \t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t// \t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t// \t\t\t\t)\n\t// \t\t\t),\n\t// \t\t);\n\t// \t\tconst builtRelation = this.buildRelationalQueryWithPK({\n\t// \t\t\tfullSchema,\n\t// \t\t\tschema,\n\t// \t\t\ttableNamesMap,\n\t// \t\t\ttable: fullSchema[relationTableTsName] as PgTable,\n\t// \t\t\ttableConfig: schema[relationTableTsName]!,\n\t// \t\t\tqueryConfig: selectedRelationConfigValue,\n\t// \t\t\ttableAlias: relationTableAlias,\n\t// \t\t\tjoinOn,\n\t// \t\t});\n\t// \t\tconst field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${\n\t// \t\t\tsql.join(\n\t// \t\t\t\tbuiltRelation.selection.map(({ field }) =>\n\t// \t\t\t\t\tis(field, SQL.Aliased)\n\t// \t\t\t\t\t\t? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`\n\t// \t\t\t\t\t\t: is(field, Column)\n\t// \t\t\t\t\t\t? aliasedTableColumn(field, relationTableAlias)\n\t// \t\t\t\t\t\t: field\n\t// \t\t\t\t),\n\t// \t\t\t\tsql`, `,\n\t// \t\t\t)\n\t// \t\t}) end`.as(selectedRelationTsKey);\n\t// \t\tconst isLateralJoin = is(builtRelation.sql, SQL);\n\t// \t\tjoins.push({\n\t// \t\t\ton: isLateralJoin ? sql`true` : joinOn,\n\t// \t\t\ttable: is(builtRelation.sql, SQL)\n\t// \t\t\t\t? new Subquery(builtRelation.sql, {}, relationTableAlias)\n\t// \t\t\t\t: aliasedTable(builtRelation.sql, relationTableAlias),\n\t// \t\t\talias: relationTableAlias,\n\t// \t\t\tjoinType: 'left',\n\t// \t\t\tlateral: is(builtRelation.sql, SQL),\n\t// \t\t});\n\t// \t\tselectedRelations.push({\n\t// \t\t\tdbKey: selectedRelationTsKey,\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tfield,\n\t// \t\t\trelationTableTsKey: relationTableTsName,\n\t// \t\t\tisJson: true,\n\t// \t\t\tselection: builtRelation.selection,\n\t// \t\t});\n\t// \t}\n\n\t// \tlet distinct: PgSelectConfig['distinct'];\n\t// \tlet tableFrom: PgTable | Subquery = table;\n\n\t// \t// Process first Many relation - each one requires a nested subquery\n\t// \tconst manyRelation = manyRelations[0];\n\t// \tif (manyRelation) {\n\t// \t\tconst {\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tqueryConfig: selectedRelationQueryConfig,\n\t// \t\t\trelation,\n\t// \t\t} = manyRelation;\n\n\t// \t\tdistinct = {\n\t// \t\t\ton: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)),\n\t// \t\t};\n\n\t// \t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t// \t\tconst relationTableName = relation.referencedTable[Table.Symbol.Name];\n\t// \t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t// \t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t// \t\tconst joinOn = and(\n\t// \t\t\t...normalizedRelation.fields.map((field, i) =>\n\t// \t\t\t\teq(\n\t// \t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t// \t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t// \t\t\t\t)\n\t// \t\t\t),\n\t// \t\t);\n\n\t// \t\tconst builtRelationJoin = this.buildRelationalQueryWithPK({\n\t// \t\t\tfullSchema,\n\t// \t\t\tschema,\n\t// \t\t\ttableNamesMap,\n\t// \t\t\ttable: fullSchema[relationTableTsName] as PgTable,\n\t// \t\t\ttableConfig: schema[relationTableTsName]!,\n\t// \t\t\tqueryConfig: selectedRelationQueryConfig,\n\t// \t\t\ttableAlias: relationTableAlias,\n\t// \t\t\tjoinOn,\n\t// \t\t});\n\n\t// \t\tconst builtRelationSelectionField = sql`case when ${\n\t// \t\t\tsql.identifier(relationTableAlias)\n\t// \t\t} is null then '[]' else json_agg(json_build_array(${\n\t// \t\t\tsql.join(\n\t// \t\t\t\tbuiltRelationJoin.selection.map(({ field }) =>\n\t// \t\t\t\t\tis(field, SQL.Aliased)\n\t// \t\t\t\t\t\t? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`\n\t// \t\t\t\t\t\t: is(field, Column)\n\t// \t\t\t\t\t\t? aliasedTableColumn(field, relationTableAlias)\n\t// \t\t\t\t\t\t: field\n\t// \t\t\t\t),\n\t// \t\t\t\tsql`, `,\n\t// \t\t\t)\n\t// \t\t})) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);\n\t// \t\tconst isLateralJoin = is(builtRelationJoin.sql, SQL);\n\t// \t\tjoins.push({\n\t// \t\t\ton: isLateralJoin ? sql`true` : joinOn,\n\t// \t\t\ttable: isLateralJoin\n\t// \t\t\t\t? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)\n\t// \t\t\t\t: aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias),\n\t// \t\t\talias: relationTableAlias,\n\t// \t\t\tjoinType: 'left',\n\t// \t\t\tlateral: isLateralJoin,\n\t// \t\t});\n\n\t// \t\t// Build the \"from\" subquery with the remaining Many relations\n\t// \t\tconst builtTableFrom = this.buildRelationalQueryWithPK({\n\t// \t\t\tfullSchema,\n\t// \t\t\tschema,\n\t// \t\t\ttableNamesMap,\n\t// \t\t\ttable,\n\t// \t\t\ttableConfig,\n\t// \t\t\tqueryConfig: {\n\t// \t\t\t\t...config,\n\t// \t\t\t\twhere: undefined,\n\t// \t\t\t\torderBy: undefined,\n\t// \t\t\t\tlimit: undefined,\n\t// \t\t\t\toffset: undefined,\n\t// \t\t\t\twith: manyRelations.slice(1).reduce>(\n\t// \t\t\t\t\t(result, { tsKey, queryConfig: configValue }) => {\n\t// \t\t\t\t\t\tresult[tsKey] = configValue;\n\t// \t\t\t\t\t\treturn result;\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\t{},\n\t// \t\t\t\t),\n\t// \t\t\t},\n\t// \t\t\ttableAlias,\n\t// \t\t});\n\n\t// \t\tselectedRelations.push({\n\t// \t\t\tdbKey: selectedRelationTsKey,\n\t// \t\t\ttsKey: selectedRelationTsKey,\n\t// \t\t\tfield: builtRelationSelectionField,\n\t// \t\t\trelationTableTsKey: relationTableTsName,\n\t// \t\t\tisJson: true,\n\t// \t\t\tselection: builtRelationJoin.selection,\n\t// \t\t});\n\n\t// \t\t// selection = builtTableFrom.selection.map((item) =>\n\t// \t\t// \tis(item.field, SQL.Aliased)\n\t// \t\t// \t\t? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }\n\t// \t\t// \t\t: item\n\t// \t\t// );\n\t// \t\t// selectionForBuild = [{\n\t// \t\t// \tdbKey: '*',\n\t// \t\t// \ttsKey: '*',\n\t// \t\t// \tfield: sql`${sql.identifier(tableAlias)}.*`,\n\t// \t\t// \tselection: [],\n\t// \t\t// \tisJson: false,\n\t// \t\t// \trelationTableTsKey: undefined,\n\t// \t\t// }];\n\t// \t\t// const newSelectionItem: (typeof selection)[number] = {\n\t// \t\t// \tdbKey: selectedRelationTsKey,\n\t// \t\t// \ttsKey: selectedRelationTsKey,\n\t// \t\t// \tfield,\n\t// \t\t// \trelationTableTsKey: relationTableTsName,\n\t// \t\t// \tisJson: true,\n\t// \t\t// \tselection: builtRelationJoin.selection,\n\t// \t\t// };\n\t// \t\t// selection.push(newSelectionItem);\n\t// \t\t// selectionForBuild.push(newSelectionItem);\n\n\t// \t\ttableFrom = is(builtTableFrom.sql, PgTable)\n\t// \t\t\t? builtTableFrom.sql\n\t// \t\t\t: new Subquery(builtTableFrom.sql, {}, tableAlias);\n\t// \t}\n\n\t// \tif (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {\n\t// \t\tthrow new DrizzleError(`No fields selected for table \"${tableConfig.tsName}\" (\"${tableAlias}\")`);\n\t// \t}\n\n\t// \tlet selection: BuildRelationalQueryResult['selection'];\n\n\t// \tfunction prepareSelectedColumns() {\n\t// \t\treturn selectedColumns.map((key) => ({\n\t// \t\t\tdbKey: tableConfig.columns[key]!.name,\n\t// \t\t\ttsKey: key,\n\t// \t\t\tfield: tableConfig.columns[key] as PgColumn,\n\t// \t\t\trelationTableTsKey: undefined,\n\t// \t\t\tisJson: false,\n\t// \t\t\tselection: [],\n\t// \t\t}));\n\t// \t}\n\n\t// \tfunction prepareSelectedExtras() {\n\t// \t\treturn selectedExtras.map((item) => ({\n\t// \t\t\tdbKey: item.value.fieldAlias,\n\t// \t\t\ttsKey: item.tsKey,\n\t// \t\t\tfield: item.value,\n\t// \t\t\trelationTableTsKey: undefined,\n\t// \t\t\tisJson: false,\n\t// \t\t\tselection: [],\n\t// \t\t}));\n\t// \t}\n\n\t// \tif (isRoot) {\n\t// \t\tselection = [\n\t// \t\t\t...prepareSelectedColumns(),\n\t// \t\t\t...prepareSelectedExtras(),\n\t// \t\t];\n\t// \t}\n\n\t// \tif (hasUserDefinedWhere || orderBy.length > 0) {\n\t// \t\ttableFrom = new Subquery(\n\t// \t\t\tthis.buildSelectQuery({\n\t// \t\t\t\ttable: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,\n\t// \t\t\t\tfields: {},\n\t// \t\t\t\tfieldsFlat: selectionForBuild.map(({ field }) => ({\n\t// \t\t\t\t\tpath: [],\n\t// \t\t\t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t// \t\t\t\t})),\n\t// \t\t\t\tjoins,\n\t// \t\t\t\tdistinct,\n\t// \t\t\t}),\n\t// \t\t\t{},\n\t// \t\t\ttableAlias,\n\t// \t\t);\n\t// \t\tselectionForBuild = selection.map((item) =>\n\t// \t\t\tis(item.field, SQL.Aliased)\n\t// \t\t\t\t? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }\n\t// \t\t\t\t: item\n\t// \t\t);\n\t// \t\tjoins = [];\n\t// \t\tdistinct = undefined;\n\t// \t}\n\n\t// \tconst result = this.buildSelectQuery({\n\t// \t\ttable: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,\n\t// \t\tfields: {},\n\t// \t\tfieldsFlat: selectionForBuild.map(({ field }) => ({\n\t// \t\t\tpath: [],\n\t// \t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t// \t\t})),\n\t// \t\twhere,\n\t// \t\tlimit,\n\t// \t\toffset,\n\t// \t\tjoins,\n\t// \t\torderBy,\n\t// \t\tdistinct,\n\t// \t});\n\n\t// \treturn {\n\t// \t\ttableTsKey: tableConfig.tsName,\n\t// \t\tsql: result,\n\t// \t\tselection,\n\t// \t};\n\t// }\n\n\tbuildRelationalQueryWithoutPK({\n\t\tfullSchema,\n\t\tschema,\n\t\ttableNamesMap,\n\t\ttable,\n\t\ttableConfig,\n\t\tqueryConfig: config,\n\t\ttableAlias,\n\t\tnestedQueryRelation,\n\t\tjoinOn,\n\t}: {\n\t\tfullSchema: Record;\n\t\tschema: TablesRelationalConfig;\n\t\ttableNamesMap: Record;\n\t\ttable: PgTable;\n\t\ttableConfig: TableRelationalConfig;\n\t\tqueryConfig: true | DBQueryConfig<'many', true>;\n\t\ttableAlias: string;\n\t\tnestedQueryRelation?: Relation;\n\t\tjoinOn?: SQL;\n\t}): BuildRelationalQueryResult {\n\t\tlet selection: BuildRelationalQueryResult['selection'] = [];\n\t\tlet limit, offset, orderBy: NonNullable = [], where;\n\t\tconst joins: PgSelectJoinConfig[] = [];\n\n\t\tif (config === true) {\n\t\t\tconst selectionEntries = Object.entries(tableConfig.columns);\n\t\t\tselection = selectionEntries.map((\n\t\t\t\t[key, value],\n\t\t\t) => ({\n\t\t\t\tdbKey: value.name,\n\t\t\t\ttsKey: key,\n\t\t\t\tfield: aliasedTableColumn(value as PgColumn, tableAlias),\n\t\t\t\trelationTableTsKey: undefined,\n\t\t\t\tisJson: false,\n\t\t\t\tselection: [],\n\t\t\t}));\n\t\t} else {\n\t\t\tconst aliasedColumns = Object.fromEntries(\n\t\t\t\tObject.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),\n\t\t\t);\n\n\t\t\tif (config.where) {\n\t\t\t\tconst whereSql = typeof config.where === 'function'\n\t\t\t\t\t? config.where(aliasedColumns, getOperators())\n\t\t\t\t\t: config.where;\n\t\t\t\twhere = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);\n\t\t\t}\n\n\t\t\tconst fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased }[] = [];\n\t\t\tlet selectedColumns: string[] = [];\n\n\t\t\t// Figure out which columns to select\n\t\t\tif (config.columns) {\n\t\t\t\tlet isIncludeMode = false;\n\n\t\t\t\tfor (const [field, value] of Object.entries(config.columns)) {\n\t\t\t\t\tif (value === undefined) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (field in tableConfig.columns) {\n\t\t\t\t\t\tif (!isIncludeMode && value === true) {\n\t\t\t\t\t\t\tisIncludeMode = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tselectedColumns.push(field);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (selectedColumns.length > 0) {\n\t\t\t\t\tselectedColumns = isIncludeMode\n\t\t\t\t\t\t? selectedColumns.filter((c) => config.columns?.[c] === true)\n\t\t\t\t\t\t: Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Select all columns if selection is not specified\n\t\t\t\tselectedColumns = Object.keys(tableConfig.columns);\n\t\t\t}\n\n\t\t\tfor (const field of selectedColumns) {\n\t\t\t\tconst column = tableConfig.columns[field]! as PgColumn;\n\t\t\t\tfieldsSelection.push({ tsKey: field, value: column });\n\t\t\t}\n\n\t\t\tlet selectedRelations: {\n\t\t\t\ttsKey: string;\n\t\t\t\tqueryConfig: true | DBQueryConfig<'many', false>;\n\t\t\t\trelation: Relation;\n\t\t\t}[] = [];\n\n\t\t\t// Figure out which relations to select\n\t\t\tif (config.with) {\n\t\t\t\tselectedRelations = Object.entries(config.with)\n\t\t\t\t\t.filter((entry): entry is [typeof entry[0], NonNullable] => !!entry[1])\n\t\t\t\t\t.map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));\n\t\t\t}\n\n\t\t\tlet extras;\n\n\t\t\t// Figure out which extras to select\n\t\t\tif (config.extras) {\n\t\t\t\textras = typeof config.extras === 'function'\n\t\t\t\t\t? config.extras(aliasedColumns, { sql })\n\t\t\t\t\t: config.extras;\n\t\t\t\tfor (const [tsKey, value] of Object.entries(extras)) {\n\t\t\t\t\tfieldsSelection.push({\n\t\t\t\t\t\ttsKey,\n\t\t\t\t\t\tvalue: mapColumnsInAliasedSQLToAlias(value, tableAlias),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Transform `fieldsSelection` into `selection`\n\t\t\t// `fieldsSelection` shouldn't be used after this point\n\t\t\tfor (const { tsKey, value } of fieldsSelection) {\n\t\t\t\tselection.push({\n\t\t\t\t\tdbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,\n\t\t\t\t\ttsKey,\n\t\t\t\t\tfield: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,\n\t\t\t\t\trelationTableTsKey: undefined,\n\t\t\t\t\tisJson: false,\n\t\t\t\t\tselection: [],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet orderByOrig = typeof config.orderBy === 'function'\n\t\t\t\t? config.orderBy(aliasedColumns, getOrderByOperators())\n\t\t\t\t: config.orderBy ?? [];\n\t\t\tif (!Array.isArray(orderByOrig)) {\n\t\t\t\torderByOrig = [orderByOrig];\n\t\t\t}\n\t\t\torderBy = orderByOrig.map((orderByValue) => {\n\t\t\t\tif (is(orderByValue, Column)) {\n\t\t\t\t\treturn aliasedTableColumn(orderByValue, tableAlias) as PgColumn;\n\t\t\t\t}\n\t\t\t\treturn mapColumnsInSQLToAlias(orderByValue, tableAlias);\n\t\t\t});\n\n\t\t\tlimit = config.limit;\n\t\t\toffset = config.offset;\n\n\t\t\t// Process all relations\n\t\t\tfor (\n\t\t\t\tconst {\n\t\t\t\t\ttsKey: selectedRelationTsKey,\n\t\t\t\t\tqueryConfig: selectedRelationConfigValue,\n\t\t\t\t\trelation,\n\t\t\t\t} of selectedRelations\n\t\t\t) {\n\t\t\t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t\t\t\tconst relationTableName = getTableUniqueName(relation.referencedTable);\n\t\t\t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t\t\t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t\t\t\tconst joinOn = and(\n\t\t\t\t\t...normalizedRelation.fields.map((field, i) =>\n\t\t\t\t\t\teq(\n\t\t\t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t\t\t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t\t\t\t\t\t)\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst builtRelation = this.buildRelationalQueryWithoutPK({\n\t\t\t\t\tfullSchema,\n\t\t\t\t\tschema,\n\t\t\t\t\ttableNamesMap,\n\t\t\t\t\ttable: fullSchema[relationTableTsName] as PgTable,\n\t\t\t\t\ttableConfig: schema[relationTableTsName]!,\n\t\t\t\t\tqueryConfig: is(relation, One)\n\t\t\t\t\t\t? (selectedRelationConfigValue === true\n\t\t\t\t\t\t\t? { limit: 1 }\n\t\t\t\t\t\t\t: { ...selectedRelationConfigValue, limit: 1 })\n\t\t\t\t\t\t: selectedRelationConfigValue,\n\t\t\t\t\ttableAlias: relationTableAlias,\n\t\t\t\t\tjoinOn,\n\t\t\t\t\tnestedQueryRelation: relation,\n\t\t\t\t});\n\t\t\t\tconst field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);\n\t\t\t\tjoins.push({\n\t\t\t\t\ton: sql`true`,\n\t\t\t\t\ttable: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),\n\t\t\t\t\talias: relationTableAlias,\n\t\t\t\t\tjoinType: 'left',\n\t\t\t\t\tlateral: true,\n\t\t\t\t});\n\t\t\t\tselection.push({\n\t\t\t\t\tdbKey: selectedRelationTsKey,\n\t\t\t\t\ttsKey: selectedRelationTsKey,\n\t\t\t\t\tfield,\n\t\t\t\t\trelationTableTsKey: relationTableTsName,\n\t\t\t\t\tisJson: true,\n\t\t\t\t\tselection: builtRelation.selection,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (selection.length === 0) {\n\t\t\tthrow new DrizzleError({ message: `No fields selected for table \"${tableConfig.tsName}\" (\"${tableAlias}\")` });\n\t\t}\n\n\t\tlet result;\n\n\t\twhere = and(joinOn, where);\n\n\t\tif (nestedQueryRelation) {\n\t\t\tlet field = sql`json_build_array(${\n\t\t\t\tsql.join(\n\t\t\t\t\tselection.map(({ field, tsKey, isJson }) =>\n\t\t\t\t\t\tisJson\n\t\t\t\t\t\t\t? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier('data')}`\n\t\t\t\t\t\t\t: is(field, SQL.Aliased)\n\t\t\t\t\t\t\t? field.sql\n\t\t\t\t\t\t\t: field\n\t\t\t\t\t),\n\t\t\t\t\tsql`, `,\n\t\t\t\t)\n\t\t\t})`;\n\t\t\tif (is(nestedQueryRelation, Many)) {\n\t\t\t\tfield = sql`coalesce(json_agg(${field}${\n\t\t\t\t\torderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : undefined\n\t\t\t\t}), '[]'::json)`;\n\t\t\t\t// orderBy = [];\n\t\t\t}\n\t\t\tconst nestedSelection = [{\n\t\t\t\tdbKey: 'data',\n\t\t\t\ttsKey: 'data',\n\t\t\t\tfield: field.as('data'),\n\t\t\t\tisJson: true,\n\t\t\t\trelationTableTsKey: tableConfig.tsName,\n\t\t\t\tselection,\n\t\t\t}];\n\n\t\t\tconst needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;\n\n\t\t\tif (needsSubquery) {\n\t\t\t\tresult = this.buildSelectQuery({\n\t\t\t\t\ttable: aliasedTable(table, tableAlias),\n\t\t\t\t\tfields: {},\n\t\t\t\t\tfieldsFlat: [{\n\t\t\t\t\t\tpath: [],\n\t\t\t\t\t\tfield: sql.raw('*'),\n\t\t\t\t\t}],\n\t\t\t\t\twhere,\n\t\t\t\t\tlimit,\n\t\t\t\t\toffset,\n\t\t\t\t\torderBy,\n\t\t\t\t\tsetOperators: [],\n\t\t\t\t});\n\n\t\t\t\twhere = undefined;\n\t\t\t\tlimit = undefined;\n\t\t\t\toffset = undefined;\n\t\t\t\torderBy = [];\n\t\t\t} else {\n\t\t\t\tresult = aliasedTable(table, tableAlias);\n\t\t\t}\n\n\t\t\tresult = this.buildSelectQuery({\n\t\t\t\ttable: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),\n\t\t\t\tfields: {},\n\t\t\t\tfieldsFlat: nestedSelection.map(({ field }) => ({\n\t\t\t\t\tpath: [],\n\t\t\t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t\t\t\t})),\n\t\t\t\tjoins,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\torderBy,\n\t\t\t\tsetOperators: [],\n\t\t\t});\n\t\t} else {\n\t\t\tresult = this.buildSelectQuery({\n\t\t\t\ttable: aliasedTable(table, tableAlias),\n\t\t\t\tfields: {},\n\t\t\t\tfieldsFlat: selection.map(({ field }) => ({\n\t\t\t\t\tpath: [],\n\t\t\t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t\t\t\t})),\n\t\t\t\tjoins,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\torderBy,\n\t\t\t\tsetOperators: [],\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\ttableTsKey: tableConfig.tsName,\n\t\t\tsql: result,\n\t\t\tselection,\n\t\t};\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { type ColumnsSelection, View } from '~/sql/sql.ts';\n\nexport abstract class PgViewBase<\n\tTName extends string = string,\n\tTExisting extends boolean = boolean,\n\tTSelectedFields extends ColumnsSelection = ColumnsSelection,\n> extends View {\n\tstatic readonly [entityKind]: string = 'PgViewBase';\n\n\tdeclare readonly _: View['_'] & {\n\t\treadonly viewBrand: 'PgViewBase';\n\t};\n}\n", "import { ColumnAliasProxyHandler, TableAliasProxyHandler } from './alias.ts';\nimport { Column } from './column.ts';\nimport { entityKind, is } from './entity.ts';\nimport { SQL, View } from './sql/sql.ts';\nimport { Subquery } from './subquery.ts';\nimport { ViewBaseConfig } from './view-common.ts';\n\nexport class SelectionProxyHandler | View>\n\timplements ProxyHandler | View>\n{\n\tstatic readonly [entityKind]: string = 'SelectionProxyHandler';\n\n\tprivate config: {\n\t\t/**\n\t\t * Table alias for the columns\n\t\t */\n\t\talias?: string;\n\t\t/**\n\t\t * What to do when a field is an instance of `SQL.Aliased` and it's not a selection field (from a subquery)\n\t\t *\n\t\t * `sql` - return the underlying SQL expression\n\t\t *\n\t\t * `alias` - return the field alias\n\t\t */\n\t\tsqlAliasedBehavior: 'sql' | 'alias';\n\t\t/**\n\t\t * What to do when a field is an instance of `SQL` and it doesn't have an alias declared\n\t\t *\n\t\t * `sql` - return the underlying SQL expression\n\t\t *\n\t\t * `error` - return a DrizzleTypeError on type level and throw an error on runtime\n\t\t */\n\t\tsqlBehavior: 'sql' | 'error';\n\n\t\t/**\n\t\t * Whether to replace the original name of the column with the alias\n\t\t * Should be set to `true` for views creation\n\t\t * @default false\n\t\t */\n\t\treplaceOriginalName?: boolean;\n\t};\n\n\tconstructor(config: SelectionProxyHandler['config']) {\n\t\tthis.config = { ...config };\n\t}\n\n\tget(subquery: T, prop: string | symbol): any {\n\t\tif (prop === '_') {\n\t\t\treturn {\n\t\t\t\t...subquery['_' as keyof typeof subquery],\n\t\t\t\tselectedFields: new Proxy(\n\t\t\t\t\t(subquery as Subquery)._.selectedFields,\n\t\t\t\t\tthis as ProxyHandler>,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\n\t\tif (prop === ViewBaseConfig) {\n\t\t\treturn {\n\t\t\t\t...subquery[ViewBaseConfig as keyof typeof subquery],\n\t\t\t\tselectedFields: new Proxy(\n\t\t\t\t\t(subquery as View)[ViewBaseConfig].selectedFields,\n\t\t\t\t\tthis as ProxyHandler>,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\n\t\tif (typeof prop === 'symbol') {\n\t\t\treturn subquery[prop as keyof typeof subquery];\n\t\t}\n\n\t\tconst columns = is(subquery, Subquery)\n\t\t\t? subquery._.selectedFields\n\t\t\t: is(subquery, View)\n\t\t\t? subquery[ViewBaseConfig].selectedFields\n\t\t\t: subquery;\n\t\tconst value: unknown = columns[prop as keyof typeof columns];\n\n\t\tif (is(value, SQL.Aliased)) {\n\t\t\t// Never return the underlying SQL expression for a field previously selected in a subquery\n\t\t\tif (this.config.sqlAliasedBehavior === 'sql' && !value.isSelectionField) {\n\t\t\t\treturn value.sql;\n\t\t\t}\n\n\t\t\tconst newValue = value.clone();\n\t\t\tnewValue.isSelectionField = true;\n\t\t\treturn newValue;\n\t\t}\n\n\t\tif (is(value, SQL)) {\n\t\t\tif (this.config.sqlBehavior === 'sql') {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tthrow new Error(\n\t\t\t\t`You tried to reference \"${prop}\" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using \".as('alias')\" method.`,\n\t\t\t);\n\t\t}\n\n\t\tif (is(value, Column)) {\n\t\t\tif (this.config.alias) {\n\t\t\t\treturn new Proxy(\n\t\t\t\t\tvalue,\n\t\t\t\t\tnew ColumnAliasProxyHandler(\n\t\t\t\t\t\tnew Proxy(\n\t\t\t\t\t\t\tvalue.table,\n\t\t\t\t\t\t\tnew TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n\t\tif (typeof value !== 'object' || value === null) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn new Proxy(value, new SelectionProxyHandler(this.config));\n\t}\n}\n", "import { entityKind, is } from '~/entity.ts';\nimport type { PgColumn } from '~/pg-core/columns/index.ts';\nimport type { PgDialect } from '~/pg-core/dialect.ts';\nimport type { PgSession, PreparedQueryConfig } from '~/pg-core/session.ts';\nimport type { SubqueryWithSelection } from '~/pg-core/subquery.ts';\nimport type { PgTable } from '~/pg-core/table.ts';\nimport { PgViewBase } from '~/pg-core/view-base.ts';\nimport { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport type {\n\tBuildSubquerySelection,\n\tGetSelectTableName,\n\tGetSelectTableSelection,\n\tJoinNullability,\n\tJoinType,\n\tSelectMode,\n\tSelectResult,\n\tSetOperator,\n} from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport { SQL, View } from '~/sql/sql.ts';\nimport type { ColumnsSelection, Placeholder, Query, SQLWrapper } from '~/sql/sql.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport { tracer } from '~/tracing.ts';\nimport { applyMixins, getTableColumns, getTableLikeName, haveSameKeys, type ValueOrArray } from '~/utils.ts';\nimport { orderSelectedFields } from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type {\n\tAnyPgSelect,\n\tCreatePgSelectFromBuilderMode,\n\tGetPgSetOperators,\n\tLockConfig,\n\tLockStrength,\n\tPgCreateSetOperatorFn,\n\tPgJoinFn,\n\tPgSelectConfig,\n\tPgSelectDynamic,\n\tPgSelectHKT,\n\tPgSelectHKTBase,\n\tPgSelectPrepare,\n\tPgSelectWithout,\n\tPgSetOperatorExcludedMethods,\n\tPgSetOperatorWithResult,\n\tSelectedFields,\n\tSetOperatorRightSelect,\n} from './select.types.ts';\n\nexport class PgSelectBuilder<\n\tTSelection extends SelectedFields | undefined,\n\tTBuilderMode extends 'db' | 'qb' = 'db',\n> {\n\tstatic readonly [entityKind]: string = 'PgSelectBuilder';\n\n\tprivate fields: TSelection;\n\tprivate session: PgSession | undefined;\n\tprivate dialect: PgDialect;\n\tprivate withList: Subquery[] = [];\n\tprivate distinct: boolean | {\n\t\ton: (PgColumn | SQLWrapper)[];\n\t} | undefined;\n\n\tconstructor(\n\t\tconfig: {\n\t\t\tfields: TSelection;\n\t\t\tsession: PgSession | undefined;\n\t\t\tdialect: PgDialect;\n\t\t\twithList?: Subquery[];\n\t\t\tdistinct?: boolean | {\n\t\t\t\ton: (PgColumn | SQLWrapper)[];\n\t\t\t};\n\t\t},\n\t) {\n\t\tthis.fields = config.fields;\n\t\tthis.session = config.session;\n\t\tthis.dialect = config.dialect;\n\t\tif (config.withList) {\n\t\t\tthis.withList = config.withList;\n\t\t}\n\t\tthis.distinct = config.distinct;\n\t}\n\n\t/**\n\t * Specify the table, subquery, or other target that you're\n\t * building a select query against.\n\t *\n\t * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}\n\t */\n\tfrom(\n\t\tsource: TFrom,\n\t): CreatePgSelectFromBuilderMode<\n\t\tTBuilderMode,\n\t\tGetSelectTableName,\n\t\tTSelection extends undefined ? GetSelectTableSelection : TSelection,\n\t\tTSelection extends undefined ? 'single' : 'partial'\n\t> {\n\t\tconst isPartialSelect = !!this.fields;\n\n\t\tlet fields: SelectedFields;\n\t\tif (this.fields) {\n\t\t\tfields = this.fields;\n\t\t} else if (is(source, Subquery)) {\n\t\t\t// This is required to use the proxy handler to get the correct field values from the subquery\n\t\t\tfields = Object.fromEntries(\n\t\t\t\tObject.keys(source._.selectedFields).map((\n\t\t\t\t\tkey,\n\t\t\t\t) => [key, source[key as unknown as keyof typeof source] as unknown as SelectedFields[string]]),\n\t\t\t);\n\t\t} else if (is(source, PgViewBase)) {\n\t\t\tfields = source[ViewBaseConfig].selectedFields as SelectedFields;\n\t\t} else if (is(source, SQL)) {\n\t\t\tfields = {};\n\t\t} else {\n\t\t\tfields = getTableColumns(source);\n\t\t}\n\n\t\treturn new PgSelectBase({\n\t\t\ttable: source,\n\t\t\tfields,\n\t\t\tisPartialSelect,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\twithList: this.withList,\n\t\t\tdistinct: this.distinct,\n\t\t}) as any;\n\t}\n}\n\nexport abstract class PgSelectQueryBuilderBase<\n\tTHKT extends PgSelectHKTBase,\n\tTTableName extends string | undefined,\n\tTSelection extends ColumnsSelection,\n\tTSelectMode extends SelectMode,\n\tTNullabilityMap extends Record = TTableName extends string ? Record\n\t\t: {},\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n\tTResult extends any[] = SelectResult[],\n\tTSelectedFields extends ColumnsSelection = BuildSubquerySelection,\n> extends TypedQueryBuilder {\n\tstatic readonly [entityKind]: string = 'PgSelectQueryBuilder';\n\n\toverride readonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly hkt: THKT;\n\t\treadonly tableName: TTableName;\n\t\treadonly selection: TSelection;\n\t\treadonly selectMode: TSelectMode;\n\t\treadonly nullabilityMap: TNullabilityMap;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TResult;\n\t\treadonly selectedFields: TSelectedFields;\n\t};\n\n\tprotected config: PgSelectConfig;\n\tprotected joinsNotNullableMap: Record;\n\tprivate tableName: string | undefined;\n\tprivate isPartialSelect: boolean;\n\tprotected session: PgSession | undefined;\n\tprotected dialect: PgDialect;\n\n\tconstructor(\n\t\t{ table, fields, isPartialSelect, session, dialect, withList, distinct }: {\n\t\t\ttable: PgSelectConfig['table'];\n\t\t\tfields: PgSelectConfig['fields'];\n\t\t\tisPartialSelect: boolean;\n\t\t\tsession: PgSession | undefined;\n\t\t\tdialect: PgDialect;\n\t\t\twithList: Subquery[];\n\t\t\tdistinct: boolean | {\n\t\t\t\ton: (PgColumn | SQLWrapper)[];\n\t\t\t} | undefined;\n\t\t},\n\t) {\n\t\tsuper();\n\t\tthis.config = {\n\t\t\twithList,\n\t\t\ttable,\n\t\t\tfields: { ...fields },\n\t\t\tdistinct,\n\t\t\tsetOperators: [],\n\t\t};\n\t\tthis.isPartialSelect = isPartialSelect;\n\t\tthis.session = session;\n\t\tthis.dialect = dialect;\n\t\tthis._ = {\n\t\t\tselectedFields: fields as TSelectedFields,\n\t\t} as this['_'];\n\t\tthis.tableName = getTableLikeName(table);\n\t\tthis.joinsNotNullableMap = typeof this.tableName === 'string' ? { [this.tableName]: true } : {};\n\t}\n\n\tprivate createJoin(\n\t\tjoinType: TJoinType,\n\t): PgJoinFn {\n\t\treturn (\n\t\t\ttable: PgTable | Subquery | PgViewBase | SQL,\n\t\t\ton: ((aliases: TSelection) => SQL | undefined) | SQL | undefined,\n\t\t) => {\n\t\t\tconst baseTableName = this.tableName;\n\t\t\tconst tableName = getTableLikeName(table);\n\n\t\t\tif (typeof tableName === 'string' && this.config.joins?.some((join) => join.alias === tableName)) {\n\t\t\t\tthrow new Error(`Alias \"${tableName}\" is already used in this query`);\n\t\t\t}\n\n\t\t\tif (!this.isPartialSelect) {\n\t\t\t\t// If this is the first join and this is not a partial select and we're not selecting from raw SQL, \"move\" the fields from the main table to the nested object\n\t\t\t\tif (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === 'string') {\n\t\t\t\t\tthis.config.fields = {\n\t\t\t\t\t\t[baseTableName]: this.config.fields,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (typeof tableName === 'string' && !is(table, SQL)) {\n\t\t\t\t\tconst selection = is(table, Subquery)\n\t\t\t\t\t\t? table._.selectedFields\n\t\t\t\t\t\t: is(table, View)\n\t\t\t\t\t\t? table[ViewBaseConfig].selectedFields\n\t\t\t\t\t\t: table[Table.Symbol.Columns];\n\t\t\t\t\tthis.config.fields[tableName] = selection;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (typeof on === 'function') {\n\t\t\t\ton = on(\n\t\t\t\t\tnew Proxy(\n\t\t\t\t\t\tthis.config.fields,\n\t\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t\t) as TSelection,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!this.config.joins) {\n\t\t\t\tthis.config.joins = [];\n\t\t\t}\n\n\t\t\tthis.config.joins.push({ on, table, joinType, alias: tableName });\n\n\t\t\tif (typeof tableName === 'string') {\n\t\t\t\tswitch (joinType) {\n\t\t\t\t\tcase 'left': {\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'right': {\n\t\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(this.joinsNotNullableMap).map(([key]) => [key, false]),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'inner': {\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'full': {\n\t\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(this.joinsNotNullableMap).map(([key]) => [key, false]),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this as any;\n\t\t};\n\t}\n\n\t/**\n\t * Executes a `left join` operation by adding another table to the current query.\n\t *\n\t * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()\n\t * .from(users)\n\t * .leftJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .leftJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\tleftJoin = this.createJoin('left');\n\n\t/**\n\t * Executes a `right join` operation by adding another table to the current query.\n\t *\n\t * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()\n\t * .from(users)\n\t * .rightJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .rightJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\trightJoin = this.createJoin('right');\n\n\t/**\n\t * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.\n\t *\n\t * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User; pets: Pet }[] = await db.select()\n\t * .from(users)\n\t * .innerJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .innerJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\tinnerJoin = this.createJoin('inner');\n\n\t/**\n\t * Executes a `full join` operation by combining rows from two tables into a new table.\n\t *\n\t * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()\n\t * .from(users)\n\t * .fullJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .fullJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\tfullJoin = this.createJoin('full');\n\n\tprivate createSetOperator(\n\t\ttype: SetOperator,\n\t\tisAll: boolean,\n\t): >(\n\t\trightSelection:\n\t\t\t| ((setOperators: GetPgSetOperators) => SetOperatorRightSelect)\n\t\t\t| SetOperatorRightSelect,\n\t) => PgSelectWithout<\n\t\tthis,\n\t\tTDynamic,\n\t\tPgSetOperatorExcludedMethods,\n\t\ttrue\n\t> {\n\t\treturn (rightSelection) => {\n\t\t\tconst rightSelect = (typeof rightSelection === 'function'\n\t\t\t\t? rightSelection(getPgSetOperators())\n\t\t\t\t: rightSelection) as TypedQueryBuilder<\n\t\t\t\t\tany,\n\t\t\t\t\tTResult\n\t\t\t\t>;\n\n\t\t\tif (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Set operator error (union / intersect / except): selected fields are not the same or are in a different order',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.config.setOperators.push({ type, isAll, rightSelect });\n\t\t\treturn this as any;\n\t\t};\n\t}\n\n\t/**\n\t * Adds `union` set operator to the query.\n\t *\n\t * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all unique names from customers and users tables\n\t * await db.select({ name: users.name })\n\t * .from(users)\n\t * .union(\n\t * db.select({ name: customers.name }).from(customers)\n\t * );\n\t * // or\n\t * import { union } from 'drizzle-orm/pg-core'\n\t *\n\t * await union(\n\t * db.select({ name: users.name }).from(users),\n\t * db.select({ name: customers.name }).from(customers)\n\t * );\n\t * ```\n\t */\n\tunion = this.createSetOperator('union', false);\n\n\t/**\n\t * Adds `union all` set operator to the query.\n\t *\n\t * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all transaction ids from both online and in-store sales\n\t * await db.select({ transaction: onlineSales.transactionId })\n\t * .from(onlineSales)\n\t * .unionAll(\n\t * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n\t * );\n\t * // or\n\t * import { unionAll } from 'drizzle-orm/pg-core'\n\t *\n\t * await unionAll(\n\t * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),\n\t * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n\t * );\n\t * ```\n\t */\n\tunionAll = this.createSetOperator('union', true);\n\n\t/**\n\t * Adds `intersect` set operator to the query.\n\t *\n\t * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select course names that are offered in both departments A and B\n\t * await db.select({ courseName: depA.courseName })\n\t * .from(depA)\n\t * .intersect(\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * // or\n\t * import { intersect } from 'drizzle-orm/pg-core'\n\t *\n\t * await intersect(\n\t * db.select({ courseName: depA.courseName }).from(depA),\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * ```\n\t */\n\tintersect = this.createSetOperator('intersect', false);\n\n\t/**\n\t * Adds `intersect all` set operator to the query.\n\t *\n\t * Calling this method will retain only the rows that are present in both result sets including all duplicates.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all products and quantities that are ordered by both regular and VIP customers\n\t * await db.select({\n\t * productId: regularCustomerOrders.productId,\n\t * quantityOrdered: regularCustomerOrders.quantityOrdered\n\t * })\n\t * .from(regularCustomerOrders)\n\t * .intersectAll(\n\t * db.select({\n\t * productId: vipCustomerOrders.productId,\n\t * quantityOrdered: vipCustomerOrders.quantityOrdered\n\t * })\n\t * .from(vipCustomerOrders)\n\t * );\n\t * // or\n\t * import { intersectAll } from 'drizzle-orm/pg-core'\n\t *\n\t * await intersectAll(\n\t * db.select({\n\t * productId: regularCustomerOrders.productId,\n\t * quantityOrdered: regularCustomerOrders.quantityOrdered\n\t * })\n\t * .from(regularCustomerOrders),\n\t * db.select({\n\t * productId: vipCustomerOrders.productId,\n\t * quantityOrdered: vipCustomerOrders.quantityOrdered\n\t * })\n\t * .from(vipCustomerOrders)\n\t * );\n\t * ```\n\t */\n\tintersectAll = this.createSetOperator('intersect', true);\n\n\t/**\n\t * Adds `except` set operator to the query.\n\t *\n\t * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all courses offered in department A but not in department B\n\t * await db.select({ courseName: depA.courseName })\n\t * .from(depA)\n\t * .except(\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * // or\n\t * import { except } from 'drizzle-orm/pg-core'\n\t *\n\t * await except(\n\t * db.select({ courseName: depA.courseName }).from(depA),\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * ```\n\t */\n\texcept = this.createSetOperator('except', false);\n\n\t/**\n\t * Adds `except all` set operator to the query.\n\t *\n\t * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all products that are ordered by regular customers but not by VIP customers\n\t * await db.select({\n\t * productId: regularCustomerOrders.productId,\n\t * quantityOrdered: regularCustomerOrders.quantityOrdered,\n\t * })\n\t * .from(regularCustomerOrders)\n\t * .exceptAll(\n\t * db.select({\n\t * productId: vipCustomerOrders.productId,\n\t * quantityOrdered: vipCustomerOrders.quantityOrdered,\n\t * })\n\t * .from(vipCustomerOrders)\n\t * );\n\t * // or\n\t * import { exceptAll } from 'drizzle-orm/pg-core'\n\t *\n\t * await exceptAll(\n\t * db.select({\n\t * productId: regularCustomerOrders.productId,\n\t * quantityOrdered: regularCustomerOrders.quantityOrdered\n\t * })\n\t * .from(regularCustomerOrders),\n\t * db.select({\n\t * productId: vipCustomerOrders.productId,\n\t * quantityOrdered: vipCustomerOrders.quantityOrdered\n\t * })\n\t * .from(vipCustomerOrders)\n\t * );\n\t * ```\n\t */\n\texceptAll = this.createSetOperator('except', true);\n\n\t/** @internal */\n\taddSetOperators(setOperators: PgSelectConfig['setOperators']): PgSelectWithout<\n\t\tthis,\n\t\tTDynamic,\n\t\tPgSetOperatorExcludedMethods,\n\t\ttrue\n\t> {\n\t\tthis.config.setOperators.push(...setOperators);\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `where` clause to the query.\n\t *\n\t * Calling this method will select only those rows that fulfill a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#filtering}\n\t *\n\t * @param where the `where` clause.\n\t *\n\t * @example\n\t * You can use conditional operators and `sql function` to filter the rows to be selected.\n\t *\n\t * ```ts\n\t * // Select all cars with green color\n\t * await db.select().from(cars).where(eq(cars.color, 'green'));\n\t * // or\n\t * await db.select().from(cars).where(sql`${cars.color} = 'green'`)\n\t * ```\n\t *\n\t * You can logically combine conditional operators with `and()` and `or()` operators:\n\t *\n\t * ```ts\n\t * // Select all BMW cars with a green color\n\t * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t *\n\t * // Select all cars with the green or blue color\n\t * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t * ```\n\t */\n\twhere(\n\t\twhere: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined,\n\t): PgSelectWithout {\n\t\tif (typeof where === 'function') {\n\t\t\twhere = where(\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\t\t}\n\t\tthis.config.where = where;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `having` clause to the query.\n\t *\n\t * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}\n\t *\n\t * @param having the `having` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all brands with more than one car\n\t * await db.select({\n\t * \tbrand: cars.brand,\n\t * \tcount: sql`cast(count(${cars.id}) as int)`,\n\t * })\n\t * .from(cars)\n\t * .groupBy(cars.brand)\n\t * .having(({ count }) => gt(count, 1));\n\t * ```\n\t */\n\thaving(\n\t\thaving: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined,\n\t): PgSelectWithout {\n\t\tif (typeof having === 'function') {\n\t\t\thaving = having(\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\t\t}\n\t\tthis.config.having = having;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `group by` clause to the query.\n\t *\n\t * Calling this method will group rows that have the same values into summary rows, often used for aggregation purposes.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Group and count people by their last names\n\t * await db.select({\n\t * lastName: people.lastName,\n\t * count: sql`cast(count(*) as int)`\n\t * })\n\t * .from(people)\n\t * .groupBy(people.lastName);\n\t * ```\n\t */\n\tgroupBy(\n\t\tbuilder: (aliases: this['_']['selection']) => ValueOrArray,\n\t): PgSelectWithout;\n\tgroupBy(...columns: (PgColumn | SQL | SQL.Aliased)[]): PgSelectWithout;\n\tgroupBy(\n\t\t...columns:\n\t\t\t| [(aliases: this['_']['selection']) => ValueOrArray]\n\t\t\t| (PgColumn | SQL | SQL.Aliased)[]\n\t): PgSelectWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst groupBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\t\t\tthis.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];\n\t\t} else {\n\t\t\tthis.config.groupBy = columns as (PgColumn | SQL | SQL.Aliased)[];\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `order by` clause to the query.\n\t *\n\t * Calling this method will sort the result-set in ascending or descending order. By default, the sort order is ascending.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#order-by}\n\t *\n\t * @example\n\t *\n\t * ```\n\t * // Select cars ordered by year\n\t * await db.select().from(cars).orderBy(cars.year);\n\t * ```\n\t *\n\t * You can specify whether results are in ascending or descending order with the `asc()` and `desc()` operators.\n\t *\n\t * ```ts\n\t * // Select cars ordered by year in descending order\n\t * await db.select().from(cars).orderBy(desc(cars.year));\n\t *\n\t * // Select cars ordered by year and price\n\t * await db.select().from(cars).orderBy(asc(cars.year), desc(cars.price));\n\t * ```\n\t */\n\torderBy(\n\t\tbuilder: (aliases: this['_']['selection']) => ValueOrArray,\n\t): PgSelectWithout;\n\torderBy(...columns: (PgColumn | SQL | SQL.Aliased)[]): PgSelectWithout;\n\torderBy(\n\t\t...columns:\n\t\t\t| [(aliases: this['_']['selection']) => ValueOrArray]\n\t\t\t| (PgColumn | SQL | SQL.Aliased)[]\n\t): PgSelectWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst orderBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\n\t\t\tconst orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];\n\n\t\t\tif (this.config.setOperators.length > 0) {\n\t\t\t\tthis.config.setOperators.at(-1)!.orderBy = orderByArray;\n\t\t\t} else {\n\t\t\t\tthis.config.orderBy = orderByArray;\n\t\t\t}\n\t\t} else {\n\t\t\tconst orderByArray = columns as (PgColumn | SQL | SQL.Aliased)[];\n\n\t\t\tif (this.config.setOperators.length > 0) {\n\t\t\t\tthis.config.setOperators.at(-1)!.orderBy = orderByArray;\n\t\t\t} else {\n\t\t\t\tthis.config.orderBy = orderByArray;\n\t\t\t}\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `limit` clause to the query.\n\t *\n\t * Calling this method will set the maximum number of rows that will be returned by this query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}\n\t *\n\t * @param limit the `limit` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Get the first 10 people from this query.\n\t * await db.select().from(people).limit(10);\n\t * ```\n\t */\n\tlimit(limit: number | Placeholder): PgSelectWithout {\n\t\tif (this.config.setOperators.length > 0) {\n\t\t\tthis.config.setOperators.at(-1)!.limit = limit;\n\t\t} else {\n\t\t\tthis.config.limit = limit;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `offset` clause to the query.\n\t *\n\t * Calling this method will skip a number of rows when returning results from this query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}\n\t *\n\t * @param offset the `offset` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Get the 10th-20th people from this query.\n\t * await db.select().from(people).offset(10).limit(10);\n\t * ```\n\t */\n\toffset(offset: number | Placeholder): PgSelectWithout {\n\t\tif (this.config.setOperators.length > 0) {\n\t\t\tthis.config.setOperators.at(-1)!.offset = offset;\n\t\t} else {\n\t\t\tthis.config.offset = offset;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `for` clause to the query.\n\t *\n\t * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.\n\t *\n\t * See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}\n\t *\n\t * @param strength the lock strength.\n\t * @param config the lock configuration.\n\t */\n\tfor(strength: LockStrength, config: LockConfig = {}): PgSelectWithout {\n\t\tthis.config.lockingClause = { strength, config };\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildSelectQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\tas(\n\t\talias: TAlias,\n\t): SubqueryWithSelection {\n\t\treturn new Proxy(\n\t\t\tnew Subquery(this.getSQL(), this.config.fields, alias),\n\t\t\tnew SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t) as SubqueryWithSelection;\n\t}\n\n\t/** @internal */\n\toverride getSelectedFields(): this['_']['selectedFields'] {\n\t\treturn new Proxy(\n\t\t\tthis.config.fields,\n\t\t\tnew SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t) as this['_']['selectedFields'];\n\t}\n\n\t$dynamic(): PgSelectDynamic {\n\t\treturn this;\n\t}\n}\n\nexport interface PgSelectBase<\n\tTTableName extends string | undefined,\n\tTSelection extends ColumnsSelection,\n\tTSelectMode extends SelectMode,\n\tTNullabilityMap extends Record = TTableName extends string ? Record\n\t\t: {},\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n\tTResult extends any[] = SelectResult[],\n\tTSelectedFields extends ColumnsSelection = BuildSubquerySelection,\n> extends\n\tPgSelectQueryBuilderBase<\n\t\tPgSelectHKT,\n\t\tTTableName,\n\t\tTSelection,\n\t\tTSelectMode,\n\t\tTNullabilityMap,\n\t\tTDynamic,\n\t\tTExcludedMethods,\n\t\tTResult,\n\t\tTSelectedFields\n\t>,\n\tQueryPromise,\n\tSQLWrapper\n{}\n\nexport class PgSelectBase<\n\tTTableName extends string | undefined,\n\tTSelection extends ColumnsSelection,\n\tTSelectMode extends SelectMode,\n\tTNullabilityMap extends Record = TTableName extends string ? Record\n\t\t: {},\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n\tTResult = SelectResult[],\n\tTSelectedFields = BuildSubquerySelection,\n> extends PgSelectQueryBuilderBase<\n\tPgSelectHKT,\n\tTTableName,\n\tTSelection,\n\tTSelectMode,\n\tTNullabilityMap,\n\tTDynamic,\n\tTExcludedMethods,\n\tTResult,\n\tTSelectedFields\n> implements RunnableQuery, SQLWrapper {\n\tstatic readonly [entityKind]: string = 'PgSelect';\n\n\t/** @internal */\n\t_prepare(name?: string): PgSelectPrepare {\n\t\tconst { session, config, dialect, joinsNotNullableMap } = this;\n\t\tif (!session) {\n\t\t\tthrow new Error('Cannot execute a query on a query builder. Please use a database instance instead.');\n\t\t}\n\t\treturn tracer.startActiveSpan('drizzle.prepareQuery', () => {\n\t\t\tconst fieldsList = orderSelectedFields(config.fields);\n\t\t\tconst query = session.prepareQuery<\n\t\t\t\tPreparedQueryConfig & { execute: TResult }\n\t\t\t>(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true);\n\t\t\tquery.joinsNotNullableMap = joinsNotNullableMap;\n\t\t\treturn query;\n\t\t});\n\t}\n\n\t/**\n\t * Create a prepared statement for this query. This allows\n\t * the database to remember this query for the given session\n\t * and call it by name, rather than specifying the full query.\n\t *\n\t * {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}\n\t */\n\tprepare(name: string): PgSelectPrepare {\n\t\treturn this._prepare(name);\n\t}\n\n\texecute: ReturnType['execute'] = (placeholderValues) => {\n\t\treturn tracer.startActiveSpan('drizzle.operation', () => {\n\t\t\treturn this._prepare().execute(placeholderValues);\n\t\t});\n\t};\n}\n\napplyMixins(PgSelectBase, [QueryPromise]);\n\nfunction createSetOperator(type: SetOperator, isAll: boolean): PgCreateSetOperatorFn {\n\treturn (leftSelect, rightSelect, ...restSelects) => {\n\t\tconst setOperators = [rightSelect, ...restSelects].map((select) => ({\n\t\t\ttype,\n\t\t\tisAll,\n\t\t\trightSelect: select as AnyPgSelect,\n\t\t}));\n\n\t\tfor (const setOperator of setOperators) {\n\t\t\tif (!haveSameKeys((leftSelect as any).getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Set operator error (union / intersect / except): selected fields are not the same or are in a different order',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn (leftSelect as AnyPgSelect).addSetOperators(setOperators) as any;\n\t};\n}\n\nconst getPgSetOperators = () => ({\n\tunion,\n\tunionAll,\n\tintersect,\n\tintersectAll,\n\texcept,\n\texceptAll,\n});\n\n/**\n * Adds `union` set operator to the query.\n *\n * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}\n *\n * @example\n *\n * ```ts\n * // Select all unique names from customers and users tables\n * import { union } from 'drizzle-orm/pg-core'\n *\n * await union(\n * db.select({ name: users.name }).from(users),\n * db.select({ name: customers.name }).from(customers)\n * );\n * // or\n * await db.select({ name: users.name })\n * .from(users)\n * .union(\n * db.select({ name: customers.name }).from(customers)\n * );\n * ```\n */\nexport const union = createSetOperator('union', false);\n\n/**\n * Adds `union all` set operator to the query.\n *\n * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}\n *\n * @example\n *\n * ```ts\n * // Select all transaction ids from both online and in-store sales\n * import { unionAll } from 'drizzle-orm/pg-core'\n *\n * await unionAll(\n * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),\n * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n * );\n * // or\n * await db.select({ transaction: onlineSales.transactionId })\n * .from(onlineSales)\n * .unionAll(\n * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n * );\n * ```\n */\nexport const unionAll = createSetOperator('union', true);\n\n/**\n * Adds `intersect` set operator to the query.\n *\n * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}\n *\n * @example\n *\n * ```ts\n * // Select course names that are offered in both departments A and B\n * import { intersect } from 'drizzle-orm/pg-core'\n *\n * await intersect(\n * db.select({ courseName: depA.courseName }).from(depA),\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * // or\n * await db.select({ courseName: depA.courseName })\n * .from(depA)\n * .intersect(\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * ```\n */\nexport const intersect = createSetOperator('intersect', false);\n\n/**\n * Adds `intersect all` set operator to the query.\n *\n * Calling this method will retain only the rows that are present in both result sets including all duplicates.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}\n *\n * @example\n *\n * ```ts\n * // Select all products and quantities that are ordered by both regular and VIP customers\n * import { intersectAll } from 'drizzle-orm/pg-core'\n *\n * await intersectAll(\n * db.select({\n * productId: regularCustomerOrders.productId,\n * quantityOrdered: regularCustomerOrders.quantityOrdered\n * })\n * .from(regularCustomerOrders),\n * db.select({\n * productId: vipCustomerOrders.productId,\n * quantityOrdered: vipCustomerOrders.quantityOrdered\n * })\n * .from(vipCustomerOrders)\n * );\n * // or\n * await db.select({\n * productId: regularCustomerOrders.productId,\n * quantityOrdered: regularCustomerOrders.quantityOrdered\n * })\n * .from(regularCustomerOrders)\n * .intersectAll(\n * db.select({\n * productId: vipCustomerOrders.productId,\n * quantityOrdered: vipCustomerOrders.quantityOrdered\n * })\n * .from(vipCustomerOrders)\n * );\n * ```\n */\nexport const intersectAll = createSetOperator('intersect', true);\n\n/**\n * Adds `except` set operator to the query.\n *\n * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}\n *\n * @example\n *\n * ```ts\n * // Select all courses offered in department A but not in department B\n * import { except } from 'drizzle-orm/pg-core'\n *\n * await except(\n * db.select({ courseName: depA.courseName }).from(depA),\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * // or\n * await db.select({ courseName: depA.courseName })\n * .from(depA)\n * .except(\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * ```\n */\nexport const except = createSetOperator('except', false);\n\n/**\n * Adds `except all` set operator to the query.\n *\n * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}\n *\n * @example\n *\n * ```ts\n * // Select all products that are ordered by regular customers but not by VIP customers\n * import { exceptAll } from 'drizzle-orm/pg-core'\n *\n * await exceptAll(\n * db.select({\n * productId: regularCustomerOrders.productId,\n * quantityOrdered: regularCustomerOrders.quantityOrdered\n * })\n * .from(regularCustomerOrders),\n * db.select({\n * productId: vipCustomerOrders.productId,\n * quantityOrdered: vipCustomerOrders.quantityOrdered\n * })\n * .from(vipCustomerOrders)\n * );\n * // or\n * await db.select({\n * productId: regularCustomerOrders.productId,\n * quantityOrdered: regularCustomerOrders.quantityOrdered,\n * })\n * .from(regularCustomerOrders)\n * .exceptAll(\n * db.select({\n * productId: vipCustomerOrders.productId,\n * quantityOrdered: vipCustomerOrders.quantityOrdered,\n * })\n * .from(vipCustomerOrders)\n * );\n * ```\n */\nexport const exceptAll = createSetOperator('except', true);\n", "import { entityKind } from '~/entity.ts';\nimport type { SQL, SQLWrapper } from '~/sql/index.ts';\n\nexport abstract class TypedQueryBuilder implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'TypedQueryBuilder';\n\n\tdeclare _: {\n\t\tselectedFields: TSelection;\n\t\tresult: TResult;\n\t};\n\n\t/** @internal */\n\tgetSelectedFields(): TSelection {\n\t\treturn this._.selectedFields;\n\t}\n\n\tabstract getSQL(): SQL;\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { PgDialect } from '~/pg-core/dialect.ts';\nimport type {\n\tPgPreparedQuery,\n\tPgQueryResultHKT,\n\tPgQueryResultKind,\n\tPgSession,\n\tPreparedQueryConfig,\n} from '~/pg-core/session.ts';\nimport type { PgMaterializedView } from '~/pg-core/view.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Query, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport { tracer } from '~/tracing.ts';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PgRefreshMaterializedView\n\textends\n\t\tQueryPromise>,\n\t\tRunnableQuery, 'pg'>,\n\t\tSQLWrapper\n{\n\treadonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly result: PgQueryResultKind;\n\t};\n}\n\nexport class PgRefreshMaterializedView\n\textends QueryPromise>\n\timplements RunnableQuery, 'pg'>, SQLWrapper\n{\n\tstatic readonly [entityKind]: string = 'PgRefreshMaterializedView';\n\n\tprivate config: {\n\t\tview: PgMaterializedView;\n\t\tconcurrently?: boolean;\n\t\twithNoData?: boolean;\n\t};\n\n\tconstructor(\n\t\tview: PgMaterializedView,\n\t\tprivate session: PgSession,\n\t\tprivate dialect: PgDialect,\n\t) {\n\t\tsuper();\n\t\tthis.config = { view };\n\t}\n\n\tconcurrently(): this {\n\t\tif (this.config.withNoData !== undefined) {\n\t\t\tthrow new Error('Cannot use concurrently and withNoData together');\n\t\t}\n\t\tthis.config.concurrently = true;\n\t\treturn this;\n\t}\n\n\twithNoData(): this {\n\t\tif (this.config.concurrently !== undefined) {\n\t\t\tthrow new Error('Cannot use concurrently and withNoData together');\n\t\t}\n\t\tthis.config.withNoData = true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildRefreshMaterializedViewQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(name?: string): PgPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: PgQueryResultKind;\n\t\t}\n\t> {\n\t\treturn tracer.startActiveSpan('drizzle.prepareQuery', () => {\n\t\t\treturn this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), undefined, name, true);\n\t\t});\n\t}\n\n\tprepare(name: string): PgPreparedQuery<\n\t\tPreparedQueryConfig & {\n\t\t\texecute: PgQueryResultKind;\n\t\t}\n\t> {\n\t\treturn this._prepare(name);\n\t}\n\n\texecute: ReturnType['execute'] = (placeholderValues) => {\n\t\treturn tracer.startActiveSpan('drizzle.operation', () => {\n\t\t\treturn this._prepare().execute(placeholderValues);\n\t\t});\n\t};\n}\n", "import type { GetColumnData } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { PgDialect } from '~/pg-core/dialect.ts';\nimport type {\n\tPgPreparedQuery,\n\tPgQueryResultHKT,\n\tPgQueryResultKind,\n\tPgSession,\n\tPreparedQueryConfig,\n} from '~/pg-core/session.ts';\nimport type { PgTable } from '~/pg-core/table.ts';\nimport type { SelectResultFields } from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Query, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport { mapUpdateSet, orderSelectedFields, type UpdateSet } from '~/utils.ts';\nimport type { PgColumn } from '../columns/common.ts';\nimport type { SelectedFields, SelectedFieldsOrdered } from './select.types.ts';\n\nexport interface PgUpdateConfig {\n\twhere?: SQL | undefined;\n\tset: UpdateSet;\n\ttable: PgTable;\n\treturning?: SelectedFieldsOrdered;\n\twithList?: Subquery[];\n}\n\nexport type PgUpdateSetSource =\n\t& {\n\t\t[Key in keyof TTable['$inferInsert']]?:\n\t\t\t| GetColumnData\n\t\t\t| SQL;\n\t}\n\t& {};\n\nexport class PgUpdateBuilder {\n\tstatic readonly [entityKind]: string = 'PgUpdateBuilder';\n\n\tdeclare readonly _: {\n\t\treadonly table: TTable;\n\t};\n\n\tconstructor(\n\t\tprivate table: TTable,\n\t\tprivate session: PgSession,\n\t\tprivate dialect: PgDialect,\n\t\tprivate withList?: Subquery[],\n\t) {}\n\n\tset(values: PgUpdateSetSource): PgUpdateBase {\n\t\treturn new PgUpdateBase(\n\t\t\tthis.table,\n\t\t\tmapUpdateSet(this.table, values),\n\t\t\tthis.session,\n\t\t\tthis.dialect,\n\t\t\tthis.withList,\n\t\t);\n\t}\n}\n\nexport type PgUpdateWithout<\n\tT extends AnyPgUpdate,\n\tTDynamic extends boolean,\n\tK extends keyof T & string,\n> = TDynamic extends true ? T : Omit<\n\tPgUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['queryResult'],\n\t\tT['_']['returning'],\n\t\tTDynamic,\n\t\tT['_']['excludedMethods'] | K\n\t>,\n\tT['_']['excludedMethods'] | K\n>;\n\nexport type PgUpdateReturningAll = PgUpdateWithout<\n\tPgUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['queryResult'],\n\t\tT['_']['table']['$inferSelect'],\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type PgUpdateReturning<\n\tT extends AnyPgUpdate,\n\tTDynamic extends boolean,\n\tTSelectedFields extends SelectedFields,\n> = PgUpdateWithout<\n\tPgUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['queryResult'],\n\t\tSelectResultFields,\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type PgUpdatePrepare = PgPreparedQuery<\n\tPreparedQueryConfig & {\n\t\texecute: T['_']['returning'] extends undefined ? PgQueryResultKind\n\t\t\t: T['_']['returning'][];\n\t}\n>;\n\nexport type PgUpdateDynamic = PgUpdate<\n\tT['_']['table'],\n\tT['_']['queryResult'],\n\tT['_']['returning']\n>;\n\nexport type PgUpdate<\n\tTTable extends PgTable = PgTable,\n\tTQueryResult extends PgQueryResultHKT = PgQueryResultHKT,\n\tTReturning extends Record | undefined = Record | undefined,\n> = PgUpdateBase;\n\ntype AnyPgUpdate = PgUpdateBase;\n\nexport interface PgUpdateBase<\n\tTTable extends PgTable,\n\tTQueryResult extends PgQueryResultHKT,\n\tTReturning extends Record | undefined = undefined,\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n> extends\n\tQueryPromise : TReturning[]>,\n\tRunnableQuery : TReturning[], 'pg'>,\n\tSQLWrapper\n{\n\treadonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly table: TTable;\n\t\treadonly queryResult: TQueryResult;\n\t\treadonly returning: TReturning;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TReturning extends undefined ? PgQueryResultKind : TReturning[];\n\t};\n}\n\nexport class PgUpdateBase<\n\tTTable extends PgTable,\n\tTQueryResult extends PgQueryResultHKT,\n\tTReturning extends Record | undefined = undefined,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTDynamic extends boolean = false,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTExcludedMethods extends string = never,\n> extends QueryPromise : TReturning[]>\n\timplements\n\t\tRunnableQuery : TReturning[], 'pg'>,\n\t\tSQLWrapper\n{\n\tstatic readonly [entityKind]: string = 'PgUpdate';\n\n\tprivate config: PgUpdateConfig;\n\n\tconstructor(\n\t\ttable: TTable,\n\t\tset: UpdateSet,\n\t\tprivate session: PgSession,\n\t\tprivate dialect: PgDialect,\n\t\twithList?: Subquery[],\n\t) {\n\t\tsuper();\n\t\tthis.config = { set, table, withList };\n\t}\n\n\t/**\n\t * Adds a 'where' clause to the query.\n\t *\n\t * Calling this method will update only those rows that fulfill a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/update}\n\t *\n\t * @param where the 'where' clause.\n\t *\n\t * @example\n\t * You can use conditional operators and `sql function` to filter the rows to be updated.\n\t *\n\t * ```ts\n\t * // Update all cars with green color\n\t * await db.update(cars).set({ color: 'red' })\n\t * .where(eq(cars.color, 'green'));\n\t * // or\n\t * await db.update(cars).set({ color: 'red' })\n\t * .where(sql`${cars.color} = 'green'`)\n\t * ```\n\t *\n\t * You can logically combine conditional operators with `and()` and `or()` operators:\n\t *\n\t * ```ts\n\t * // Update all BMW cars with a green color\n\t * await db.update(cars).set({ color: 'red' })\n\t * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t *\n\t * // Update all cars with the green or blue color\n\t * await db.update(cars).set({ color: 'red' })\n\t * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t * ```\n\t */\n\twhere(where: SQL | undefined): PgUpdateWithout {\n\t\tthis.config.where = where;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `returning` clause to the query.\n\t *\n\t * Calling this method will return the specified fields of the updated rows. If no fields are specified, all fields will be returned.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/update#update-with-returning}\n\t *\n\t * @example\n\t * ```ts\n\t * // Update all cars with the green color and return all fields\n\t * const updatedCars: Car[] = await db.update(cars)\n\t * .set({ color: 'red' })\n\t * .where(eq(cars.color, 'green'))\n\t * .returning();\n\t *\n\t * // Update all cars with the green color and return only their id and brand fields\n\t * const updatedCarsIdsAndBrands: { id: number, brand: string }[] = await db.update(cars)\n\t * .set({ color: 'red' })\n\t * .where(eq(cars.color, 'green'))\n\t * .returning({ id: cars.id, brand: cars.brand });\n\t * ```\n\t */\n\treturning(): PgUpdateReturningAll;\n\treturning(\n\t\tfields: TSelectedFields,\n\t): PgUpdateReturning;\n\treturning(\n\t\tfields: SelectedFields = this.config.table[Table.Symbol.Columns],\n\t): PgUpdateWithout {\n\t\tthis.config.returning = orderSelectedFields(fields);\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildUpdateQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(name?: string): PgUpdatePrepare {\n\t\treturn this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true);\n\t}\n\n\tprepare(name: string): PgUpdatePrepare {\n\t\treturn this._prepare(name);\n\t}\n\n\toverride execute: ReturnType['execute'] = (placeholderValues) => {\n\t\treturn this._prepare().execute(placeholderValues);\n\t};\n\n\t$dynamic(): PgUpdateDynamic {\n\t\treturn this as any;\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport {\n\ttype BuildQueryResult,\n\ttype BuildRelationalQueryResult,\n\ttype DBQueryConfig,\n\tmapRelationalRow,\n\ttype TableRelationalConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Query, QueryWithTypings, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport { tracer } from '~/tracing.ts';\nimport type { KnownKeysOnly } from '~/utils.ts';\nimport type { PgDialect } from '../dialect.ts';\nimport type { PgPreparedQuery, PgSession, PreparedQueryConfig } from '../session.ts';\nimport type { PgTable } from '../table.ts';\n\nexport class RelationalQueryBuilder {\n\tstatic readonly [entityKind]: string = 'PgRelationalQueryBuilder';\n\n\tconstructor(\n\t\tprivate fullSchema: Record,\n\t\tprivate schema: TSchema,\n\t\tprivate tableNamesMap: Record,\n\t\tprivate table: PgTable,\n\t\tprivate tableConfig: TableRelationalConfig,\n\t\tprivate dialect: PgDialect,\n\t\tprivate session: PgSession,\n\t) {}\n\n\tfindMany>(\n\t\tconfig?: KnownKeysOnly>,\n\t): PgRelationalQuery[]> {\n\t\treturn new PgRelationalQuery(\n\t\t\tthis.fullSchema,\n\t\t\tthis.schema,\n\t\t\tthis.tableNamesMap,\n\t\t\tthis.table,\n\t\t\tthis.tableConfig,\n\t\t\tthis.dialect,\n\t\t\tthis.session,\n\t\t\tconfig ? (config as DBQueryConfig<'many', true>) : {},\n\t\t\t'many',\n\t\t);\n\t}\n\n\tfindFirst, 'limit'>>(\n\t\tconfig?: KnownKeysOnly, 'limit'>>,\n\t): PgRelationalQuery | undefined> {\n\t\treturn new PgRelationalQuery(\n\t\t\tthis.fullSchema,\n\t\t\tthis.schema,\n\t\t\tthis.tableNamesMap,\n\t\t\tthis.table,\n\t\t\tthis.tableConfig,\n\t\t\tthis.dialect,\n\t\t\tthis.session,\n\t\t\tconfig ? { ...(config as DBQueryConfig<'many', true> | undefined), limit: 1 } : { limit: 1 },\n\t\t\t'first',\n\t\t);\n\t}\n}\n\nexport class PgRelationalQuery extends QueryPromise\n\timplements RunnableQuery, SQLWrapper\n{\n\tstatic readonly [entityKind]: string = 'PgRelationalQuery';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly result: TResult;\n\t};\n\n\tconstructor(\n\t\tprivate fullSchema: Record,\n\t\tprivate schema: TablesRelationalConfig,\n\t\tprivate tableNamesMap: Record,\n\t\tprivate table: PgTable,\n\t\tprivate tableConfig: TableRelationalConfig,\n\t\tprivate dialect: PgDialect,\n\t\tprivate session: PgSession,\n\t\tprivate config: DBQueryConfig<'many', true> | true,\n\t\tprivate mode: 'many' | 'first',\n\t) {\n\t\tsuper();\n\t}\n\n\t/** @internal */\n\t_prepare(name?: string): PgPreparedQuery {\n\t\treturn tracer.startActiveSpan('drizzle.prepareQuery', () => {\n\t\t\tconst { query, builtQuery } = this._toSQL();\n\n\t\t\treturn this.session.prepareQuery(\n\t\t\t\tbuiltQuery,\n\t\t\t\tundefined,\n\t\t\t\tname,\n\t\t\t\ttrue,\n\t\t\t\t(rawRows, mapColumnValue) => {\n\t\t\t\t\tconst rows = rawRows.map((row) =>\n\t\t\t\t\t\tmapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)\n\t\t\t\t\t);\n\t\t\t\t\tif (this.mode === 'first') {\n\t\t\t\t\t\treturn rows[0] as TResult;\n\t\t\t\t\t}\n\t\t\t\t\treturn rows as TResult;\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\tprepare(name: string): PgPreparedQuery {\n\t\treturn this._prepare(name);\n\t}\n\n\tprivate _getQuery() {\n\t\treturn this.dialect.buildRelationalQueryWithoutPK({\n\t\t\tfullSchema: this.fullSchema,\n\t\t\tschema: this.schema,\n\t\t\ttableNamesMap: this.tableNamesMap,\n\t\t\ttable: this.table,\n\t\t\ttableConfig: this.tableConfig,\n\t\t\tqueryConfig: this.config,\n\t\t\ttableAlias: this.tableConfig.tsName,\n\t\t});\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this._getQuery().sql as SQL;\n\t}\n\n\tprivate _toSQL(): { query: BuildRelationalQueryResult; builtQuery: QueryWithTypings } {\n\t\tconst query = this._getQuery();\n\n\t\tconst builtQuery = this.dialect.sqlToQuery(query.sql as SQL);\n\n\t\treturn { query, builtQuery };\n\t}\n\n\ttoSQL(): Query {\n\t\treturn this._toSQL().builtQuery;\n\t}\n\n\toverride execute(): Promise {\n\t\treturn tracer.startActiveSpan('drizzle.operation', () => {\n\t\t\treturn this._prepare().execute();\n\t\t});\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport type { Query, SQL, SQLWrapper } from '~/sql/sql.ts';\n\nexport interface PgRaw extends QueryPromise, RunnableQuery, SQLWrapper {}\n\nexport class PgRaw extends QueryPromise\n\timplements RunnableQuery, SQLWrapper, PreparedQuery\n{\n\tstatic readonly [entityKind]: string = 'PgRaw';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'pg';\n\t\treadonly result: TResult;\n\t};\n\n\tconstructor(\n\t\tpublic execute: () => Promise,\n\t\tprivate sql: SQL,\n\t\tprivate query: Query,\n\t\tprivate mapBatchResult: (result: unknown) => unknown,\n\t) {\n\t\tsuper();\n\t}\n\n\t/** @internal */\n\tgetSQL() {\n\t\treturn this.sql;\n\t}\n\n\tgetQuery() {\n\t\treturn this.query;\n\t}\n\n\tmapResult(result: unknown, isFromBatch?: boolean) {\n\t\treturn isFromBatch ? this.mapBatchResult(result) : result;\n\t}\n\n\t_prepare(): PreparedQuery {\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tisResponseInArrayMode() {\n\t\treturn false;\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { TransactionRollbackError } from '~/errors.ts';\nimport type { TablesRelationalConfig } from '~/relations.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport { type Query, type SQL, sql } from '~/sql/index.ts';\nimport { tracer } from '~/tracing.ts';\nimport { PgDatabase } from './db.ts';\nimport type { PgDialect } from './dialect.ts';\nimport type { SelectedFieldsOrdered } from './query-builders/select.types.ts';\n\nexport interface PreparedQueryConfig {\n\texecute: unknown;\n\tall: unknown;\n\tvalues: unknown;\n}\n\nexport abstract class PgPreparedQuery implements PreparedQuery {\n\tconstructor(protected query: Query) {}\n\n\tgetQuery(): Query {\n\t\treturn this.query;\n\t}\n\n\tmapResult(response: unknown, _isFromBatch?: boolean): unknown {\n\t\treturn response;\n\t}\n\n\tstatic readonly [entityKind]: string = 'PgPreparedQuery';\n\n\t/** @internal */\n\tjoinsNotNullableMap?: Record;\n\n\tabstract execute(placeholderValues?: Record): Promise;\n\n\t/** @internal */\n\tabstract all(placeholderValues?: Record): Promise;\n\n\t/** @internal */\n\tabstract isResponseInArrayMode(): boolean;\n}\n\nexport interface PgTransactionConfig {\n\tisolationLevel?: 'read uncommitted' | 'read committed' | 'repeatable read' | 'serializable';\n\taccessMode?: 'read only' | 'read write';\n\tdeferrable?: boolean;\n}\n\nexport abstract class PgSession<\n\tTQueryResult extends PgQueryResultHKT = PgQueryResultHKT,\n\tTFullSchema extends Record = Record,\n\tTSchema extends TablesRelationalConfig = Record,\n> {\n\tstatic readonly [entityKind]: string = 'PgSession';\n\n\tconstructor(protected dialect: PgDialect) {}\n\n\tabstract prepareQuery(\n\t\tquery: Query,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\tname: string | undefined,\n\t\tisResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => T['execute'],\n\t): PgPreparedQuery;\n\n\texecute(query: SQL): Promise {\n\t\treturn tracer.startActiveSpan('drizzle.operation', () => {\n\t\t\tconst prepared = tracer.startActiveSpan('drizzle.prepareQuery', () => {\n\t\t\t\treturn this.prepareQuery(\n\t\t\t\t\tthis.dialect.sqlToQuery(query),\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\tfalse,\n\t\t\t\t);\n\t\t\t});\n\n\t\t\treturn prepared.execute();\n\t\t});\n\t}\n\n\tall(query: SQL): Promise {\n\t\treturn this.prepareQuery(\n\t\t\tthis.dialect.sqlToQuery(query),\n\t\t\tundefined,\n\t\t\tundefined,\n\t\t\tfalse,\n\t\t).all();\n\t}\n\n\tabstract transaction(\n\t\ttransaction: (tx: PgTransaction) => Promise,\n\t\tconfig?: PgTransactionConfig,\n\t): Promise;\n}\n\nexport abstract class PgTransaction<\n\tTQueryResult extends PgQueryResultHKT,\n\tTFullSchema extends Record = Record,\n\tTSchema extends TablesRelationalConfig = Record,\n> extends PgDatabase {\n\tstatic readonly [entityKind]: string = 'PgTransaction';\n\n\tconstructor(\n\t\tdialect: PgDialect,\n\t\tsession: PgSession,\n\t\tprotected schema: {\n\t\t\tfullSchema: Record;\n\t\t\tschema: TSchema;\n\t\t\ttableNamesMap: Record;\n\t\t} | undefined,\n\t\tprotected readonly nestedIndex = 0,\n\t) {\n\t\tsuper(dialect, session, schema);\n\t}\n\n\trollback(): never {\n\t\tthrow new TransactionRollbackError();\n\t}\n\n\t/** @internal */\n\tgetTransactionConfigSQL(config: PgTransactionConfig): SQL {\n\t\tconst chunks: string[] = [];\n\t\tif (config.isolationLevel) {\n\t\t\tchunks.push(`isolation level ${config.isolationLevel}`);\n\t\t}\n\t\tif (config.accessMode) {\n\t\t\tchunks.push(config.accessMode);\n\t\t}\n\t\tif (typeof config.deferrable === 'boolean') {\n\t\t\tchunks.push(config.deferrable ? 'deferrable' : 'not deferrable');\n\t\t}\n\t\treturn sql.raw(chunks.join(' '));\n\t}\n\n\tsetTransaction(config: PgTransactionConfig): Promise {\n\t\treturn this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);\n\t}\n\n\tabstract override transaction(\n\t\ttransaction: (tx: PgTransaction) => Promise,\n\t): Promise;\n}\n\nexport interface PgQueryResultHKT {\n\treadonly $brand: 'PgQueryResultHKT';\n\treadonly row: unknown;\n\treadonly type: unknown;\n}\n\nexport type PgQueryResultKind = (TKind & {\n\treadonly row: TRow;\n})['type'];\n", "export * from \"./dbMiddleware\";\nexport * from \"./githubApiMiddleware\";\nexport * from \"./githubWebhooksMiddleware\";\nexport * from \"./reactRendererMiddleware\";\n", "import { neon } from \"@neondatabase/serverless\";\nimport { drizzle } from \"drizzle-orm/neon-http\";\nimport { createMiddleware } from \"hono/factory\";\n\nimport * as schema from \"../db\";\nimport type { Db, HonoEnv } from \"../types\";\n\nlet db: Db | undefined;\n\nfunction getDbInstance(url: string) {\n if (!db) {\n const sql = neon(url);\n db = drizzle(sql, { schema });\n }\n\n return db;\n}\n\n/**\n * Middleware to add the database instance to the context.\n */\nexport const dbMiddleware = createMiddleware(async (c, next) => {\n const db = getDbInstance(c.env.DATABASE_URL);\n c.set(\"db\", db);\n\n await next();\n});\n", "var to=Object.create;var Ce=Object.defineProperty;var ro=Object.getOwnPropertyDescriptor;var no=Object.getOwnPropertyNames;var io=Object.getPrototypeOf,so=Object.prototype.hasOwnProperty;var oo=(r,e,t)=>e in r?Ce(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):\nr[e]=t;var a=(r,e)=>Ce(r,\"name\",{value:e,configurable:!0});var z=(r,e)=>()=>(r&&(e=r(r=0)),e);var I=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ie=(r,e)=>{for(var t in e)\nCe(r,t,{get:e[t],enumerable:!0})},An=(r,e,t,n)=>{if(e&&typeof e==\"object\"||typeof e==\n\"function\")for(let i of no(e))!so.call(r,i)&&i!==t&&Ce(r,i,{get:()=>e[i],enumerable:!(n=\nro(e,i))||n.enumerable});return r};var Te=(r,e,t)=>(t=r!=null?to(io(r)):{},An(e||!r||!r.__esModule?Ce(t,\"default\",{\nvalue:r,enumerable:!0}):t,r)),N=r=>An(Ce({},\"__esModule\",{value:!0}),r);var _=(r,e,t)=>oo(r,typeof e!=\"symbol\"?e+\"\":e,t);var In=I(nt=>{\"use strict\";p();nt.byteLength=uo;nt.toByteArray=ho;nt.fromByteArray=\npo;var ae=[],te=[],ao=typeof Uint8Array<\"u\"?Uint8Array:Array,Pt=\"ABCDEFGHIJKLMNO\\\nPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";for(ve=0,Cn=Pt.length;ve0)throw new Error(\"Invalid string. Length must be a multip\\\nle of 4\");var t=r.indexOf(\"=\");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}a(Tn,\n\"getLens\");function uo(r){var e=Tn(r),t=e[0],n=e[1];return(t+n)*3/4-n}a(uo,\"byte\\\nLength\");function co(r,e,t){return(e+t)*3/4-t}a(co,\"_byteLength\");function ho(r){\nvar e,t=Tn(r),n=t[0],i=t[1],s=new ao(co(r,n,i)),o=0,u=i>0?n-4:n,c;for(c=0;c>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=\nte[r.charCodeAt(c)]<<2|te[r.charCodeAt(c+1)]>>4,s[o++]=e&255),i===1&&(e=te[r.charCodeAt(\nc)]<<10|te[r.charCodeAt(c+1)]<<4|te[r.charCodeAt(c+2)]>>2,s[o++]=e>>8&255,s[o++]=\ne&255),s}a(ho,\"toByteArray\");function lo(r){return ae[r>>18&63]+ae[r>>12&63]+ae[r>>\n6&63]+ae[r&63]}a(lo,\"tripletToBase64\");function fo(r,e,t){for(var n,i=[],s=e;su?u:o+s));return n===1?(e=r[t-1],i.push(ae[e>>2]+\nae[e<<4&63]+\"==\")):n===2&&(e=(r[t-2]<<8)+r[t-1],i.push(ae[e>>10]+ae[e>>4&63]+ae[e<<\n2&63]+\"=\")),i.join(\"\")}a(po,\"fromByteArray\")});var Pn=I(Bt=>{p();Bt.read=function(r,e,t,n,i){var s,o,u=i*8-n-1,c=(1<>\n1,l=-7,d=t?i-1:0,b=t?-1:1,C=r[e+d];for(d+=b,s=C&(1<<-l)-1,C>>=-l,l+=u;l>0;s=s*256+\nr[e+d],d+=b,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=n;l>0;o=o*256+r[e+d],d+=b,l-=8);if(s===\n0)s=1-h;else{if(s===c)return o?NaN:(C?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-h}return(C?\n-1:1)*o*Math.pow(2,s-n)};Bt.write=function(r,e,t,n,i,s){var o,u,c,h=s*8-i-1,l=(1<<\nh)-1,d=l>>1,b=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,C=n?0:s-1,B=n?1:-1,W=e<0||\ne===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(u=isNaN(e)?1:0,o=l):(o=Math.\nfloor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+d>=1?e+=b/c:e+=\nb*Math.pow(2,1-d),e*c>=2&&(o++,c/=2),o+d>=l?(u=0,o=l):o+d>=1?(u=(e*c-1)*Math.pow(\n2,i),o=o+d):(u=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;r[t+C]=u&255,C+=B,u/=256,\ni-=8);for(o=o<0;r[t+C]=o&255,C+=B,o/=256,h-=8);r[t+C-B]|=W*128}});var $n=I(Le=>{\"use strict\";p();var Lt=In(),Pe=Pn(),Bn=typeof Symbol==\"function\"&&\ntypeof Symbol.for==\"function\"?Symbol.for(\"nodejs.util.inspect.custom\"):null;Le.Buffer=\nf;Le.SlowBuffer=So;Le.INSPECT_MAX_BYTES=50;var it=2147483647;Le.kMaxLength=it;f.\nTYPED_ARRAY_SUPPORT=yo();!f.TYPED_ARRAY_SUPPORT&&typeof console<\"u\"&&typeof console.\nerror==\"function\"&&console.error(\"This browser lacks typed array (Uint8Array) su\\\npport which is required by `buffer` v5.x. Use `buffer` v4.x if you require old b\\\nrowser support.\");function yo(){try{let r=new Uint8Array(1),e={foo:a(function(){\nreturn 42},\"foo\")};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(\nr,e),r.foo()===42}catch{return!1}}a(yo,\"typedArraySupport\");Object.defineProperty(\nf.prototype,\"parent\",{enumerable:!0,get:a(function(){if(f.isBuffer(this))return this.\nbuffer},\"get\")});Object.defineProperty(f.prototype,\"offset\",{enumerable:!0,get:a(\nfunction(){if(f.isBuffer(this))return this.byteOffset},\"get\")});function fe(r){if(r>\nit)throw new RangeError('The value \"'+r+'\" is invalid for option \"size\"');let e=new Uint8Array(\nr);return Object.setPrototypeOf(e,f.prototype),e}a(fe,\"createBuffer\");function f(r,e,t){\nif(typeof r==\"number\"){if(typeof e==\"string\")throw new TypeError('The \"string\" a\\\nrgument must be of type string. Received type number');return Dt(r)}return Mn(r,\ne,t)}a(f,\"Buffer\");f.poolSize=8192;function Mn(r,e,t){if(typeof r==\"string\")return go(\nr,e);if(ArrayBuffer.isView(r))return wo(r);if(r==null)throw new TypeError(\"The f\\\nirst argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-l\\\nike Object. Received type \"+typeof r);if(ue(r,ArrayBuffer)||r&&ue(r.buffer,ArrayBuffer)||\ntypeof SharedArrayBuffer<\"u\"&&(ue(r,SharedArrayBuffer)||r&&ue(r.buffer,SharedArrayBuffer)))\nreturn Ft(r,e,t);if(typeof r==\"number\")throw new TypeError('The \"value\" argument\\\n must not be of type number. Received type number');let n=r.valueOf&&r.valueOf();\nif(n!=null&&n!==r)return f.from(n,e,t);let i=bo(r);if(i)return i;if(typeof Symbol<\n\"u\"&&Symbol.toPrimitive!=null&&typeof r[Symbol.toPrimitive]==\"function\")return f.\nfrom(r[Symbol.toPrimitive](\"string\"),e,t);throw new TypeError(\"The first argumen\\\nt must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. \\\nReceived type \"+typeof r)}a(Mn,\"from\");f.from=function(r,e,t){return Mn(r,e,t)};\nObject.setPrototypeOf(f.prototype,Uint8Array.prototype);Object.setPrototypeOf(f,\nUint8Array);function Dn(r){if(typeof r!=\"number\")throw new TypeError('\"size\" arg\\\nument must be of type number');if(r<0)throw new RangeError('The value \"'+r+'\" is\\\n invalid for option \"size\"')}a(Dn,\"assertSize\");function mo(r,e,t){return Dn(r),\nr<=0?fe(r):e!==void 0?typeof t==\"string\"?fe(r).fill(e,t):fe(r).fill(e):fe(r)}a(mo,\n\"alloc\");f.alloc=function(r,e,t){return mo(r,e,t)};function Dt(r){return Dn(r),fe(\nr<0?0:kt(r)|0)}a(Dt,\"allocUnsafe\");f.allocUnsafe=function(r){return Dt(r)};f.allocUnsafeSlow=\nfunction(r){return Dt(r)};function go(r,e){if((typeof e!=\"string\"||e===\"\")&&(e=\"\\\nutf8\"),!f.isEncoding(e))throw new TypeError(\"Unknown encoding: \"+e);let t=kn(r,e)|\n0,n=fe(t),i=n.write(r,e);return i!==t&&(n=n.slice(0,i)),n}a(go,\"fromString\");function Rt(r){\nlet e=r.length<0?0:kt(r.length)|0,t=fe(e);for(let n=0;n=\nit)throw new RangeError(\"Attempt to allocate Buffer larger than maximum size: 0x\"+\nit.toString(16)+\" bytes\");return r|0}a(kt,\"checked\");function So(r){return+r!=r&&\n(r=0),f.alloc(+r)}a(So,\"SlowBuffer\");f.isBuffer=a(function(e){return e!=null&&e.\n_isBuffer===!0&&e!==f.prototype},\"isBuffer\");f.compare=a(function(e,t){if(ue(e,Uint8Array)&&\n(e=f.from(e,e.offset,e.byteLength)),ue(t,Uint8Array)&&(t=f.from(t,t.offset,t.byteLength)),\n!f.isBuffer(e)||!f.isBuffer(t))throw new TypeError('The \"buf1\", \"buf2\" arguments\\\n must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t.\nlength;for(let s=0,o=Math.min(n,i);si.length?(f.isBuffer(\no)||(o=f.from(o)),o.copy(i,s)):Uint8Array.prototype.set.call(i,o,s);else if(f.isBuffer(\no))o.copy(i,s);else throw new TypeError('\"list\" argument must be an Array of Buf\\\nfers');s+=o.length}return i},\"concat\");function kn(r,e){if(f.isBuffer(r))return r.\nlength;if(ArrayBuffer.isView(r)||ue(r,ArrayBuffer))return r.byteLength;if(typeof r!=\n\"string\")throw new TypeError('The \"string\" argument must be one of type string, \\\nBuffer, or ArrayBuffer. Received type '+typeof r);let t=r.length,n=arguments.length>\n2&&arguments[2]===!0;if(!n&&t===0)return 0;let i=!1;for(;;)switch(e){case\"ascii\":case\"\\\nlatin1\":case\"binary\":return t;case\"utf8\":case\"utf-8\":return Mt(r).length;case\"uc\\\ns2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return t*2;case\"hex\":return t>>>1;case\"\\\nbase64\":return Gn(r).length;default:if(i)return n?-1:Mt(r).length;e=(\"\"+e).toLowerCase(),\ni=!0}}a(kn,\"byteLength\");f.byteLength=kn;function xo(r,e,t){let n=!1;if((e===void 0||\ne<0)&&(e=0),e>this.length||((t===void 0||t>this.length)&&(t=this.length),t<=0)||\n(t>>>=0,e>>>=0,t<=e))return\"\";for(r||(r=\"utf8\");;)switch(r){case\"hex\":return Lo(\nthis,e,t);case\"utf8\":case\"utf-8\":return On(this,e,t);case\"ascii\":return Po(this,\ne,t);case\"latin1\":case\"binary\":return Bo(this,e,t);case\"base64\":return To(this,e,\nt);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return Ro(this,e,t);default:\nif(n)throw new TypeError(\"Unknown encoding: \"+r);r=(r+\"\").toLowerCase(),n=!0}}a(\nxo,\"slowToString\");f.prototype._isBuffer=!0;function Ee(r,e,t){let n=r[e];r[e]=r[t],\nr[t]=n}a(Ee,\"swap\");f.prototype.swap16=a(function(){let e=this.length;if(e%2!==0)\nthrow new RangeError(\"Buffer size must be a multiple of 16-bits\");for(let t=0;t<\ne;t+=2)Ee(this,t,t+1);return this},\"swap16\");f.prototype.swap32=a(function(){let e=this.\nlength;if(e%4!==0)throw new RangeError(\"Buffer size must be a multiple of 32-bit\\\ns\");for(let t=0;tt&&(e+=\" ... \"),\"\"},\"inspect\");Bn&&(f.prototype[Bn]=f.prototype.inspect);f.prototype.compare=\na(function(e,t,n,i,s){if(ue(e,Uint8Array)&&(e=f.from(e,e.offset,e.byteLength)),!f.\nisBuffer(e))throw new TypeError('The \"target\" argument must be one of type Buffe\\\nr or Uint8Array. Received type '+typeof e);if(t===void 0&&(t=0),n===void 0&&(n=e?\ne.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),t<0||n>e.length||i<0||\ns>this.length)throw new RangeError(\"out of range index\");if(i>=s&&t>=n)return 0;\nif(i>=s)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;\nlet o=s-i,u=n-t,c=Math.min(o,u),h=this.slice(i,s),l=e.slice(t,n);for(let d=0;d2147483647?t=2147483647:\nt<-2147483648&&(t=-2147483648),t=+t,Ot(t)&&(t=i?0:r.length-1),t<0&&(t=r.length+t),\nt>=r.length){if(i)return-1;t=r.length-1}else if(t<0)if(i)t=0;else return-1;if(typeof e==\n\"string\"&&(e=f.from(e,n)),f.isBuffer(e))return e.length===0?-1:Ln(r,e,t,n,i);if(typeof e==\n\"number\")return e=e&255,typeof Uint8Array.prototype.indexOf==\"function\"?i?Uint8Array.\nprototype.indexOf.call(r,e,t):Uint8Array.prototype.lastIndexOf.call(r,e,t):Ln(r,\n[e],t,n,i);throw new TypeError(\"val must be string, number or Buffer\")}a(Un,\"bid\\\nirectionalIndexOf\");function Ln(r,e,t,n,i){let s=1,o=r.length,u=e.length;if(n!==\nvoid 0&&(n=String(n).toLowerCase(),n===\"ucs2\"||n===\"ucs-2\"||n===\"utf16le\"||n===\"\\\nutf-16le\")){if(r.length<2||e.length<2)return-1;s=2,o/=2,u/=2,t/=2}function c(l,d){\nreturn s===1?l[d]:l.readUInt16BE(d*s)}a(c,\"read\");let h;if(i){let l=-1;for(h=t;h<\no;h++)if(c(r,h)===c(e,l===-1?0:h-l)){if(l===-1&&(l=h),h-l+1===u)return l*s}else l!==\n-1&&(h-=h-l),l=-1}else for(t+u>o&&(t=o-u),h=t;h>=0;h--){let l=!0;for(let d=0;di&&(n=i)):n=i;let s=e.length;n>\ns/2&&(n=s/2);let o;for(o=0;o>>0,isFinite(n)?\n(n=n>>>0,i===void 0&&(i=\"utf8\")):(i=n,n=void 0);else throw new Error(\"Buffer.wri\\\nte(string, encoding, offset[, length]) is no longer supported\");let s=this.length-\nt;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError(\n\"Attempt to write outside buffer bounds\");i||(i=\"utf8\");let o=!1;for(;;)switch(i){case\"\\\nhex\":return vo(this,e,t,n);case\"utf8\":case\"utf-8\":return Eo(this,e,t,n);case\"asc\\\nii\":case\"latin1\":case\"binary\":return _o(this,e,t,n);case\"base64\":return Ao(this,\ne,t,n);case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return Co(this,e,t,n);default:\nif(o)throw new TypeError(\"Unknown encoding: \"+i);i=(\"\"+i).toLowerCase(),o=!0}},\"\\\nwrite\");f.prototype.toJSON=a(function(){return{type:\"Buffer\",data:Array.prototype.\nslice.call(this._arr||this,0)}},\"toJSON\");function To(r,e,t){return e===0&&t===r.\nlength?Lt.fromByteArray(r):Lt.fromByteArray(r.slice(e,t))}a(To,\"base64Slice\");function On(r,e,t){\nt=Math.min(r.length,t);let n=[],i=e;for(;i239?4:s>223?\n3:s>191?2:1;if(i+u<=t){let c,h,l,d;switch(u){case 1:s<128&&(o=s);break;case 2:c=\nr[i+1],(c&192)===128&&(d=(s&31)<<6|c&63,d>127&&(o=d));break;case 3:c=r[i+1],h=r[i+\n2],(c&192)===128&&(h&192)===128&&(d=(s&15)<<12|(c&63)<<6|h&63,d>2047&&(d<55296||\nd>57343)&&(o=d));break;case 4:c=r[i+1],h=r[i+2],l=r[i+3],(c&192)===128&&(h&192)===\n128&&(l&192)===128&&(d=(s&15)<<18|(c&63)<<12|(h&63)<<6|l&63,d>65535&&d<1114112&&\n(o=d))}}o===null?(o=65533,u=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|\no&1023),n.push(o),i+=u}return Io(n)}a(On,\"utf8Slice\");var Rn=4096;function Io(r){\nlet e=r.length;if(e<=Rn)return String.fromCharCode.apply(String,r);let t=\"\",n=0;\nfor(;nn)&&(t=n);let i=\"\";for(let s=e;sn&&(e=n),t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),tt)throw new RangeError(\n\"Trying to access beyond buffer length\")}a(q,\"checkOffset\");f.prototype.readUintLE=\nf.prototype.readUIntLE=a(function(e,t,n){e=e>>>0,t=t>>>0,n||q(e,t,this.length);let i=this[e],\ns=1,o=0;for(;++o>>0,t=t>>>0,n||q(e,t,this.\nlength);let i=this[e+--t],s=1;for(;t>0&&(s*=256);)i+=this[e+--t]*s;return i},\"re\\\nadUIntBE\");f.prototype.readUint8=f.prototype.readUInt8=a(function(e,t){return e=\ne>>>0,t||q(e,1,this.length),this[e]},\"readUInt8\");f.prototype.readUint16LE=f.prototype.\nreadUInt16LE=a(function(e,t){return e=e>>>0,t||q(e,2,this.length),this[e]|this[e+\n1]<<8},\"readUInt16LE\");f.prototype.readUint16BE=f.prototype.readUInt16BE=a(function(e,t){\nreturn e=e>>>0,t||q(e,2,this.length),this[e]<<8|this[e+1]},\"readUInt16BE\");f.prototype.\nreadUint32LE=f.prototype.readUInt32LE=a(function(e,t){return e=e>>>0,t||q(e,4,this.\nlength),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216},\"readUInt32LE\");\nf.prototype.readUint32BE=f.prototype.readUInt32BE=a(function(e,t){return e=e>>>0,\nt||q(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])},\"\\\nreadUInt32BE\");f.prototype.readBigUInt64LE=ge(a(function(e){e=e>>>0,Be(e,\"offset\");\nlet t=this[e],n=this[e+7];(t===void 0||n===void 0)&&We(e,this.length-8);let i=t+\nthis[++e]*2**8+this[++e]*2**16+this[++e]*2**24,s=this[++e]+this[++e]*2**8+this[++e]*\n2**16+n*2**24;return BigInt(i)+(BigInt(s)<>>0,Be(e,\"offset\");let t=this[e],n=this[e+7];\n(t===void 0||n===void 0)&&We(e,this.length-8);let i=t*2**24+this[++e]*2**16+this[++e]*\n2**8+this[++e],s=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(\ni)<>>0,t=t>>>0,n||q(e,t,this.length);let i=this[e],s=1,o=0;for(;++o=s&&(i-=Math.pow(2,8*t)),i},\"readIntLE\");f.prototype.\nreadIntBE=a(function(e,t,n){e=e>>>0,t=t>>>0,n||q(e,t,this.length);let i=t,s=1,o=this[e+\n--i];for(;i>0&&(s*=256);)o+=this[e+--i]*s;return s*=128,o>=s&&(o-=Math.pow(2,8*t)),\no},\"readIntBE\");f.prototype.readInt8=a(function(e,t){return e=e>>>0,t||q(e,1,this.\nlength),this[e]&128?(255-this[e]+1)*-1:this[e]},\"readInt8\");f.prototype.readInt16LE=\na(function(e,t){e=e>>>0,t||q(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&\n32768?n|4294901760:n},\"readInt16LE\");f.prototype.readInt16BE=a(function(e,t){e=e>>>\n0,t||q(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n},\n\"readInt16BE\");f.prototype.readInt32LE=a(function(e,t){return e=e>>>0,t||q(e,4,this.\nlength),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},\"readInt32LE\");f.prototype.\nreadInt32BE=a(function(e,t){return e=e>>>0,t||q(e,4,this.length),this[e]<<24|this[e+\n1]<<16|this[e+2]<<8|this[e+3]},\"readInt32BE\");f.prototype.readBigInt64LE=ge(a(function(e){\ne=e>>>0,Be(e,\"offset\");let t=this[e],n=this[e+7];(t===void 0||n===void 0)&&We(e,\nthis.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(\ni)<>>0,Be(e,\"offset\");\nlet t=this[e],n=this[e+7];(t===void 0||n===void 0)&&We(e,this.length-8);let i=(t<<\n24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(i)<>>0,t||q(e,4,this.length),Pe.read(this,e,\n!0,23,4)},\"readFloatLE\");f.prototype.readFloatBE=a(function(e,t){return e=e>>>0,\nt||q(e,4,this.length),Pe.read(this,e,!1,23,4)},\"readFloatBE\");f.prototype.readDoubleLE=\na(function(e,t){return e=e>>>0,t||q(e,8,this.length),Pe.read(this,e,!0,52,8)},\"r\\\neadDoubleLE\");f.prototype.readDoubleBE=a(function(e,t){return e=e>>>0,t||q(e,8,this.\nlength),Pe.read(this,e,!1,52,8)},\"readDoubleBE\");function Y(r,e,t,n,i,s){if(!f.isBuffer(\nr))throw new TypeError('\"buffer\" argument must be a Buffer instance');if(e>i||e<\ns)throw new RangeError('\"value\" argument is out of bounds');if(t+n>r.length)throw new RangeError(\n\"Index out of range\")}a(Y,\"checkInt\");f.prototype.writeUintLE=f.prototype.writeUIntLE=\na(function(e,t,n,i){if(e=+e,t=t>>>0,n=n>>>0,!i){let u=Math.pow(2,8*n)-1;Y(this,e,\nt,n,u,0)}let s=1,o=0;for(this[t]=e&255;++o>>0,n=n>>>0,!i){let u=Math.pow(2,8*n)-1;Y(this,e,t,n,u,0)}let s=n-1,\no=1;for(this[t+s]=e&255;--s>=0&&(o*=256);)this[t+s]=e/o&255;return t+n},\"writeUI\\\nntBE\");f.prototype.writeUint8=f.prototype.writeUInt8=a(function(e,t,n){return e=\n+e,t=t>>>0,n||Y(this,e,t,1,255,0),this[t]=e&255,t+1},\"writeUInt8\");f.prototype.writeUint16LE=\nf.prototype.writeUInt16LE=a(function(e,t,n){return e=+e,t=t>>>0,n||Y(this,e,t,2,\n65535,0),this[t]=e&255,this[t+1]=e>>>8,t+2},\"writeUInt16LE\");f.prototype.writeUint16BE=\nf.prototype.writeUInt16BE=a(function(e,t,n){return e=+e,t=t>>>0,n||Y(this,e,t,2,\n65535,0),this[t]=e>>>8,this[t+1]=e&255,t+2},\"writeUInt16BE\");f.prototype.writeUint32LE=\nf.prototype.writeUInt32LE=a(function(e,t,n){return e=+e,t=t>>>0,n||Y(this,e,t,4,\n4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=e&255,t+\n4},\"writeUInt32LE\");f.prototype.writeUint32BE=f.prototype.writeUInt32BE=a(function(e,t,n){\nreturn e=+e,t=t>>>0,n||Y(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,\nthis[t+2]=e>>>8,this[t+3]=e&255,t+4},\"writeUInt32BE\");function Nn(r,e,t,n,i){Hn(\ne,n,i,r,t,7);let s=Number(e&BigInt(4294967295));r[t++]=s,s=s>>8,r[t++]=s,s=s>>8,\nr[t++]=s,s=s>>8,r[t++]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return r[t++]=\no,o=o>>8,r[t++]=o,o=o>>8,r[t++]=o,o=o>>8,r[t++]=o,t}a(Nn,\"wrtBigUInt64LE\");function qn(r,e,t,n,i){\nHn(e,n,i,r,t,7);let s=Number(e&BigInt(4294967295));r[t+7]=s,s=s>>8,r[t+6]=s,s=s>>\n8,r[t+5]=s,s=s>>8,r[t+4]=s;let o=Number(e>>BigInt(32)&BigInt(4294967295));return r[t+\n3]=o,o=o>>8,r[t+2]=o,o=o>>8,r[t+1]=o,o=o>>8,r[t]=o,t+8}a(qn,\"wrtBigUInt64BE\");f.\nprototype.writeBigUInt64LE=ge(a(function(e,t=0){return Nn(this,e,t,BigInt(0),BigInt(\n\"0xffffffffffffffff\"))},\"writeBigUInt64LE\"));f.prototype.writeBigUInt64BE=ge(a(function(e,t=0){\nreturn qn(this,e,t,BigInt(0),BigInt(\"0xffffffffffffffff\"))},\"writeBigUInt64BE\"));\nf.prototype.writeIntLE=a(function(e,t,n,i){if(e=+e,t=t>>>0,!i){let c=Math.pow(2,\n8*n-1);Y(this,e,t,n,c-1,-c)}let s=0,o=1,u=0;for(this[t]=e&255;++s>0)-u&255;return t+n},\"writeIntL\\\nE\");f.prototype.writeIntBE=a(function(e,t,n,i){if(e=+e,t=t>>>0,!i){let c=Math.pow(\n2,8*n-1);Y(this,e,t,n,c-1,-c)}let s=n-1,o=1,u=0;for(this[t+s]=e&255;--s>=0&&(o*=\n256);)e<0&&u===0&&this[t+s+1]!==0&&(u=1),this[t+s]=(e/o>>0)-u&255;return t+n},\"w\\\nriteIntBE\");f.prototype.writeInt8=a(function(e,t,n){return e=+e,t=t>>>0,n||Y(this,\ne,t,1,127,-128),e<0&&(e=255+e+1),this[t]=e&255,t+1},\"writeInt8\");f.prototype.writeInt16LE=\na(function(e,t,n){return e=+e,t=t>>>0,n||Y(this,e,t,2,32767,-32768),this[t]=e&255,\nthis[t+1]=e>>>8,t+2},\"writeInt16LE\");f.prototype.writeInt16BE=a(function(e,t,n){\nreturn e=+e,t=t>>>0,n||Y(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=e&255,\nt+2},\"writeInt16BE\");f.prototype.writeInt32LE=a(function(e,t,n){return e=+e,t=t>>>\n0,n||Y(this,e,t,4,2147483647,-2147483648),this[t]=e&255,this[t+1]=e>>>8,this[t+2]=\ne>>>16,this[t+3]=e>>>24,t+4},\"writeInt32LE\");f.prototype.writeInt32BE=a(function(e,t,n){\nreturn e=+e,t=t>>>0,n||Y(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+\n1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=e&255,t+4},\"writeIn\\\nt32BE\");f.prototype.writeBigInt64LE=ge(a(function(e,t=0){return Nn(this,e,t,-BigInt(\n\"0x8000000000000000\"),BigInt(\"0x7fffffffffffffff\"))},\"writeBigInt64LE\"));f.prototype.\nwriteBigInt64BE=ge(a(function(e,t=0){return qn(this,e,t,-BigInt(\"0x8000000000000\\\n000\"),BigInt(\"0x7fffffffffffffff\"))},\"writeBigInt64BE\"));function Qn(r,e,t,n,i,s){\nif(t+n>r.length)throw new RangeError(\"Index out of range\");if(t<0)throw new RangeError(\n\"Index out of range\")}a(Qn,\"checkIEEE754\");function Wn(r,e,t,n,i){return e=+e,t=\nt>>>0,i||Qn(r,e,t,4,34028234663852886e22,-34028234663852886e22),Pe.write(r,e,t,n,\n23,4),t+4}a(Wn,\"writeFloat\");f.prototype.writeFloatLE=a(function(e,t,n){return Wn(\nthis,e,t,!0,n)},\"writeFloatLE\");f.prototype.writeFloatBE=a(function(e,t,n){return Wn(\nthis,e,t,!1,n)},\"writeFloatBE\");function jn(r,e,t,n,i){return e=+e,t=t>>>0,i||Qn(\nr,e,t,8,17976931348623157e292,-17976931348623157e292),Pe.write(r,e,t,n,52,8),t+8}\na(jn,\"writeDouble\");f.prototype.writeDoubleLE=a(function(e,t,n){return jn(this,e,\nt,!0,n)},\"writeDoubleLE\");f.prototype.writeDoubleBE=a(function(e,t,n){return jn(\nthis,e,t,!1,n)},\"writeDoubleBE\");f.prototype.copy=a(function(e,t,n,i){if(!f.isBuffer(\ne))throw new TypeError(\"argument should be a Buffer\");if(n||(n=0),!i&&i!==0&&(i=\nthis.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError(\"Index out of range\");if(i<0)throw new RangeError(\n\"sourceEnd out of bounds\");i>this.length&&(i=this.length),e.length-t>>0,\nn=n===void 0?this.length:n>>>0,e||(e=0);let s;if(typeof e==\"number\")for(s=t;s2**32?i=Fn(String(t)):typeof t==\"bigint\"&&(i=String(t),\n(t>BigInt(2)**BigInt(32)||t<-(BigInt(2)**BigInt(32)))&&(i=Fn(i)),i+=\"n\"),n+=` It\\\n must be ${e}. Received ${i}`,n},RangeError);function Fn(r){let e=\"\",t=r.length,\nn=r[0]===\"-\"?1:0;for(;t>=n+4;t-=3)e=`_${r.slice(t-3,t)}${e}`;return`${r.slice(0,\nt)}${e}`}a(Fn,\"addNumericalSeparator\");function Fo(r,e,t){Be(e,\"offset\"),(r[e]===\nvoid 0||r[e+t]===void 0)&&We(e,r.length-(t+1))}a(Fo,\"checkBounds\");function Hn(r,e,t,n,i,s){\nif(r>t||r3?e===0||e===BigInt(0)?u=\n`>= 0${o} and < 2${o} ** ${(s+1)*8}${o}`:u=`>= -(2${o} ** ${(s+1)*8-1}${o}) and \\\n< 2 ** ${(s+1)*8-1}${o}`:u=`>= ${e}${o} and <= ${t}${o}`,new Ie.ERR_OUT_OF_RANGE(\n\"value\",u,r)}Fo(n,i,s)}a(Hn,\"checkIntBI\");function Be(r,e){if(typeof r!=\"number\")\nthrow new Ie.ERR_INVALID_ARG_TYPE(e,\"number\",r)}a(Be,\"validateNumber\");function We(r,e,t){\nthrow Math.floor(r)!==r?(Be(r,t),new Ie.ERR_OUT_OF_RANGE(t||\"offset\",\"an integer\",\nr)):e<0?new Ie.ERR_BUFFER_OUT_OF_BOUNDS:new Ie.ERR_OUT_OF_RANGE(t||\"offset\",`>= ${t?\n1:0} and <= ${e}`,r)}a(We,\"boundsError\");var Mo=/[^+/0-9A-Za-z-_]/g;function Do(r){\nif(r=r.split(\"=\")[0],r=r.trim().replace(Mo,\"\"),r.length<2)return\"\";for(;r.length%\n4!==0;)r=r+\"=\";return r}a(Do,\"base64clean\");function Mt(r,e){e=e||1/0;let t,n=r.\nlength,i=null,s=[];for(let o=0;o55295&&t<57344){if(!i){\nif(t>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(o+1===n){(e-=3)>-1&&\ns.push(239,191,189);continue}i=t;continue}if(t<56320){(e-=3)>-1&&s.push(239,191,\n189),i=t;continue}t=(i-55296<<10|t-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,\n189);if(i=null,t<128){if((e-=1)<0)break;s.push(t)}else if(t<2048){if((e-=2)<0)break;\ns.push(t>>6|192,t&63|128)}else if(t<65536){if((e-=3)<0)break;s.push(t>>12|224,t>>\n6&63|128,t&63|128)}else if(t<1114112){if((e-=4)<0)break;s.push(t>>18|240,t>>12&63|\n128,t>>6&63|128,t&63|128)}else throw new Error(\"Invalid code point\")}return s}a(\nMt,\"utf8ToBytes\");function ko(r){let e=[];for(let t=0;t>8,i=t%256,s.push(i),s.push(n);return s}\na(Uo,\"utf16leToBytes\");function Gn(r){return Lt.toByteArray(Do(r))}a(Gn,\"base64T\\\noBytes\");function st(r,e,t,n){let i;for(i=0;i=e.length||i>=r.length);++i)\ne[i+t]=r[i];return i}a(st,\"blitBuffer\");function ue(r,e){return r instanceof e||\nr!=null&&r.constructor!=null&&r.constructor.name!=null&&r.constructor.name===e.name}\na(ue,\"isInstance\");function Ot(r){return r!==r}a(Ot,\"numberIsNaN\");var Oo=function(){\nlet r=\"0123456789abcdef\",e=new Array(256);for(let t=0;t<16;++t){let n=t*16;for(let i=0;i<\n16;++i)e[n+i]=r[t]+r[i]}return e}();function ge(r){return typeof BigInt>\"u\"?No:r}\na(ge,\"defineBigIntMethod\");function No(){throw new Error(\"BigInt not supported\")}\na(No,\"BufferBigIntNotDefined\")});var S,x,v,g,y,m,p=z(()=>{\"use strict\";S=globalThis,x=globalThis.setImmediate??(r=>setTimeout(\nr,0)),v=globalThis.clearImmediate??(r=>clearTimeout(r)),g=globalThis.crypto??{};\ng.subtle??(g.subtle={});y=typeof globalThis.Buffer==\"function\"&&typeof globalThis.\nBuffer.allocUnsafe==\"function\"?globalThis.Buffer:$n().Buffer,m=globalThis.process??\n{};m.env??(m.env={});try{m.nextTick(()=>{})}catch{let e=Promise.resolve();m.nextTick=\ne.then.bind(e)}});var we=I((Xc,Nt)=>{\"use strict\";p();var Re=typeof Reflect==\"object\"?Reflect:null,\nVn=Re&&typeof Re.apply==\"function\"?Re.apply:a(function(e,t,n){return Function.prototype.\napply.call(e,t,n)},\"ReflectApply\"),ot;Re&&typeof Re.ownKeys==\"function\"?ot=Re.ownKeys:\nObject.getOwnPropertySymbols?ot=a(function(e){return Object.getOwnPropertyNames(\ne).concat(Object.getOwnPropertySymbols(e))},\"ReflectOwnKeys\"):ot=a(function(e){return Object.\ngetOwnPropertyNames(e)},\"ReflectOwnKeys\");function qo(r){console&&console.warn&&\nconsole.warn(r)}a(qo,\"ProcessEmitWarning\");var zn=Number.isNaN||a(function(e){return e!==\ne},\"NumberIsNaN\");function L(){L.init.call(this)}a(L,\"EventEmitter\");Nt.exports=\nL;Nt.exports.once=Ho;L.EventEmitter=L;L.prototype._events=void 0;L.prototype._eventsCount=\n0;L.prototype._maxListeners=void 0;var Kn=10;function at(r){if(typeof r!=\"functi\\\non\")throw new TypeError('The \"listener\" argument must be of type Function. Recei\\\nved type '+typeof r)}a(at,\"checkListener\");Object.defineProperty(L,\"defaultMaxLi\\\nsteners\",{enumerable:!0,get:a(function(){return Kn},\"get\"),set:a(function(r){if(typeof r!=\n\"number\"||r<0||zn(r))throw new RangeError('The value of \"defaultMaxListeners\" is\\\n out of range. It must be a non-negative number. Received '+r+\".\");Kn=r},\"set\")});\nL.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this).\n_events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=\nthis._maxListeners||void 0};L.prototype.setMaxListeners=a(function(e){if(typeof e!=\n\"number\"||e<0||zn(e))throw new RangeError('The value of \"n\" is out of range. It \\\nmust be a non-negative number. Received '+e+\".\");return this._maxListeners=e,this},\n\"setMaxListeners\");function Yn(r){return r._maxListeners===void 0?L.defaultMaxListeners:\nr._maxListeners}a(Yn,\"_getMaxListeners\");L.prototype.getMaxListeners=a(function(){\nreturn Yn(this)},\"getMaxListeners\");L.prototype.emit=a(function(e){for(var t=[],\nn=1;n\n0&&(o=t[0]),o instanceof Error)throw o;var u=new Error(\"Unhandled error.\"+(o?\" (\"+\no.message+\")\":\"\"));throw u.context=o,u}var c=s[e];if(c===void 0)return!1;if(typeof c==\n\"function\")Vn(c,this,t);else for(var h=c.length,l=ti(c,h),n=0;n0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error(\"Po\\\nssible EventEmitter memory leak detected. \"+o.length+\" \"+String(e)+\" listeners a\\\ndded. Use emitter.setMaxListeners() to increase limit\");u.name=\"MaxListenersExce\\\nededWarning\",u.emitter=r,u.type=e,u.count=o.length,qo(u)}return r}a(Zn,\"_addList\\\nener\");L.prototype.addListener=a(function(e,t){return Zn(this,e,t,!1)},\"addListe\\\nner\");L.prototype.on=L.prototype.addListener;L.prototype.prependListener=a(function(e,t){\nreturn Zn(this,e,t,!0)},\"prependListener\");function Qo(){if(!this.fired)return this.\ntarget.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?\nthis.listener.call(this.target):this.listener.apply(this.target,arguments)}a(Qo,\n\"onceWrapper\");function Jn(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,\nlistener:t},i=Qo.bind(n);return i.listener=t,n.wrapFn=i,i}a(Jn,\"_onceWrap\");L.prototype.\nonce=a(function(e,t){return at(t),this.on(e,Jn(this,e,t)),this},\"once\");L.prototype.\nprependOnceListener=a(function(e,t){return at(t),this.prependListener(e,Jn(this,\ne,t)),this},\"prependOnceListener\");L.prototype.removeListener=a(function(e,t){var n,\ni,s,o,u;if(at(t),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;\nif(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):\n(delete i[e],i.removeListener&&this.emit(\"removeListener\",e,n.listener||t));else if(typeof n!=\n\"function\"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){u=n[o].\nlistener,s=o;break}if(s<0)return this;s===0?n.shift():Wo(n,s),n.length===1&&(i[e]=\nn[0]),i.removeListener!==void 0&&this.emit(\"removeListener\",e,u||t)}return this},\n\"removeListener\");L.prototype.off=L.prototype.removeListener;L.prototype.removeAllListeners=\na(function(e){var t,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===\nvoid 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=\n0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),\nthis;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i=0;i--)this.removeListener(e,t[i]);return this},\"removeAllListeners\");function Xn(r,e,t){\nvar n=r._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i==\n\"function\"?t?[i.listener||i]:[i]:t?jo(i):ti(i,i.length)}a(Xn,\"_listeners\");L.prototype.\nlisteners=a(function(e){return Xn(this,e,!0)},\"listeners\");L.prototype.rawListeners=\na(function(e){return Xn(this,e,!1)},\"rawListeners\");L.listenerCount=function(r,e){\nreturn typeof r.listenerCount==\"function\"?r.listenerCount(e):ei.call(r,e)};L.prototype.\nlistenerCount=ei;function ei(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t==\n\"function\")return 1;if(t!==void 0)return t.length}return 0}a(ei,\"listenerCount\");\nL.prototype.eventNames=a(function(){return this._eventsCount>0?ot(this._events):\n[]},\"eventNames\");function ti(r,e){for(var t=new Array(e),n=0;n$o});var $o,He=z(()=>{\"use strict\";p();$o={}});function Ge(r){let e=1779033703,t=3144134277,n=1013904242,i=2773480762,s=1359893119,\no=2600822924,u=528734635,c=1541459225,h=0,l=0,d=[1116352408,1899447441,3049323471,\n3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,\n1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,\n604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,\n3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,\n1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,\n3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,\n883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,\n2361852424,2428436474,2756734187,3204031479,3329325298],b=a((A,w)=>A>>>w|A<<32-w,\n\"rrot\"),C=new Uint32Array(64),B=new Uint8Array(64),W=a(()=>{for(let R=0,G=0;R<16;R++,\nG+=4)C[R]=B[G]<<24|B[G+1]<<16|B[G+2]<<8|B[G+3];for(let R=16;R<64;R++){let G=b(C[R-\n15],7)^b(C[R-15],18)^C[R-15]>>>3,he=b(C[R-2],17)^b(C[R-2],19)^C[R-2]>>>10;C[R]=C[R-\n16]+G+C[R-7]+he|0}let A=e,w=t,P=n,V=i,k=s,j=o,ce=u,ee=c;for(let R=0;R<64;R++){let G=b(\nk,6)^b(k,11)^b(k,25),he=k&j^~k&ce,ye=ee+G+he+d[R]+C[R]|0,xe=b(A,2)^b(A,13)^b(A,22),\nme=A&w^A&P^w&P,se=xe+me|0;ee=ce,ce=j,j=k,k=V+ye|0,V=P,P=w,w=A,A=ye+se|0}e=e+A|0,\nt=t+w|0,n=n+P|0,i=i+V|0,s=s+k|0,o=o+j|0,u=u+ce|0,c=c+ee|0,l=0},\"process\"),X=a(A=>{\ntypeof A==\"string\"&&(A=new TextEncoder().encode(A));for(let w=0;w{if(B[l++]=128,l==64&&W(),l+8>64){\nfor(;l<64;)B[l++]=0;W()}for(;l<58;)B[l++]=0;let A=h*8;B[l++]=A/1099511627776&255,\nB[l++]=A/4294967296&255,B[l++]=A>>>24,B[l++]=A>>>16&255,B[l++]=A>>>8&255,B[l++]=\nA&255,W();let w=new Uint8Array(32);return w[0]=e>>>24,w[1]=e>>>16&255,w[2]=e>>>8&\n255,w[3]=e&255,w[4]=t>>>24,w[5]=t>>>16&255,w[6]=t>>>8&255,w[7]=t&255,w[8]=n>>>24,\nw[9]=n>>>16&255,w[10]=n>>>8&255,w[11]=n&255,w[12]=i>>>24,w[13]=i>>>16&255,w[14]=\ni>>>8&255,w[15]=i&255,w[16]=s>>>24,w[17]=s>>>16&255,w[18]=s>>>8&255,w[19]=s&255,\nw[20]=o>>>24,w[21]=o>>>16&255,w[22]=o>>>8&255,w[23]=o&255,w[24]=u>>>24,w[25]=u>>>\n16&255,w[26]=u>>>8&255,w[27]=u&255,w[28]=c>>>24,w[29]=c>>>16&255,w[30]=c>>>8&255,\nw[31]=c&255,w},\"digest\");return r===void 0?{add:X,digest:de}:(X(r),de())}var ni=z(\n()=>{\"use strict\";p();a(Ge,\"sha256\")});var O,$e,ii=z(()=>{\"use strict\";p();O=class O{constructor(){_(this,\"_dataLength\",\n0);_(this,\"_bufferLength\",0);_(this,\"_state\",new Int32Array(4));_(this,\"_buffer\",\nnew ArrayBuffer(68));_(this,\"_buffer8\");_(this,\"_buffer32\");this._buffer8=new Uint8Array(\nthis._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashByteArray(e,t=!1){\nreturn this.onePassHasher.start().appendByteArray(e).end(t)}static hashStr(e,t=!1){\nreturn this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){\nreturn this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){let t=O.\nhexChars,n=O.hexOut,i,s,o,u;for(u=0;u<4;u+=1)for(s=u*8,i=e[u],o=0;o<8;o+=2)n[s+1+\no]=t.charAt(i&15),i>>>=4,n[s+0+o]=t.charAt(i&15),i>>>=4;return n.join(\"\")}static _md5cycle(e,t){\nlet n=e[0],i=e[1],s=e[2],o=e[3];n+=(i&s|~i&o)+t[0]-680876936|0,n=(n<<7|n>>>25)+i|\n0,o+=(n&i|~n&s)+t[1]-389564586|0,o=(o<<12|o>>>20)+n|0,s+=(o&n|~o&i)+t[2]+606105819|\n0,s=(s<<17|s>>>15)+o|0,i+=(s&o|~s&n)+t[3]-1044525330|0,i=(i<<22|i>>>10)+s|0,n+=(i&\ns|~i&o)+t[4]-176418897|0,n=(n<<7|n>>>25)+i|0,o+=(n&i|~n&s)+t[5]+1200080426|0,o=(o<<\n12|o>>>20)+n|0,s+=(o&n|~o&i)+t[6]-1473231341|0,s=(s<<17|s>>>15)+o|0,i+=(s&o|~s&n)+\nt[7]-45705983|0,i=(i<<22|i>>>10)+s|0,n+=(i&s|~i&o)+t[8]+1770035416|0,n=(n<<7|n>>>\n25)+i|0,o+=(n&i|~n&s)+t[9]-1958414417|0,o=(o<<12|o>>>20)+n|0,s+=(o&n|~o&i)+t[10]-\n42063|0,s=(s<<17|s>>>15)+o|0,i+=(s&o|~s&n)+t[11]-1990404162|0,i=(i<<22|i>>>10)+s|\n0,n+=(i&s|~i&o)+t[12]+1804603682|0,n=(n<<7|n>>>25)+i|0,o+=(n&i|~n&s)+t[13]-40341101|\n0,o=(o<<12|o>>>20)+n|0,s+=(o&n|~o&i)+t[14]-1502002290|0,s=(s<<17|s>>>15)+o|0,i+=\n(s&o|~s&n)+t[15]+1236535329|0,i=(i<<22|i>>>10)+s|0,n+=(i&o|s&~o)+t[1]-165796510|\n0,n=(n<<5|n>>>27)+i|0,o+=(n&s|i&~s)+t[6]-1069501632|0,o=(o<<9|o>>>23)+n|0,s+=(o&\ni|n&~i)+t[11]+643717713|0,s=(s<<14|s>>>18)+o|0,i+=(s&n|o&~n)+t[0]-373897302|0,i=\n(i<<20|i>>>12)+s|0,n+=(i&o|s&~o)+t[5]-701558691|0,n=(n<<5|n>>>27)+i|0,o+=(n&s|i&\n~s)+t[10]+38016083|0,o=(o<<9|o>>>23)+n|0,s+=(o&i|n&~i)+t[15]-660478335|0,s=(s<<14|\ns>>>18)+o|0,i+=(s&n|o&~n)+t[4]-405537848|0,i=(i<<20|i>>>12)+s|0,n+=(i&o|s&~o)+t[9]+\n568446438|0,n=(n<<5|n>>>27)+i|0,o+=(n&s|i&~s)+t[14]-1019803690|0,o=(o<<9|o>>>23)+\nn|0,s+=(o&i|n&~i)+t[3]-187363961|0,s=(s<<14|s>>>18)+o|0,i+=(s&n|o&~n)+t[8]+1163531501|\n0,i=(i<<20|i>>>12)+s|0,n+=(i&o|s&~o)+t[13]-1444681467|0,n=(n<<5|n>>>27)+i|0,o+=(n&\ns|i&~s)+t[2]-51403784|0,o=(o<<9|o>>>23)+n|0,s+=(o&i|n&~i)+t[7]+1735328473|0,s=(s<<\n14|s>>>18)+o|0,i+=(s&n|o&~n)+t[12]-1926607734|0,i=(i<<20|i>>>12)+s|0,n+=(i^s^o)+\nt[5]-378558|0,n=(n<<4|n>>>28)+i|0,o+=(n^i^s)+t[8]-2022574463|0,o=(o<<11|o>>>21)+\nn|0,s+=(o^n^i)+t[11]+1839030562|0,s=(s<<16|s>>>16)+o|0,i+=(s^o^n)+t[14]-35309556|\n0,i=(i<<23|i>>>9)+s|0,n+=(i^s^o)+t[1]-1530992060|0,n=(n<<4|n>>>28)+i|0,o+=(n^i^s)+\nt[4]+1272893353|0,o=(o<<11|o>>>21)+n|0,s+=(o^n^i)+t[7]-155497632|0,s=(s<<16|s>>>\n16)+o|0,i+=(s^o^n)+t[10]-1094730640|0,i=(i<<23|i>>>9)+s|0,n+=(i^s^o)+t[13]+681279174|\n0,n=(n<<4|n>>>28)+i|0,o+=(n^i^s)+t[0]-358537222|0,o=(o<<11|o>>>21)+n|0,s+=(o^n^i)+\nt[3]-722521979|0,s=(s<<16|s>>>16)+o|0,i+=(s^o^n)+t[6]+76029189|0,i=(i<<23|i>>>9)+\ns|0,n+=(i^s^o)+t[9]-640364487|0,n=(n<<4|n>>>28)+i|0,o+=(n^i^s)+t[12]-421815835|0,\no=(o<<11|o>>>21)+n|0,s+=(o^n^i)+t[15]+530742520|0,s=(s<<16|s>>>16)+o|0,i+=(s^o^n)+\nt[2]-995338651|0,i=(i<<23|i>>>9)+s|0,n+=(s^(i|~o))+t[0]-198630844|0,n=(n<<6|n>>>\n26)+i|0,o+=(i^(n|~s))+t[7]+1126891415|0,o=(o<<10|o>>>22)+n|0,s+=(n^(o|~i))+t[14]-\n1416354905|0,s=(s<<15|s>>>17)+o|0,i+=(o^(s|~n))+t[5]-57434055|0,i=(i<<21|i>>>11)+\ns|0,n+=(s^(i|~o))+t[12]+1700485571|0,n=(n<<6|n>>>26)+i|0,o+=(i^(n|~s))+t[3]-1894986606|\n0,o=(o<<10|o>>>22)+n|0,s+=(n^(o|~i))+t[10]-1051523|0,s=(s<<15|s>>>17)+o|0,i+=(o^\n(s|~n))+t[1]-2054922799|0,i=(i<<21|i>>>11)+s|0,n+=(s^(i|~o))+t[8]+1873313359|0,n=\n(n<<6|n>>>26)+i|0,o+=(i^(n|~s))+t[15]-30611744|0,o=(o<<10|o>>>22)+n|0,s+=(n^(o|~i))+\nt[6]-1560198380|0,s=(s<<15|s>>>17)+o|0,i+=(o^(s|~n))+t[13]+1309151649|0,i=(i<<21|\ni>>>11)+s|0,n+=(s^(i|~o))+t[4]-145523070|0,n=(n<<6|n>>>26)+i|0,o+=(i^(n|~s))+t[11]-\n1120210379|0,o=(o<<10|o>>>22)+n|0,s+=(n^(o|~i))+t[2]+718787259|0,s=(s<<15|s>>>17)+\no|0,i+=(o^(s|~n))+t[9]-343485551|0,i=(i<<21|i>>>11)+s|0,e[0]=n+e[0]|0,e[1]=i+e[1]|\n0,e[2]=s+e[2]|0,e[3]=o+e[3]|0}start(){return this._dataLength=0,this._bufferLength=\n0,this._state.set(O.stateIdentity),this}appendStr(e){let t=this._buffer8,n=this.\n_buffer32,i=this._bufferLength,s,o;for(o=0;o>>6)+192,t[i++]=s&63|128;else if(s<55296||\ns>56319)t[i++]=(s>>>12)+224,t[i++]=s>>>6&63|128,t[i++]=s&63|128;else{if(s=(s-55296)*\n1024+(e.charCodeAt(++o)-56320)+65536,s>1114111)throw new Error(\"Unicode standard\\\n supports code points up to U+10FFFF\");t[i++]=(s>>>18)+240,t[i++]=s>>>12&63|128,\nt[i++]=s>>>6&63|128,t[i++]=s&63|128}i>=64&&(this._dataLength+=64,O._md5cycle(this.\n_state,n),i-=64,n[0]=n[16])}return this._bufferLength=i,this}appendAsciiStr(e){let t=this.\n_buffer8,n=this._buffer32,i=this._bufferLength,s,o=0;for(;;){for(s=Math.min(e.length-\no,64-i);s--;)t[i++]=e.charCodeAt(o++);if(i<64)break;this._dataLength+=64,O._md5cycle(\nthis._state,n),i=0}return this._bufferLength=i,this}appendByteArray(e){let t=this.\n_buffer8,n=this._buffer32,i=this._bufferLength,s,o=0;for(;;){for(s=Math.min(e.length-\no,64-i);s--;)t[i++]=e[o++];if(i<64)break;this._dataLength+=64,O._md5cycle(this._state,\nn),i=0}return this._bufferLength=i,this}getState(){let e=this._state;return{buffer:String.\nfromCharCode.apply(null,Array.from(this._buffer8)),buflen:this._bufferLength,length:this.\n_dataLength,state:[e[0],e[1],e[2],e[3]]}}setState(e){let t=e.buffer,n=e.state,i=this.\n_state,s;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=n[0],i[1]=\nn[1],i[2]=n[2],i[3]=n[3],s=0;s>2)+1;this._dataLength+=\nt;let o=this._dataLength*8;if(n[t]=128,n[t+1]=n[t+2]=n[t+3]=0,i.set(O.buffer32Identity.\nsubarray(s),s),t>55&&(O._md5cycle(this._state,i),i.set(O.buffer32Identity)),o<=4294967295)\ni[14]=o;else{let u=o.toString(16).match(/(.*?)(.{0,8})$/);if(u===null)return;let c=parseInt(\nu[2],16),h=parseInt(u[1],16)||0;i[14]=c,i[15]=h}return O._md5cycle(this._state,i),\ne?this._state:O._hex(this._state)}};a(O,\"Md5\"),_(O,\"stateIdentity\",new Int32Array(\n[1732584193,-271733879,-1732584194,271733878])),_(O,\"buffer32Identity\",new Int32Array(\n[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])),_(O,\"hexChars\",\"0123456789abcdef\"),_(O,\"hexO\\\nut\",[]),_(O,\"onePassHasher\",new O);$e=O});var qt={};ie(qt,{createHash:()=>Ko,createHmac:()=>zo,randomBytes:()=>Vo});function Vo(r){\nreturn g.getRandomValues(y.alloc(r))}function Ko(r){if(r===\"sha256\")return{update:a(\nfunction(e){return{digest:a(function(){return y.from(Ge(e))},\"digest\")}},\"update\")};\nif(r===\"md5\")return{update:a(function(e){return{digest:a(function(){return typeof e==\n\"string\"?$e.hashStr(e):$e.hashByteArray(e)},\"digest\")}},\"update\")};throw new Error(\n`Hash type '${r}' not supported`)}function zo(r,e){if(r!==\"sha256\")throw new Error(\n`Only sha256 is supported (requested: '${r}')`);return{update:a(function(t){return{\ndigest:a(function(){typeof e==\"string\"&&(e=new TextEncoder().encode(e)),typeof t==\n\"string\"&&(t=new TextEncoder().encode(t));let n=e.length;if(n>64)e=Ge(e);else if(n<\n64){let c=new Uint8Array(64);c.set(e),e=c}let i=new Uint8Array(64),s=new Uint8Array(\n64);for(let c=0;c<64;c++)i[c]=54^e[c],s[c]=92^e[c];let o=new Uint8Array(t.length+\n64);o.set(i,0),o.set(t,64);let u=new Uint8Array(96);return u.set(s,0),u.set(Ge(o),\n64),y.from(Ge(u))},\"digest\")}},\"update\")}}var Qt=z(()=>{\"use strict\";p();ni();ii();\na(Vo,\"randomBytes\");a(Ko,\"createHash\");a(zo,\"createHmac\")});var jt=I(si=>{\"use strict\";p();si.parse=function(r,e){return new Wt(r,e).parse()};\nvar ut=class ut{constructor(e,t){this.source=e,this.transform=t||Yo,this.position=\n0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=\nthis.source.length}nextCharacter(){var e=this.source[this.position++];return e===\n\"\\\\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){\nthis.recorded.push(e)}newEntry(e){var t;(this.recorded.length>0||e)&&(t=this.recorded.\njoin(\"\"),t===\"NULL\"&&!e&&(t=null),t!==null&&(t=this.transform(t)),this.entries.push(\nt),this.recorded=[])}consumeDimensions(){if(this.source[0]===\"[\")for(;!this.isEof();){\nvar e=this.nextCharacter();if(e.value===\"=\")break}}parse(e){var t,n,i;for(this.consumeDimensions();!this.\nisEof();)if(t=this.nextCharacter(),t.value===\"{\"&&!i)this.dimension++,this.dimension>\n1&&(n=new ut(this.source.substr(this.position-1),this.transform),this.entries.push(\nn.parse(!0)),this.position+=n.position-2);else if(t.value===\"}\"&&!i){if(this.dimension--,\n!this.dimension&&(this.newEntry(),e))return this.entries}else t.value==='\"'&&!t.\nescaped?(i&&this.newEntry(!0),i=!i):t.value===\",\"&&!i?this.newEntry():this.record(\nt.value);if(this.dimension!==0)throw new Error(\"array dimension not balanced\");return this.\nentries}};a(ut,\"ArrayParser\");var Wt=ut;function Yo(r){return r}a(Yo,\"identity\")});var Ht=I((mh,oi)=>{p();var Zo=jt();oi.exports={create:a(function(r,e){return{parse:a(\nfunction(){return Zo.parse(r,e)},\"parse\")}},\"create\")}});var ci=I((bh,ui)=>{\"use strict\";p();var Jo=/(\\d{1,})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})(\\.\\d{1,})?.*?( BC)?$/,\nXo=/^(\\d{1,})-(\\d{2})-(\\d{2})( BC)?$/,ea=/([Z+-])(\\d{2})?:?(\\d{2})?:?(\\d{2})?/,ta=/^-?infinity$/;\nui.exports=a(function(e){if(ta.test(e))return Number(e.replace(\"i\",\"I\"));var t=Jo.\nexec(e);if(!t)return ra(e)||null;var n=!!t[8],i=parseInt(t[1],10);n&&(i=ai(i));var s=parseInt(\nt[2],10)-1,o=t[3],u=parseInt(t[4],10),c=parseInt(t[5],10),h=parseInt(t[6],10),l=t[7];\nl=l?1e3*parseFloat(l):0;var d,b=na(e);return b!=null?(d=new Date(Date.UTC(i,s,o,\nu,c,h,l)),Gt(i)&&d.setUTCFullYear(i),b!==0&&d.setTime(d.getTime()-b)):(d=new Date(\ni,s,o,u,c,h,l),Gt(i)&&d.setFullYear(i)),d},\"parseDate\");function ra(r){var e=Xo.\nexec(r);if(e){var t=parseInt(e[1],10),n=!!e[4];n&&(t=ai(t));var i=parseInt(e[2],\n10)-1,s=e[3],o=new Date(t,i,s);return Gt(t)&&o.setFullYear(t),o}}a(ra,\"getDate\");\nfunction na(r){if(r.endsWith(\"+00\"))return 0;var e=ea.exec(r.split(\" \")[1]);if(e){\nvar t=e[1];if(t===\"Z\")return 0;var n=t===\"-\"?-1:1,i=parseInt(e[2],10)*3600+parseInt(\ne[3]||0,10)*60+parseInt(e[4]||0,10);return i*n*1e3}}a(na,\"timeZoneOffset\");function ai(r){\nreturn-(r-1)}a(ai,\"bcYearToNegativeYear\");function Gt(r){return r>=0&&r<100}a(Gt,\n\"is0To99\")});var li=I((vh,hi)=>{p();hi.exports=sa;var ia=Object.prototype.hasOwnProperty;function sa(r){\nfor(var e=1;e{\"use strict\";p();var oa=li();pi.exports=Fe;function Fe(r){if(!(this instanceof\nFe))return new Fe(r);oa(this,wa(r))}a(Fe,\"PostgresInterval\");var aa=[\"seconds\",\"\\\nminutes\",\"hours\",\"days\",\"months\",\"years\"];Fe.prototype.toPostgres=function(){var r=aa.\nfilter(this.hasOwnProperty,this);return this.milliseconds&&r.indexOf(\"seconds\")<\n0&&r.push(\"seconds\"),r.length===0?\"0\":r.map(function(e){var t=this[e]||0;return e===\n\"seconds\"&&this.milliseconds&&(t=(t+this.milliseconds/1e3).toFixed(6).replace(/\\.?0+$/,\n\"\")),t+\" \"+e},this).join(\" \")};var ua={years:\"Y\",months:\"M\",days:\"D\",hours:\"H\",minutes:\"\\\nM\",seconds:\"S\"},ca=[\"years\",\"months\",\"days\"],ha=[\"hours\",\"minutes\",\"seconds\"];Fe.\nprototype.toISOString=Fe.prototype.toISO=function(){var r=ca.map(t,this).join(\"\"),\ne=ha.map(t,this).join(\"\");return\"P\"+r+\"T\"+e;function t(n){var i=this[n]||0;return n===\n\"seconds\"&&this.milliseconds&&(i=(i+this.milliseconds/1e3).toFixed(6).replace(/0+$/,\n\"\")),i+ua[n]}};var $t=\"([+-]?\\\\d+)\",la=$t+\"\\\\s+years?\",fa=$t+\"\\\\s+mons?\",pa=$t+\"\\\n\\\\s+days?\",da=\"([+-])?([\\\\d]*):(\\\\d\\\\d):(\\\\d\\\\d)\\\\.?(\\\\d{1,6})?\",ya=new RegExp([\nla,fa,pa,da].map(function(r){return\"(\"+r+\")?\"}).join(\"\\\\s*\")),fi={years:2,months:4,\ndays:6,hours:9,minutes:10,seconds:11,milliseconds:12},ma=[\"hours\",\"minutes\",\"sec\\\nonds\",\"milliseconds\"];function ga(r){var e=r+\"000000\".slice(r.length);return parseInt(\ne,10)/1e3}a(ga,\"parseMilliseconds\");function wa(r){if(!r)return{};var e=ya.exec(\nr),t=e[8]===\"-\";return Object.keys(fi).reduce(function(n,i){var s=fi[i],o=e[s];return!o||\n(o=i===\"milliseconds\"?ga(o):parseInt(o,10),!o)||(t&&~ma.indexOf(i)&&(o*=-1),n[i]=\no),n},{})}a(wa,\"parse\")});var mi=I((Ih,yi)=>{\"use strict\";p();yi.exports=a(function(e){if(/^\\\\x/.test(e))return new y(\ne.substr(2),\"hex\");for(var t=\"\",n=0;n{p();var Ve=jt(),Ke=Ht(),ct=ci(),wi=di(),bi=mi();function ht(r){\nreturn a(function(t){return t===null?t:r(t)},\"nullAllowed\")}a(ht,\"allowNull\");function Si(r){\nreturn r===null?r:r===\"TRUE\"||r===\"t\"||r===\"true\"||r===\"y\"||r===\"yes\"||r===\"on\"||\nr===\"1\"}a(Si,\"parseBool\");function ba(r){return r?Ve.parse(r,Si):null}a(ba,\"pars\\\neBoolArray\");function Sa(r){return parseInt(r,10)}a(Sa,\"parseBaseTenInt\");function Vt(r){\nreturn r?Ve.parse(r,ht(Sa)):null}a(Vt,\"parseIntegerArray\");function xa(r){return r?\nVe.parse(r,ht(function(e){return xi(e).trim()})):null}a(xa,\"parseBigIntegerArray\");\nvar va=a(function(r){if(!r)return null;var e=Ke.create(r,function(t){return t!==\nnull&&(t=Zt(t)),t});return e.parse()},\"parsePointArray\"),Kt=a(function(r){if(!r)\nreturn null;var e=Ke.create(r,function(t){return t!==null&&(t=parseFloat(t)),t});\nreturn e.parse()},\"parseFloatArray\"),re=a(function(r){if(!r)return null;var e=Ke.\ncreate(r);return e.parse()},\"parseStringArray\"),zt=a(function(r){if(!r)return null;\nvar e=Ke.create(r,function(t){return t!==null&&(t=ct(t)),t});return e.parse()},\"\\\nparseDateArray\"),Ea=a(function(r){if(!r)return null;var e=Ke.create(r,function(t){\nreturn t!==null&&(t=wi(t)),t});return e.parse()},\"parseIntervalArray\"),_a=a(function(r){\nreturn r?Ve.parse(r,ht(bi)):null},\"parseByteAArray\"),Yt=a(function(r){return parseInt(\nr,10)},\"parseInteger\"),xi=a(function(r){var e=String(r);return/^\\d+$/.test(e)?e:\nr},\"parseBigInteger\"),gi=a(function(r){return r?Ve.parse(r,ht(JSON.parse)):null},\n\"parseJsonArray\"),Zt=a(function(r){return r[0]!==\"(\"?null:(r=r.substring(1,r.length-\n1).split(\",\"),{x:parseFloat(r[0]),y:parseFloat(r[1])})},\"parsePoint\"),Aa=a(function(r){\nif(r[0]!==\"<\"&&r[1]!==\"(\")return null;for(var e=\"(\",t=\"\",n=!1,i=2;i{\"use strict\";p();var Z=1e6;function Ta(r){var e=r.readInt32BE(\n0),t=r.readUInt32BE(4),n=\"\";e<0&&(e=~e+(t===0),t=~t+1>>>0,n=\"-\");var i=\"\",s,o,u,\nc,h,l;{if(s=e%Z,e=e/Z>>>0,o=4294967296*s+t,t=o/Z>>>0,u=\"\"+(o-Z*t),t===0&&e===0)return n+\nu+i;for(c=\"\",h=6-u.length,l=0;l>>0,o=4294967296*\ns+t,t=o/Z>>>0,u=\"\"+(o-Z*t),t===0&&e===0)return n+u+i;for(c=\"\",h=6-u.length,l=0;l<\nh;l++)c+=\"0\";i=c+u+i}{if(s=e%Z,e=e/Z>>>0,o=4294967296*s+t,t=o/Z>>>0,u=\"\"+(o-Z*t),\nt===0&&e===0)return n+u+i;for(c=\"\",h=6-u.length,l=0;l{p();var Ia=Ai(),F=a(function(r,e,t,n,i){t=t||0,n=n||!1,i=i||function(C,B,W){\nreturn C*Math.pow(2,W)+B};var s=t>>3,o=a(function(C){return n?~C&255:C},\"inv\"),u=255,\nc=8-t%8;e>t%8);var h=0;t%8+e>=8&&(h=i(0,o(r[s])&\nu,c));for(var l=e+t>>3,d=s+1;d0&&\n(h=i(h,o(r[l])>>8-b,b)),h},\"parseBits\"),Ii=a(function(r,e,t){var n=Math.pow(2,t-\n1)-1,i=F(r,1),s=F(r,t,1);if(s===0)return 0;var o=1,u=a(function(h,l,d){h===0&&(h=\n1);for(var b=1;b<=d;b++)o/=2,(l&1<0&&(h+=o);return h},\"parsePrecisionBits\"),\nc=F(r,e,t+1,!1,u);return s==Math.pow(2,t+1)-1?c===0?i===0?1/0:-1/0:NaN:(i===0?1:\n-1)*Math.pow(2,s-n)*c},\"parseFloatFromBits\"),Pa=a(function(r){return F(r,1)==1?-1*\n(F(r,15,1,!0)+1):F(r,15,1)},\"parseInt16\"),Ci=a(function(r){return F(r,1)==1?-1*(F(\nr,31,1,!0)+1):F(r,31,1)},\"parseInt32\"),Ba=a(function(r){return Ii(r,23,8)},\"pars\\\neFloat32\"),La=a(function(r){return Ii(r,52,11)},\"parseFloat64\"),Ra=a(function(r){\nvar e=F(r,16,32);if(e==49152)return NaN;for(var t=Math.pow(1e4,F(r,16,16)),n=0,i=[],\ns=F(r,16),o=0;o>3,(i+=l<<3)>>3),\nd;console.log(\"ERROR: ElementType not implemented: \"+h)},\"parseElement\"),c=a(function(h,l){\nvar d=[],b;if(h.length>1){var C=h.shift();for(b=0;b0},\"parseBool\"),Da=a(function(r){r(20,Ia),r(21,Pa),r(23,Ci),r(26,\nCi),r(1700,Ra),r(700,Ba),r(701,La),r(16,Ma),r(1114,Ti.bind(null,!1)),r(1184,Ti.bind(\nnull,!0)),r(1e3,ze),r(1007,ze),r(1016,ze),r(1008,ze),r(1009,ze),r(25,Fa)},\"init\");\nPi.exports={init:Da}});var Ri=I((qh,Li)=>{p();Li.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,\nREGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,\nSMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,\nTINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,\nBPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,\nTIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,\nREGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,\nPG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,\nREGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var Je=I(Ze=>{p();var ka=Ei(),Ua=Bi(),Oa=Ht(),Na=Ri();Ze.getTypeParser=qa;Ze.setTypeParser=\nQa;Ze.arrayParser=Oa;Ze.builtins=Na;var Ye={text:{},binary:{}};function Fi(r){return String(\nr)}a(Fi,\"noParse\");function qa(r,e){return e=e||\"text\",Ye[e]&&Ye[e][r]||Fi}a(qa,\n\"getTypeParser\");function Qa(r,e,t){typeof e==\"function\"&&(t=e,e=\"text\"),Ye[e][r]=\nt}a(Qa,\"setTypeParser\");ka.init(function(r,e){Ye.text[r]=e});Ua.init(function(r,e){\nYe.binary[r]=e})});var Xe=I((Gh,Jt)=>{\"use strict\";p();Jt.exports={host:\"localhost\",user:m.platform===\n\"win32\"?m.env.USERNAME:m.env.USER,database:void 0,password:null,connectionString:void 0,\nport:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:\"\",ssl:!1,\napplication_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,\nstatement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,\nconnect_timeout:0,keepalives:1,keepalives_idle:0};var Me=Je(),Wa=Me.getTypeParser(\n20,\"text\"),ja=Me.getTypeParser(1016,\"text\");Jt.exports.__defineSetter__(\"parseIn\\\nt8\",function(r){Me.setTypeParser(20,\"text\",r?Me.getTypeParser(23,\"text\"):Wa),Me.\nsetTypeParser(1016,\"text\",r?Me.getTypeParser(1007,\"text\"):ja)})});var et=I((Vh,Di)=>{\"use strict\";p();var Ha=(Qt(),N(qt)),Ga=Xe();function $a(r){var e=r.\nreplace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"');return'\"'+e+'\"'}a($a,\"escapeElement\");\nfunction Mi(r){for(var e=\"{\",t=0;t0&&(e=e+\",\"),r[t]===null||typeof r[t]>\n\"u\"?e=e+\"NULL\":Array.isArray(r[t])?e=e+Mi(r[t]):r[t]instanceof y?e+=\"\\\\\\\\x\"+r[t].\ntoString(\"hex\"):e+=$a(lt(r[t]));return e=e+\"}\",e}a(Mi,\"arrayString\");var lt=a(function(r,e){\nif(r==null)return null;if(r instanceof y)return r;if(ArrayBuffer.isView(r)){var t=y.\nfrom(r.buffer,r.byteOffset,r.byteLength);return t.length===r.byteLength?t:t.slice(\nr.byteOffset,r.byteOffset+r.byteLength)}return r instanceof Date?Ga.parseInputDatesAsUTC?\nza(r):Ka(r):Array.isArray(r)?Mi(r):typeof r==\"object\"?Va(r,e):r.toString()},\"pre\\\npareValue\");function Va(r,e){if(r&&typeof r.toPostgres==\"function\"){if(e=e||[],e.\nindexOf(r)!==-1)throw new Error('circular reference detected while preparing \"'+\nr+'\" for query');return e.push(r),lt(r.toPostgres(lt),e)}return JSON.stringify(r)}\na(Va,\"prepareObject\");function H(r,e){for(r=\"\"+r;r.length{\"use strict\";p();var er=(Qt(),N(qt));function Ja(r){if(r.indexOf(\n\"SCRAM-SHA-256\")===-1)throw new Error(\"SASL: Only mechanism SCRAM-SHA-256 is cur\\\nrently supported\");let e=er.randomBytes(18).toString(\"base64\");return{mechanism:\"\\\nSCRAM-SHA-256\",clientNonce:e,response:\"n,,n=*,r=\"+e,message:\"SASLInitialResponse\"}}\na(Ja,\"startSession\");function Xa(r,e,t){if(r.message!==\"SASLInitialResponse\")throw new Error(\n\"SASL: Last message was not SASLInitialResponse\");if(typeof e!=\"string\")throw new Error(\n\"SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string\");if(typeof t!=\n\"string\")throw new Error(\"SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a\\\n string\");let n=ru(t);if(n.nonce.startsWith(r.clientNonce)){if(n.nonce.length===\nr.clientNonce.length)throw new Error(\"SASL: SCRAM-SERVER-FIRST-MESSAGE: server n\\\nonce is too short\")}else throw new Error(\"SASL: SCRAM-SERVER-FIRST-MESSAGE: serv\\\ner nonce does not start with client nonce\");var i=y.from(n.salt,\"base64\"),s=su(e,\ni,n.iteration),o=De(s,\"Client Key\"),u=iu(o),c=\"n=*,r=\"+r.clientNonce,h=\"r=\"+n.nonce+\n\",s=\"+n.salt+\",i=\"+n.iteration,l=\"c=biws,r=\"+n.nonce,d=c+\",\"+h+\",\"+l,b=De(u,d),C=Oi(\no,b),B=C.toString(\"base64\"),W=De(s,\"Server Key\"),X=De(W,d);r.message=\"SASLRespon\\\nse\",r.serverSignature=X.toString(\"base64\"),r.response=l+\",p=\"+B}a(Xa,\"continueSe\\\nssion\");function eu(r,e){if(r.message!==\"SASLResponse\")throw new Error(\"SASL: La\\\nst message was not SASLResponse\");if(typeof e!=\"string\")throw new Error(\"SASL: S\\\nCRAM-SERVER-FINAL-MESSAGE: serverData must be a string\");let{serverSignature:t}=nu(\ne);if(t!==r.serverSignature)throw new Error(\"SASL: SCRAM-SERVER-FINAL-MESSAGE: s\\\nerver signature does not match\")}a(eu,\"finalizeSession\");function tu(r){if(typeof r!=\n\"string\")throw new TypeError(\"SASL: text must be a string\");return r.split(\"\").map(\n(e,t)=>r.charCodeAt(t)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}a(tu,\"isPrintableC\\\nhars\");function ki(r){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.\ntest(r)}a(ki,\"isBase64\");function Ui(r){if(typeof r!=\"string\")throw new TypeError(\n\"SASL: attribute pairs text must be a string\");return new Map(r.split(\",\").map(e=>{\nif(!/^.=/.test(e))throw new Error(\"SASL: Invalid attribute pair entry\");let t=e[0],\nn=e.substring(2);return[t,n]}))}a(Ui,\"parseAttributePairs\");function ru(r){let e=Ui(\nr),t=e.get(\"r\");if(t){if(!tu(t))throw new Error(\"SASL: SCRAM-SERVER-FIRST-MESSAG\\\nE: nonce must only contain printable characters\")}else throw new Error(\"SASL: SC\\\nRAM-SERVER-FIRST-MESSAGE: nonce missing\");let n=e.get(\"s\");if(n){if(!ki(n))throw new Error(\n\"SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64\")}else throw new Error(\"S\\\nASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing\");let i=e.get(\"i\");if(i){if(!/^[1-9][0-9]*$/.\ntest(i))throw new Error(\"SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration cou\\\nnt\")}else throw new Error(\"SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing\");\nlet s=parseInt(i,10);return{nonce:t,salt:n,iteration:s}}a(ru,\"parseServerFirstMe\\\nssage\");function nu(r){let t=Ui(r).get(\"v\");if(t){if(!ki(t))throw new Error(\"SAS\\\nL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64\")}else throw new Error(\n\"SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing\");return{serverSignature:t}}\na(nu,\"parseServerFinalMessage\");function Oi(r,e){if(!y.isBuffer(r))throw new TypeError(\n\"first argument must be a Buffer\");if(!y.isBuffer(e))throw new TypeError(\"second\\\n argument must be a Buffer\");if(r.length!==e.length)throw new Error(\"Buffer leng\\\nths must match\");if(r.length===0)throw new Error(\"Buffers cannot be empty\");return y.\nfrom(r.map((t,n)=>r[n]^e[n]))}a(Oi,\"xorBuffers\");function iu(r){return er.createHash(\n\"sha256\").update(r).digest()}a(iu,\"sha256\");function De(r,e){return er.createHmac(\n\"sha256\",r).update(e).digest()}a(De,\"hmacSha256\");function su(r,e,t){for(var n=De(\nr,y.concat([e,y.from([0,0,0,1])])),i=n,s=0;sou});function ou(...r){return r.join(\"/\")}var rr=z(()=>{\n\"use strict\";p();a(ou,\"join\")});var nr={};ie(nr,{stat:()=>au});function au(r,e){e(new Error(\"No filesystem\"))}var ir=z(\n()=>{\"use strict\";p();a(au,\"stat\")});var sr={};ie(sr,{default:()=>uu});var uu,or=z(()=>{\"use strict\";p();uu={}});var Qi={};ie(Qi,{StringDecoder:()=>ar});var ur,ar,Wi=z(()=>{\"use strict\";p();ur=\nclass ur{constructor(e){_(this,\"td\");this.td=new TextDecoder(e)}write(e){return this.\ntd.decode(e,{stream:!0})}end(e){return this.td.decode(e)}};a(ur,\"StringDecoder\");\nar=ur});var $i=I((ol,Gi)=>{\"use strict\";p();var{Transform:cu}=(or(),N(sr)),{StringDecoder:hu}=(Wi(),N(Qi)),\nbe=Symbol(\"last\"),ft=Symbol(\"decoder\");function lu(r,e,t){let n;if(this.overflow){\nif(n=this[ft].write(r).split(this.matcher),n.length===1)return t();n.shift(),this.\noverflow=!1}else this[be]+=this[ft].write(r),n=this[be].split(this.matcher);this[be]=\nn.pop();for(let i=0;ithis.maxLength,this.overflow&&!this.skipOverflow){\nt(new Error(\"maximum buffer reached\"));return}t()}a(lu,\"transform\");function fu(r){\nif(this[be]+=this[ft].end(),this[be])try{Hi(this,this.mapper(this[be]))}catch(e){\nreturn r(e)}r()}a(fu,\"flush\");function Hi(r,e){e!==void 0&&r.push(e)}a(Hi,\"push\");\nfunction ji(r){return r}a(ji,\"noop\");function pu(r,e,t){switch(r=r||/\\r?\\n/,e=e||\nji,t=t||{},arguments.length){case 1:typeof r==\"function\"?(e=r,r=/\\r?\\n/):typeof r==\n\"object\"&&!(r instanceof RegExp)&&!r[Symbol.split]&&(t=r,r=/\\r?\\n/);break;case 2:\ntypeof r==\"function\"?(t=e,e=r,r=/\\r?\\n/):typeof e==\"object\"&&(t=e,e=ji)}t=Object.\nassign({},t),t.autoDestroy=!0,t.transform=lu,t.flush=fu,t.readableObjectMode=!0;\nlet n=new cu(t);return n[be]=\"\",n[ft]=new hu(\"utf8\"),n.matcher=r,n.mapper=e,n.maxLength=\nt.maxLength,n.skipOverflow=t.skipOverflow||!1,n.overflow=!1,n._destroy=function(i,s){\nthis._writableState.errorEmitted=!1,s(i)},n}a(pu,\"split\");Gi.exports=pu});var zi=I((cl,pe)=>{\"use strict\";p();var Vi=(rr(),N(tr)),du=(or(),N(sr)).Stream,yu=$i(),\nKi=(He(),N(je)),mu=5432,pt=m.platform===\"win32\",tt=m.stderr,gu=56,wu=7,bu=61440,\nSu=32768;function xu(r){return(r&bu)==Su}a(xu,\"isRegFile\");var ke=[\"host\",\"port\",\n\"database\",\"user\",\"password\"],cr=ke.length,vu=ke[cr-1];function hr(){var r=tt instanceof\ndu&&tt.writable===!0;if(r){var e=Array.prototype.slice.call(arguments).concat(`\n`);tt.write(Ki.format.apply(Ki,e))}}a(hr,\"warn\");Object.defineProperty(pe.exports,\n\"isWin\",{get:a(function(){return pt},\"get\"),set:a(function(r){pt=r},\"set\")});pe.\nexports.warnTo=function(r){var e=tt;return tt=r,e};pe.exports.getFileName=function(r){\nvar e=r||m.env,t=e.PGPASSFILE||(pt?Vi.join(e.APPDATA||\"./\",\"postgresql\",\"pgpass.\\\nconf\"):Vi.join(e.HOME||\"./\",\".pgpass\"));return t};pe.exports.usePgPass=function(r,e){\nreturn Object.prototype.hasOwnProperty.call(m.env,\"PGPASSWORD\")?!1:pt?!0:(e=e||\"\\\n\",xu(r.mode)?r.mode&(gu|wu)?(hr('WARNING: password file \"%s\" has group or \\\nworld access; permissions should be u=rw (0600) or less',e),!1):!0:(hr('WARNING:\\\n password file \"%s\" is not a plain file',e),!1))};var Eu=pe.exports.match=function(r,e){\nreturn ke.slice(0,-1).reduce(function(t,n,i){return i==1&&Number(r[n]||mu)===Number(\ne[n])?t&&!0:t&&(e[n]===\"*\"||e[n]===r[n])},!0)};pe.exports.getPassword=function(r,e,t){\nvar n,i=e.pipe(yu());function s(c){var h=_u(c);h&&Au(h)&&Eu(r,h)&&(n=h[vu],i.end())}\na(s,\"onLine\");var o=a(function(){e.destroy(),t(n)},\"onEnd\"),u=a(function(c){e.destroy(),\nhr(\"WARNING: error on reading file: %s\",c),t(void 0)},\"onErr\");e.on(\"error\",u),i.\non(\"data\",s).on(\"end\",o).on(\"error\",u)};var _u=pe.exports.parseLine=function(r){\nif(r.length<11||r.match(/^\\s+#/))return null;for(var e=\"\",t=\"\",n=0,i=0,s=0,o={},\nu=!1,c=a(function(l,d,b){var C=r.substring(d,b);Object.hasOwnProperty.call(m.env,\n\"PGPASS_NO_DEESCAPE\")||(C=C.replace(/\\\\([:\\\\])/g,\"$1\")),o[ke[l]]=C},\"addToObj\"),\nh=0;h=0&&e==\":\"&&t!==\"\\\\\"&&(c(n,i,h+1),i=h+2,n+=1)}return o=Object.keys(o).length===\ncr?o:null,o},Au=pe.exports.isValidEntry=function(r){for(var e={0:function(o){return o.\nlength>0},1:function(o){return o===\"*\"?!0:(o=Number(o),isFinite(o)&&o>0&&o<9007199254740992&&\nMath.floor(o)===o)},2:function(o){return o.length>0},3:function(o){return o.length>\n0},4:function(o){return o.length>0}},t=0;t{\"use strict\";p();var fl=(rr(),N(tr)),Yi=(ir(),N(nr)),dt=zi();\nlr.exports=function(r,e){var t=dt.getFileName();Yi.stat(t,function(n,i){if(n||!dt.\nusePgPass(i,t))return e(void 0);var s=Yi.createReadStream(t);dt.getPassword(r,s,\ne)})};lr.exports.warnTo=dt.warnTo});var mt=I((yl,Ji)=>{\"use strict\";p();var Cu=Je();function yt(r){this._types=r||Cu,\nthis.text={},this.binary={}}a(yt,\"TypeOverrides\");yt.prototype.getOverrides=function(r){\nswitch(r){case\"text\":return this.text;case\"binary\":return this.binary;default:return{}}};\nyt.prototype.setTypeParser=function(r,e,t){typeof e==\"function\"&&(t=e,e=\"text\"),\nthis.getOverrides(e)[r]=t};yt.prototype.getTypeParser=function(r,e){return e=e||\n\"text\",this.getOverrides(e)[r]||this._types.getTypeParser(r,e)};Ji.exports=yt});var Xi={};ie(Xi,{default:()=>Tu});var Tu,es=z(()=>{\"use strict\";p();Tu={}});var ts={};ie(ts,{parse:()=>fr});function fr(r,e=!1){let{protocol:t}=new URL(r),n=\"\\\nhttp:\"+r.substring(t.length),{username:i,password:s,host:o,hostname:u,port:c,pathname:h,\nsearch:l,searchParams:d,hash:b}=new URL(n);s=decodeURIComponent(s),i=decodeURIComponent(\ni),h=decodeURIComponent(h);let C=i+\":\"+s,B=e?Object.fromEntries(d.entries()):l;return{\nhref:r,protocol:t,auth:C,username:i,password:s,host:o,hostname:u,port:c,pathname:h,\nsearch:l,query:B,hash:b}}var pr=z(()=>{\"use strict\";p();a(fr,\"parse\")});var ns=I((xl,rs)=>{\"use strict\";p();var Iu=(pr(),N(ts)),dr=(ir(),N(nr));function yr(r){\nif(r.charAt(0)===\"/\"){var t=r.split(\" \");return{host:t[0],database:t[1]}}var e=Iu.\nparse(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(r)?encodeURI(r).replace(/\\%25(\\d\\d)/g,\n\"%$1\"):r,!0),t=e.query;for(var n in t)Array.isArray(t[n])&&(t[n]=t[n][t[n].length-\n1]);var i=(e.auth||\":\").split(\":\");if(t.user=i[0],t.password=i.splice(1).join(\":\"),\nt.port=e.port,e.protocol==\"socket:\")return t.host=decodeURI(e.pathname),t.database=\ne.query.db,t.client_encoding=e.query.encoding,t;t.host||(t.host=e.hostname);var s=e.\npathname;if(!t.host&&s&&/^%2f/i.test(s)){var o=s.split(\"/\");t.host=decodeURIComponent(\no[0]),s=o.splice(1).join(\"/\")}switch(s&&s.charAt(0)===\"/\"&&(s=s.slice(1)||null),\nt.database=s&&decodeURI(s),(t.ssl===\"true\"||t.ssl===\"1\")&&(t.ssl=!0),t.ssl===\"0\"&&\n(t.ssl=!1),(t.sslcert||t.sslkey||t.sslrootcert||t.sslmode)&&(t.ssl={}),t.sslcert&&\n(t.ssl.cert=dr.readFileSync(t.sslcert).toString()),t.sslkey&&(t.ssl.key=dr.readFileSync(\nt.sslkey).toString()),t.sslrootcert&&(t.ssl.ca=dr.readFileSync(t.sslrootcert).toString()),\nt.sslmode){case\"disable\":{t.ssl=!1;break}case\"prefer\":case\"require\":case\"verify-\\\nca\":case\"verify-full\":break;case\"no-verify\":{t.ssl.rejectUnauthorized=!1;break}}\nreturn t}a(yr,\"parse\");rs.exports=yr;yr.parse=yr});var gt=I((_l,os)=>{\"use strict\";p();var Pu=(es(),N(Xi)),ss=Xe(),is=ns().parse,$=a(\nfunction(r,e,t){return t===void 0?t=m.env[\"PG\"+r.toUpperCase()]:t===!1||(t=m.env[t]),\ne[r]||t||ss[r]},\"val\"),Bu=a(function(){switch(m.env.PGSSLMODE){case\"disable\":return!1;case\"\\\nprefer\":case\"require\":case\"verify-ca\":case\"verify-full\":return!0;case\"no-verify\":\nreturn{rejectUnauthorized:!1}}return ss.ssl},\"readSSLConfigFromEnvironment\"),Ue=a(\nfunction(r){return\"'\"+(\"\"+r).replace(/\\\\/g,\"\\\\\\\\\").replace(/'/g,\"\\\\'\")+\"'\"},\"quo\\\nteParamValue\"),ne=a(function(r,e,t){var n=e[t];n!=null&&r.push(t+\"=\"+Ue(n))},\"ad\\\nd\"),gr=class gr{constructor(e){e=typeof e==\"string\"?is(e):e||{},e.connectionString&&\n(e=Object.assign({},e,is(e.connectionString))),this.user=$(\"user\",e),this.database=\n$(\"database\",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(\n$(\"port\",e),10),this.host=$(\"host\",e),Object.defineProperty(this,\"password\",{configurable:!0,\nenumerable:!1,writable:!0,value:$(\"password\",e)}),this.binary=$(\"binary\",e),this.\noptions=$(\"options\",e),this.ssl=typeof e.ssl>\"u\"?Bu():e.ssl,typeof this.ssl==\"st\\\nring\"&&this.ssl===\"true\"&&(this.ssl=!0),this.ssl===\"no-verify\"&&(this.ssl={rejectUnauthorized:!1}),\nthis.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,\"key\",{enumerable:!1}),this.\nclient_encoding=$(\"client_encoding\",e),this.replication=$(\"replication\",e),this.\nisDomainSocket=!(this.host||\"\").indexOf(\"/\"),this.application_name=$(\"applicatio\\\nn_name\",e,\"PGAPPNAME\"),this.fallback_application_name=$(\"fallback_application_na\\\nme\",e,!1),this.statement_timeout=$(\"statement_timeout\",e,!1),this.lock_timeout=$(\n\"lock_timeout\",e,!1),this.idle_in_transaction_session_timeout=$(\"idle_in_transac\\\ntion_session_timeout\",e,!1),this.query_timeout=$(\"query_timeout\",e,!1),e.connectionTimeoutMillis===\nvoid 0?this.connect_timeout=m.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.\nfloor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===\n!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis==\"number\"&&(this.keepalives_idle=\nMath.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){var t=[];\nne(t,this,\"user\"),ne(t,this,\"password\"),ne(t,this,\"port\"),ne(t,this,\"application\\\n_name\"),ne(t,this,\"fallback_application_name\"),ne(t,this,\"connect_timeout\"),ne(t,\nthis,\"options\");var n=typeof this.ssl==\"object\"?this.ssl:this.ssl?{sslmode:this.\nssl}:{};if(ne(t,n,\"sslmode\"),ne(t,n,\"sslca\"),ne(t,n,\"sslkey\"),ne(t,n,\"sslcert\"),\nne(t,n,\"sslrootcert\"),this.database&&t.push(\"dbname=\"+Ue(this.database)),this.replication&&\nt.push(\"replication=\"+Ue(this.replication)),this.host&&t.push(\"host=\"+Ue(this.host)),\nthis.isDomainSocket)return e(null,t.join(\" \"));this.client_encoding&&t.push(\"cli\\\nent_encoding=\"+Ue(this.client_encoding)),Pu.lookup(this.host,function(i,s){return i?\ne(i,null):(t.push(\"hostaddr=\"+Ue(s)),e(null,t.join(\" \")))})}};a(gr,\"ConnectionPa\\\nrameters\");var mr=gr;os.exports=mr});var cs=I((Tl,us)=>{\"use strict\";p();var Lu=Je(),as=/^([A-Za-z]+)(?: (\\d+))?(?: (\\d+))?/,\nbr=class br{constructor(e,t){this.command=null,this.rowCount=null,this.oid=null,\nthis.rows=[],this.fields=[],this._parsers=void 0,this._types=t,this.RowCtor=null,\nthis.rowAsArray=e===\"array\",this.rowAsArray&&(this.parseRow=this._parseRowAsArray)}addCommandComplete(e){\nvar t;e.text?t=as.exec(e.text):t=as.exec(e.command),t&&(this.command=t[1],t[3]?(this.\noid=parseInt(t[2],10),this.rowCount=parseInt(t[3],10)):t[2]&&(this.rowCount=parseInt(\nt[2],10)))}_parseRowAsArray(e){for(var t=new Array(e.length),n=0,i=e.length;n{\"use strict\";p();var{EventEmitter:Ru}=we(),hs=cs(),ls=et(),xr=class xr extends Ru{constructor(e,t,n){\nsuper(),e=ls.normalizeQueryConfig(e,t,n),this.text=e.text,this.values=e.values,this.\nrows=e.rows,this.types=e.types,this.name=e.name,this.binary=e.binary,this.portal=\ne.portal||\"\",this.callback=e.callback,this._rowMode=e.rowMode,m.domain&&e.callback&&\n(this.callback=m.domain.bind(e.callback)),this._result=new hs(this._rowMode,this.\ntypes),this._results=this._result,this.isPreparedStatement=!1,this._canceledDueToError=\n!1,this._promise=null}requiresPreparation(){return this.name||this.rows?!0:!this.\ntext||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&\n(Array.isArray(this._results)||(this._results=[this._result]),this._result=new hs(\nthis._rowMode,this.types),this._results.push(this._result))}handleRowDescription(e){\nthis._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.\ncallback||!this.listeners(\"row\").length}handleDataRow(e){let t;if(!this._canceledDueToError){\ntry{t=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return}\nthis.emit(\"row\",t,this._result),this._accumulateRows&&this._result.addRow(t)}}handleCommandComplete(e,t){\nthis._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&t.sync()}handleEmptyQuery(e){\nthis.rows&&e.sync()}handleError(e,t){if(this._canceledDueToError&&(e=this._canceledDueToError,\nthis._canceledDueToError=!1),this.callback)return this.callback(e);this.emit(\"er\\\nror\",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(\nthis._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(t){\nm.nextTick(()=>{throw t})}this.emit(\"end\",this._results)}submit(e){if(typeof this.\ntext!=\"string\"&&typeof this.name!=\"string\")return new Error(\"A query must have e\\\nither text or a name. Supplying neither is unsupported.\");let t=e.parsedStatements[this.\nname];return this.text&&t&&this.text!==t?new Error(`Prepared statements must be \\\nunique - '${this.name}' was used for a different statement`):this.values&&!Array.\nisArray(this.values)?new Error(\"Query values must be an array\"):(this.requiresPreparation()?\nthis.prepare(e):e.query(this.text),null)}hasBeenParsed(e){return this.name&&e.parsedStatements[this.\nname]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,t){e.execute(\n{portal:this.portal,rows:t}),t?e.flush():e.sync()}prepare(e){this.isPreparedStatement=\n!0,this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});\ntry{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.\nbinary,valueMapper:ls.prepareValue})}catch(t){this.handleError(t,e);return}e.describe(\n{type:\"P\",name:this.portal||\"\"}),this._getRows(e,this.rows)}handleCopyInResponse(e){\ne.sendCopyFail(\"No source stream defined\")}handleCopyData(e,t){}};a(xr,\"Query\");\nvar Sr=xr;fs.exports=Sr});var ys={};ie(ys,{Socket:()=>_e,isIP:()=>Fu});function Fu(r){return 0}var ds,Mu,E,\n_e,wt=z(()=>{\"use strict\";p();ds=Te(we(),1);a(Fu,\"isIP\");Mu=a(r=>r.replace(/^[^.]+\\./,\n\"api.\"),\"transformHost\"),E=class E extends ds.EventEmitter{constructor(){super(...arguments);\n_(this,\"opts\",{});_(this,\"connecting\",!1);_(this,\"pending\",!0);_(this,\"writable\",\n!0);_(this,\"encrypted\",!1);_(this,\"authorized\",!1);_(this,\"destroyed\",!1);_(this,\n\"ws\",null);_(this,\"writeBuffer\");_(this,\"tlsState\",0);_(this,\"tlsRead\");_(this,\"\\\ntlsWrite\")}static get poolQueryViaFetch(){return E.opts.poolQueryViaFetch??E.defaults.\npoolQueryViaFetch}static set poolQueryViaFetch(t){E.opts.poolQueryViaFetch=t}static get fetchEndpoint(){\nreturn E.opts.fetchEndpoint??E.defaults.fetchEndpoint}static set fetchEndpoint(t){\nE.opts.fetchEndpoint=t}static get fetchConnectionCache(){return!0}static set fetchConnectionCache(t){\nconsole.warn(\"The `fetchConnectionCache` option is deprecated (now always `true`\\\n)\")}static get fetchFunction(){return E.opts.fetchFunction??E.defaults.fetchFunction}static set fetchFunction(t){\nE.opts.fetchFunction=t}static get webSocketConstructor(){return E.opts.webSocketConstructor??\nE.defaults.webSocketConstructor}static set webSocketConstructor(t){E.opts.webSocketConstructor=\nt}get webSocketConstructor(){return this.opts.webSocketConstructor??E.webSocketConstructor}set webSocketConstructor(t){\nthis.opts.webSocketConstructor=t}static get wsProxy(){return E.opts.wsProxy??E.defaults.\nwsProxy}static set wsProxy(t){E.opts.wsProxy=t}get wsProxy(){return this.opts.wsProxy??\nE.wsProxy}set wsProxy(t){this.opts.wsProxy=t}static get coalesceWrites(){return E.\nopts.coalesceWrites??E.defaults.coalesceWrites}static set coalesceWrites(t){E.opts.\ncoalesceWrites=t}get coalesceWrites(){return this.opts.coalesceWrites??E.coalesceWrites}set coalesceWrites(t){\nthis.opts.coalesceWrites=t}static get useSecureWebSocket(){return E.opts.useSecureWebSocket??\nE.defaults.useSecureWebSocket}static set useSecureWebSocket(t){E.opts.useSecureWebSocket=\nt}get useSecureWebSocket(){return this.opts.useSecureWebSocket??E.useSecureWebSocket}set useSecureWebSocket(t){\nthis.opts.useSecureWebSocket=t}static get forceDisablePgSSL(){return E.opts.forceDisablePgSSL??\nE.defaults.forceDisablePgSSL}static set forceDisablePgSSL(t){E.opts.forceDisablePgSSL=\nt}get forceDisablePgSSL(){return this.opts.forceDisablePgSSL??E.forceDisablePgSSL}set forceDisablePgSSL(t){\nthis.opts.forceDisablePgSSL=t}static get disableSNI(){return E.opts.disableSNI??\nE.defaults.disableSNI}static set disableSNI(t){E.opts.disableSNI=t}get disableSNI(){\nreturn this.opts.disableSNI??E.disableSNI}set disableSNI(t){this.opts.disableSNI=\nt}static get pipelineConnect(){return E.opts.pipelineConnect??E.defaults.pipelineConnect}static set pipelineConnect(t){\nE.opts.pipelineConnect=t}get pipelineConnect(){return this.opts.pipelineConnect??\nE.pipelineConnect}set pipelineConnect(t){this.opts.pipelineConnect=t}static get subtls(){\nreturn E.opts.subtls??E.defaults.subtls}static set subtls(t){E.opts.subtls=t}get subtls(){\nreturn this.opts.subtls??E.subtls}set subtls(t){this.opts.subtls=t}static get pipelineTLS(){\nreturn E.opts.pipelineTLS??E.defaults.pipelineTLS}static set pipelineTLS(t){E.opts.\npipelineTLS=t}get pipelineTLS(){return this.opts.pipelineTLS??E.pipelineTLS}set pipelineTLS(t){\nthis.opts.pipelineTLS=t}static get rootCerts(){return E.opts.rootCerts??E.defaults.\nrootCerts}static set rootCerts(t){E.opts.rootCerts=t}get rootCerts(){return this.\nopts.rootCerts??E.rootCerts}set rootCerts(t){this.opts.rootCerts=t}wsProxyAddrForHost(t,n){\nlet i=this.wsProxy;if(i===void 0)throw new Error(\"No WebSocket proxy is configur\\\ned. Please see https://github.com/neondatabase/serverless/blob/main/CONFIG.md#ws\\\nproxy-string--host-string-port-number--string--string\");return typeof i==\"functi\\\non\"?i(t,n):`${i}?address=${t}:${n}`}setNoDelay(){return this}setKeepAlive(){return this}ref(){\nreturn this}unref(){return this}connect(t,n,i){this.connecting=!0,i&&this.once(\"\\\nconnect\",i);let s=a(()=>{this.connecting=!1,this.pending=!1,this.emit(\"connect\"),\nthis.emit(\"ready\")},\"handleWebSocketOpen\"),o=a((c,h=!1)=>{c.binaryType=\"arraybuf\\\nfer\",c.addEventListener(\"error\",l=>{this.emit(\"error\",l),this.emit(\"close\")}),c.\naddEventListener(\"message\",l=>{if(this.tlsState===0){let d=y.from(l.data);this.emit(\n\"data\",d)}}),c.addEventListener(\"close\",()=>{this.emit(\"close\")}),h?s():c.addEventListener(\n\"open\",s)},\"configureWebSocket\"),u;try{u=this.wsProxyAddrForHost(n,typeof t==\"st\\\nring\"?parseInt(t,10):t)}catch(c){this.emit(\"error\",c),this.emit(\"close\");return}\ntry{let h=(this.useSecureWebSocket?\"wss:\":\"ws:\")+\"//\"+u;if(this.webSocketConstructor!==\nvoid 0)this.ws=new this.webSocketConstructor(h),o(this.ws);else try{this.ws=new WebSocket(\nh),o(this.ws)}catch{this.ws=new __unstable_WebSocket(h),o(this.ws)}}catch(c){let l=(this.\nuseSecureWebSocket?\"https:\":\"http:\")+\"//\"+u;fetch(l,{headers:{Upgrade:\"websocket\"}}).\nthen(d=>{if(this.ws=d.webSocket,this.ws==null)throw c;this.ws.accept(),o(this.ws,\n!0)}).catch(d=>{this.emit(\"error\",new Error(`All attempts to open a WebSocket to\\\n connect to the database failed. Please refer to https://github.com/neondatabase\\\n/serverless/blob/main/CONFIG.md#websocketconstructor-typeof-websocket--undefined\\\n. Details: ${d.message}`)),this.emit(\"close\")})}}async startTls(t){if(this.subtls===\nvoid 0)throw new Error(\"For Postgres SSL connections, you must set `neonConfig.s\\\nubtls` to the subtls library. See https://github.com/neondatabase/serverless/blo\\\nb/main/CONFIG.md for more information.\");this.tlsState=1;let n=this.subtls.TrustedCert.\nfromPEM(this.rootCerts),i=new this.subtls.WebSocketReadQueue(this.ws),s=i.read.bind(\ni),o=this.rawWrite.bind(this),[u,c]=await this.subtls.startTls(t,n,s,o,{useSNI:!this.\ndisableSNI,expectPreData:this.pipelineTLS?new Uint8Array([83]):void 0});this.tlsRead=\nu,this.tlsWrite=c,this.tlsState=2,this.encrypted=!0,this.authorized=!0,this.emit(\n\"secureConnection\",this),this.tlsReadLoop()}async tlsReadLoop(){for(;;){let t=await this.\ntlsRead();if(t===void 0)break;{let n=y.from(t);this.emit(\"data\",n)}}}rawWrite(t){\nif(!this.coalesceWrites){this.ws.send(t);return}if(this.writeBuffer===void 0)this.\nwriteBuffer=t,setTimeout(()=>{this.ws.send(this.writeBuffer),this.writeBuffer=void 0},\n0);else{let n=new Uint8Array(this.writeBuffer.length+t.length);n.set(this.writeBuffer),\nn.set(t,this.writeBuffer.length),this.writeBuffer=n}}write(t,n=\"utf8\",i=s=>{}){return t.\nlength===0?(i(),!0):(typeof t==\"string\"&&(t=y.from(t,n)),this.tlsState===0?(this.\nrawWrite(t),i()):this.tlsState===1?this.once(\"secureConnection\",()=>{this.write(\nt,n,i)}):(this.tlsWrite(t),i()),!0)}end(t=y.alloc(0),n=\"utf8\",i=()=>{}){return this.\nwrite(t,n,()=>{this.ws.close(),i()}),this}destroy(){return this.destroyed=!0,this.\nend()}};a(E,\"Socket\"),_(E,\"defaults\",{poolQueryViaFetch:!1,fetchEndpoint:a(t=>\"h\\\nttps://\"+Mu(t)+\"/sql\",\"fetchEndpoint\"),fetchConnectionCache:!0,fetchFunction:void 0,\nwebSocketConstructor:void 0,wsProxy:a(t=>t+\"/v2\",\"wsProxy\"),useSecureWebSocket:!0,\nforceDisablePgSSL:!0,coalesceWrites:!0,pipelineConnect:\"password\",subtls:void 0,\nrootCerts:\"\",pipelineTLS:!1,disableSNI:!1}),_(E,\"opts\",{});_e=E});var Yr=I(T=>{\"use strict\";p();Object.defineProperty(T,\"__esModule\",{value:!0});T.\nNoticeMessage=T.DataRowMessage=T.CommandCompleteMessage=T.ReadyForQueryMessage=T.\nNotificationResponseMessage=T.BackendKeyDataMessage=T.AuthenticationMD5Password=\nT.ParameterStatusMessage=T.ParameterDescriptionMessage=T.RowDescriptionMessage=T.\nField=T.CopyResponse=T.CopyDataMessage=T.DatabaseError=T.copyDone=T.emptyQuery=T.\nreplicationStart=T.portalSuspended=T.noData=T.closeComplete=T.bindComplete=T.parseComplete=\nvoid 0;T.parseComplete={name:\"parseComplete\",length:5};T.bindComplete={name:\"bin\\\ndComplete\",length:5};T.closeComplete={name:\"closeComplete\",length:5};T.noData={name:\"\\\nnoData\",length:5};T.portalSuspended={name:\"portalSuspended\",length:5};T.replicationStart=\n{name:\"replicationStart\",length:4};T.emptyQuery={name:\"emptyQuery\",length:4};T.copyDone=\n{name:\"copyDone\",length:4};var kr=class kr extends Error{constructor(e,t,n){super(\ne),this.length=t,this.name=n}};a(kr,\"DatabaseError\");var vr=kr;T.DatabaseError=vr;\nvar Ur=class Ur{constructor(e,t){this.length=e,this.chunk=t,this.name=\"copyData\"}};\na(Ur,\"CopyDataMessage\");var Er=Ur;T.CopyDataMessage=Er;var Or=class Or{constructor(e,t,n,i){\nthis.length=e,this.name=t,this.binary=n,this.columnTypes=new Array(i)}};a(Or,\"Co\\\npyResponse\");var _r=Or;T.CopyResponse=_r;var Nr=class Nr{constructor(e,t,n,i,s,o,u){\nthis.name=e,this.tableID=t,this.columnID=n,this.dataTypeID=i,this.dataTypeSize=s,\nthis.dataTypeModifier=o,this.format=u}};a(Nr,\"Field\");var Ar=Nr;T.Field=Ar;var qr=class qr{constructor(e,t){\nthis.length=e,this.fieldCount=t,this.name=\"rowDescription\",this.fields=new Array(\nthis.fieldCount)}};a(qr,\"RowDescriptionMessage\");var Cr=qr;T.RowDescriptionMessage=\nCr;var Qr=class Qr{constructor(e,t){this.length=e,this.parameterCount=t,this.name=\n\"parameterDescription\",this.dataTypeIDs=new Array(this.parameterCount)}};a(Qr,\"P\\\narameterDescriptionMessage\");var Tr=Qr;T.ParameterDescriptionMessage=Tr;var Wr=class Wr{constructor(e,t,n){\nthis.length=e,this.parameterName=t,this.parameterValue=n,this.name=\"parameterSta\\\ntus\"}};a(Wr,\"ParameterStatusMessage\");var Ir=Wr;T.ParameterStatusMessage=Ir;var jr=class jr{constructor(e,t){\nthis.length=e,this.salt=t,this.name=\"authenticationMD5Password\"}};a(jr,\"Authenti\\\ncationMD5Password\");var Pr=jr;T.AuthenticationMD5Password=Pr;var Hr=class Hr{constructor(e,t,n){\nthis.length=e,this.processID=t,this.secretKey=n,this.name=\"backendKeyData\"}};a(Hr,\n\"BackendKeyDataMessage\");var Br=Hr;T.BackendKeyDataMessage=Br;var Gr=class Gr{constructor(e,t,n,i){\nthis.length=e,this.processId=t,this.channel=n,this.payload=i,this.name=\"notifica\\\ntion\"}};a(Gr,\"NotificationResponseMessage\");var Lr=Gr;T.NotificationResponseMessage=\nLr;var $r=class $r{constructor(e,t){this.length=e,this.status=t,this.name=\"ready\\\nForQuery\"}};a($r,\"ReadyForQueryMessage\");var Rr=$r;T.ReadyForQueryMessage=Rr;var Vr=class Vr{constructor(e,t){\nthis.length=e,this.text=t,this.name=\"commandComplete\"}};a(Vr,\"CommandCompleteMes\\\nsage\");var Fr=Vr;T.CommandCompleteMessage=Fr;var Kr=class Kr{constructor(e,t){this.\nlength=e,this.fields=t,this.name=\"dataRow\",this.fieldCount=t.length}};a(Kr,\"Data\\\nRowMessage\");var Mr=Kr;T.DataRowMessage=Mr;var zr=class zr{constructor(e,t){this.\nlength=e,this.message=t,this.name=\"notice\"}};a(zr,\"NoticeMessage\");var Dr=zr;T.NoticeMessage=\nDr});var ms=I(bt=>{\"use strict\";p();Object.defineProperty(bt,\"__esModule\",{value:!0});\nbt.Writer=void 0;var Jr=class Jr{constructor(e=256){this.size=e,this.offset=5,this.\nheaderPosition=0,this.buffer=y.allocUnsafe(e)}ensure(e){var t=this.buffer.length-\nthis.offset;if(t>1)+e;this.buffer=y.allocUnsafe(\ni),n.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=\ne>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>\n8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),\nthis.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){\nif(!e)this.ensure(1);else{var t=y.byteLength(e);this.ensure(t+1),this.buffer.write(\ne,this.offset,\"utf-8\"),this.offset+=t}return this.buffer[this.offset++]=0,this}addString(e=\"\"){\nvar t=y.byteLength(e);return this.ensure(t),this.buffer.write(e,this.offset),this.\noffset+=t,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),\nthis.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let t=this.\noffset-(this.headerPosition+1);this.buffer.writeInt32BE(t,this.headerPosition+1)}\nreturn this.buffer.slice(e?0:5,this.offset)}flush(e){var t=this.join(e);return this.\noffset=5,this.headerPosition=0,this.buffer=y.allocUnsafe(this.size),t}};a(Jr,\"Wr\\\niter\");var Zr=Jr;bt.Writer=Zr});var ws=I(xt=>{\"use strict\";p();Object.defineProperty(xt,\"__esModule\",{value:!0});\nxt.serialize=void 0;var Xr=ms(),M=new Xr.Writer,Du=a(r=>{M.addInt16(3).addInt16(\n0);for(let n of Object.keys(r))M.addCString(n).addCString(r[n]);M.addCString(\"cl\\\nient_encoding\").addCString(\"UTF8\");var e=M.addCString(\"\").flush(),t=e.length+4;return new Xr.\nWriter().addInt32(t).add(e).flush()},\"startup\"),ku=a(()=>{let r=y.allocUnsafe(8);\nreturn r.writeInt32BE(8,0),r.writeInt32BE(80877103,4),r},\"requestSsl\"),Uu=a(r=>M.\naddCString(r).flush(112),\"password\"),Ou=a(function(r,e){return M.addCString(r).addInt32(\ny.byteLength(e)).addString(e),M.flush(112)},\"sendSASLInitialResponseMessage\"),Nu=a(\nfunction(r){return M.addString(r).flush(112)},\"sendSCRAMClientFinalMessage\"),qu=a(\nr=>M.addCString(r).flush(81),\"query\"),gs=[],Qu=a(r=>{let e=r.name||\"\";e.length>63&&\n(console.error(\"Warning! Postgres only supports 63 characters for query names.\"),\nconsole.error(\"You supplied %s (%s)\",e,e.length),console.error(\"This can cause c\\\nonflicts and silent errors executing queries\"));let t=r.types||gs;for(var n=t.length,\ni=M.addCString(e).addCString(r.text).addInt16(n),s=0;s{let e=r.portal||\"\",t=r.statement||\n\"\",n=r.binary||!1,i=r.values||gs,s=i.length;return M.addCString(e).addCString(t),\nM.addInt16(s),Wu(i,r.valueMapper),M.addInt16(s),M.add(Oe.flush()),M.addInt16(n?1:\n0),M.flush(66)},\"bind\"),Hu=y.from([69,0,0,0,9,0,0,0,0,0]),Gu=a(r=>{if(!r||!r.portal&&\n!r.rows)return Hu;let e=r.portal||\"\",t=r.rows||0,n=y.byteLength(e),i=4+n+1+4,s=y.\nallocUnsafe(1+i);return s[0]=69,s.writeInt32BE(i,1),s.write(e,5,\"utf-8\"),s[n+5]=\n0,s.writeUInt32BE(t,s.length-4),s},\"execute\"),$u=a((r,e)=>{let t=y.allocUnsafe(16);\nreturn t.writeInt32BE(16,0),t.writeInt16BE(1234,4),t.writeInt16BE(5678,6),t.writeInt32BE(\nr,8),t.writeInt32BE(e,12),t},\"cancel\"),en=a((r,e)=>{let n=4+y.byteLength(e)+1,i=y.\nallocUnsafe(1+n);return i[0]=r,i.writeInt32BE(n,1),i.write(e,5,\"utf-8\"),i[n]=0,i},\n\"cstringMessage\"),Vu=M.addCString(\"P\").flush(68),Ku=M.addCString(\"S\").flush(68),\nzu=a(r=>r.name?en(68,`${r.type}${r.name||\"\"}`):r.type===\"P\"?Vu:Ku,\"describe\"),Yu=a(\nr=>{let e=`${r.type}${r.name||\"\"}`;return en(67,e)},\"close\"),Zu=a(r=>M.add(r).flush(\n100),\"copyData\"),Ju=a(r=>en(102,r),\"copyFail\"),St=a(r=>y.from([r,0,0,0,4]),\"code\\\nOnlyBuffer\"),Xu=St(72),ec=St(83),tc=St(88),rc=St(99),nc={startup:Du,password:Uu,\nrequestSsl:ku,sendSASLInitialResponseMessage:Ou,sendSCRAMClientFinalMessage:Nu,query:qu,\nparse:Qu,bind:ju,execute:Gu,describe:zu,close:Yu,flush:a(()=>Xu,\"flush\"),sync:a(\n()=>ec,\"sync\"),end:a(()=>tc,\"end\"),copyData:Zu,copyDone:a(()=>rc,\"copyDone\"),copyFail:Ju,\ncancel:$u};xt.serialize=nc});var bs=I(vt=>{\"use strict\";p();Object.defineProperty(vt,\"__esModule\",{value:!0});\nvt.BufferReader=void 0;var ic=y.allocUnsafe(0),rn=class rn{constructor(e=0){this.\noffset=e,this.buffer=ic,this.encoding=\"utf-8\"}setBuffer(e,t){this.offset=e,this.\nbuffer=t}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=\n2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.\nbuffer.readInt32BE(this.offset);return this.offset+=4,e}string(e){let t=this.buffer.\ntoString(this.encoding,this.offset,this.offset+e);return this.offset+=e,t}cstring(){\nlet e=this.offset,t=e;for(;this.buffer[t++]!==0;);return this.offset=t,this.buffer.\ntoString(this.encoding,e,t-1)}bytes(e){let t=this.buffer.slice(this.offset,this.\noffset+e);return this.offset+=e,t}};a(rn,\"BufferReader\");var tn=rn;vt.BufferReader=\ntn});var vs=I(Et=>{\"use strict\";p();Object.defineProperty(Et,\"__esModule\",{value:!0});\nEt.Parser=void 0;var D=Yr(),sc=bs(),nn=1,oc=4,Ss=nn+oc,xs=y.allocUnsafe(0),on=class on{constructor(e){\nif(this.buffer=xs,this.bufferLength=0,this.bufferOffset=0,this.reader=new sc.BufferReader,\ne?.mode===\"binary\")throw new Error(\"Binary mode not supported yet\");this.mode=e?.\nmode||\"text\"}parse(e,t){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,\ni=this.bufferOffset;for(;i+Ss<=n;){let s=this.buffer[i],o=this.buffer.readUInt32BE(\ni+nn),u=nn+o;if(u+i<=n){let c=this.handlePacket(i+Ss,s,o,this.buffer);t(c),i+=u}else\nbreak}i===n?(this.buffer=xs,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=\nn-i,this.bufferOffset=i)}mergeBuffer(e){if(this.bufferLength>0){let t=this.bufferLength+\ne.byteLength;if(t+this.bufferOffset>this.buffer.byteLength){let i;if(t<=this.buffer.\nbyteLength&&this.bufferOffset>=this.bufferLength)i=this.buffer;else{let s=this.buffer.\nbyteLength*2;for(;t>=s;)s*=2;i=y.allocUnsafe(s)}this.buffer.copy(i,0,this.bufferOffset,\nthis.bufferOffset+this.bufferLength),this.buffer=i,this.bufferOffset=0}e.copy(this.\nbuffer,this.bufferOffset+this.bufferLength),this.bufferLength=t}else this.buffer=\ne,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,t,n,i){switch(t){case 50:\nreturn D.bindComplete;case 49:return D.parseComplete;case 51:return D.closeComplete;case 110:\nreturn D.noData;case 115:return D.portalSuspended;case 99:return D.copyDone;case 87:\nreturn D.replicationStart;case 73:return D.emptyQuery;case 68:return this.parseDataRowMessage(\ne,n,i);case 67:return this.parseCommandCompleteMessage(e,n,i);case 90:return this.\nparseReadyForQueryMessage(e,n,i);case 65:return this.parseNotificationMessage(e,\nn,i);case 82:return this.parseAuthenticationResponse(e,n,i);case 83:return this.\nparseParameterStatusMessage(e,n,i);case 75:return this.parseBackendKeyData(e,n,i);case 69:\nreturn this.parseErrorMessage(e,n,i,\"error\");case 78:return this.parseErrorMessage(\ne,n,i,\"notice\");case 84:return this.parseRowDescriptionMessage(e,n,i);case 116:return this.\nparseParameterDescriptionMessage(e,n,i);case 71:return this.parseCopyInMessage(e,\nn,i);case 72:return this.parseCopyOutMessage(e,n,i);case 100:return this.parseCopyData(\ne,n,i);default:return new D.DatabaseError(\"received invalid response: \"+t.toString(\n16),n,\"error\")}}parseReadyForQueryMessage(e,t,n){this.reader.setBuffer(e,n);let i=this.\nreader.string(1);return new D.ReadyForQueryMessage(t,i)}parseCommandCompleteMessage(e,t,n){\nthis.reader.setBuffer(e,n);let i=this.reader.cstring();return new D.CommandCompleteMessage(\nt,i)}parseCopyData(e,t,n){let i=n.slice(e,e+(t-4));return new D.CopyDataMessage(\nt,i)}parseCopyInMessage(e,t,n){return this.parseCopyMessage(e,t,n,\"copyInRespons\\\ne\")}parseCopyOutMessage(e,t,n){return this.parseCopyMessage(e,t,n,\"copyOutRespon\\\nse\")}parseCopyMessage(e,t,n,i){this.reader.setBuffer(e,n);let s=this.reader.byte()!==\n0,o=this.reader.int16(),u=new D.CopyResponse(t,i,s,o);for(let c=0;c{\"use strict\";p();Object.defineProperty(Se,\"__esModule\",{value:!0});\nSe.DatabaseError=Se.serialize=Se.parse=void 0;var ac=Yr();Object.defineProperty(\nSe,\"DatabaseError\",{enumerable:!0,get:a(function(){return ac.DatabaseError},\"get\")});\nvar uc=ws();Object.defineProperty(Se,\"serialize\",{enumerable:!0,get:a(function(){\nreturn uc.serialize},\"get\")});var cc=vs();function hc(r,e){let t=new cc.Parser;return r.\non(\"data\",n=>t.parse(n,e)),new Promise(n=>r.on(\"end\",()=>n()))}a(hc,\"parse\");Se.\nparse=hc});var Es={};ie(Es,{connect:()=>lc});function lc({socket:r,servername:e}){return r.\nstartTls(e),r}var _s=z(()=>{\"use strict\";p();a(lc,\"connect\")});var hn=I((tf,Ts)=>{\"use strict\";p();var As=(wt(),N(ys)),fc=we().EventEmitter,{parse:pc,\nserialize:Q}=an(),Cs=Q.flush(),dc=Q.sync(),yc=Q.end(),cn=class cn extends fc{constructor(e){\nsuper(),e=e||{},this.stream=e.stream||new As.Socket,this._keepAlive=e.keepAlive,\nthis._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.lastBuffer=\n!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=\n!1;var t=this;this.on(\"newListener\",function(n){n===\"message\"&&(t._emitMessage=!0)})}connect(e,t){\nvar n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,\nt),this.stream.once(\"connect\",function(){n._keepAlive&&n.stream.setKeepAlive(!0,\nn._keepAliveInitialDelayMillis),n.emit(\"connect\")});let i=a(function(s){n._ending&&\n(s.code===\"ECONNRESET\"||s.code===\"EPIPE\")||n.emit(\"error\",s)},\"reportStreamError\");\nif(this.stream.on(\"error\",i),this.stream.on(\"close\",function(){n.emit(\"end\")}),!this.\nssl)return this.attachListeners(this.stream);this.stream.once(\"data\",function(s){\nvar o=s.toString(\"utf8\");switch(o){case\"S\":break;case\"N\":return n.stream.end(),n.\nemit(\"error\",new Error(\"The server does not support SSL connections\"));default:return n.\nstream.end(),n.emit(\"error\",new Error(\"There was an error establishing an SSL co\\\nnnection\"))}var u=(_s(),N(Es));let c={socket:n.stream};n.ssl!==!0&&(Object.assign(\nc,n.ssl),\"key\"in n.ssl&&(c.key=n.ssl.key)),As.isIP(t)===0&&(c.servername=t);try{\nn.stream=u.connect(c)}catch(h){return n.emit(\"error\",h)}n.attachListeners(n.stream),\nn.stream.on(\"error\",i),n.emit(\"sslconnect\")})}attachListeners(e){e.on(\"end\",()=>{\nthis.emit(\"end\")}),pc(e,t=>{var n=t.name===\"error\"?\"errorMessage\":t.name;this._emitMessage&&\nthis.emit(\"message\",t),this.emit(n,t)})}requestSsl(){this.stream.write(Q.requestSsl())}startup(e){\nthis.stream.write(Q.startup(e))}cancel(e,t){this._send(Q.cancel(e,t))}password(e){\nthis._send(Q.password(e))}sendSASLInitialResponseMessage(e,t){this._send(Q.sendSASLInitialResponseMessage(\ne,t))}sendSCRAMClientFinalMessage(e){this._send(Q.sendSCRAMClientFinalMessage(e))}_send(e){\nreturn this.stream.writable?this.stream.write(e):!1}query(e){this._send(Q.query(\ne))}parse(e){this._send(Q.parse(e))}bind(e){this._send(Q.bind(e))}execute(e){this.\n_send(Q.execute(e))}flush(){this.stream.writable&&this.stream.write(Cs)}sync(){this.\n_ending=!0,this._send(Cs),this._send(dc)}ref(){this.stream.ref()}unref(){this.stream.\nunref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.\nstream.end();return}return this.stream.write(yc,()=>{this.stream.end()})}close(e){\nthis._send(Q.close(e))}describe(e){this._send(Q.describe(e))}sendCopyFromChunk(e){\nthis._send(Q.copyData(e))}endCopyFrom(){this._send(Q.copyDone())}sendCopyFail(e){\nthis._send(Q.copyFail(e))}};a(cn,\"Connection\");var un=cn;Ts.exports=un});var Bs=I((of,Ps)=>{\"use strict\";p();var mc=we().EventEmitter,sf=(He(),N(je)),gc=et(),\nln=qi(),wc=Zi(),bc=mt(),Sc=gt(),Is=ps(),xc=Xe(),vc=hn(),fn=class fn extends mc{constructor(e){\nsuper(),this.connectionParameters=new Sc(e),this.user=this.connectionParameters.\nuser,this.database=this.connectionParameters.database,this.port=this.connectionParameters.\nport,this.host=this.connectionParameters.host,Object.defineProperty(this,\"passwo\\\nrd\",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),\nthis.replication=this.connectionParameters.replication;var t=e||{};this._Promise=\nt.Promise||S.Promise,this._types=new bc(t.types),this._ending=!1,this._connecting=\n!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=\nt.connection||new vc({stream:t.stream,ssl:this.connectionParameters.ssl,keepAlive:t.\nkeepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.\nconnectionParameters.client_encoding||\"utf8\"}),this.queryQueue=[],this.binary=t.\nbinary||xc.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.\nssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,\"key\",{enumerable:!1}),\nthis._connectionTimeoutMillis=t.connectionTimeoutMillis||0}_errorAllQueries(e){let t=a(\nn=>{m.nextTick(()=>{n.handleError(e,this.connection)})},\"enqueueError\");this.activeQuery&&\n(t(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(t),this.queryQueue.\nlength=0}_connect(e){var t=this,n=this.connection;if(this._connectionCallback=e,\nthis._connecting||this._connected){let i=new Error(\"Client has already been conn\\\nected. You cannot reuse a client.\");m.nextTick(()=>{e(i)});return}this._connecting=\n!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=\nsetTimeout(()=>{n._ending=!0,n.stream.destroy(new Error(\"timeout expired\"))},this.\n_connectionTimeoutMillis)),this.host&&this.host.indexOf(\"/\")===0?n.connect(this.\nhost+\"/.s.PGSQL.\"+this.port):n.connect(this.port,this.host),n.on(\"connect\",function(){\nt.ssl?n.requestSsl():n.startup(t.getStartupConf())}),n.on(\"sslconnect\",function(){\nn.startup(t.getStartupConf())}),this._attachListeners(n),n.once(\"end\",()=>{let i=this.\n_ending?new Error(\"Connection terminated\"):new Error(\"Connection terminated unex\\\npectedly\");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(i),this.\n_ending||(this._connecting&&!this._connectionError?this._connectionCallback?this.\n_connectionCallback(i):this._handleErrorEvent(i):this._connectionError||this._handleErrorEvent(\ni)),m.nextTick(()=>{this.emit(\"end\")})})}connect(e){if(e){this._connect(e);return}\nreturn new this._Promise((t,n)=>{this._connect(i=>{i?n(i):t()})})}_attachListeners(e){\ne.on(\"authenticationCleartextPassword\",this._handleAuthCleartextPassword.bind(this)),\ne.on(\"authenticationMD5Password\",this._handleAuthMD5Password.bind(this)),e.on(\"a\\\nuthenticationSASL\",this._handleAuthSASL.bind(this)),e.on(\"authenticationSASLCont\\\ninue\",this._handleAuthSASLContinue.bind(this)),e.on(\"authenticationSASLFinal\",this.\n_handleAuthSASLFinal.bind(this)),e.on(\"backendKeyData\",this._handleBackendKeyData.\nbind(this)),e.on(\"error\",this._handleErrorEvent.bind(this)),e.on(\"errorMessage\",\nthis._handleErrorMessage.bind(this)),e.on(\"readyForQuery\",this._handleReadyForQuery.\nbind(this)),e.on(\"notice\",this._handleNotice.bind(this)),e.on(\"rowDescription\",this.\n_handleRowDescription.bind(this)),e.on(\"dataRow\",this._handleDataRow.bind(this)),\ne.on(\"portalSuspended\",this._handlePortalSuspended.bind(this)),e.on(\"emptyQuery\",\nthis._handleEmptyQuery.bind(this)),e.on(\"commandComplete\",this._handleCommandComplete.\nbind(this)),e.on(\"parseComplete\",this._handleParseComplete.bind(this)),e.on(\"cop\\\nyInResponse\",this._handleCopyInResponse.bind(this)),e.on(\"copyData\",this._handleCopyData.\nbind(this)),e.on(\"notification\",this._handleNotification.bind(this))}_checkPgPass(e){\nlet t=this.connection;typeof this.password==\"function\"?this._Promise.resolve().then(\n()=>this.password()).then(n=>{if(n!==void 0){if(typeof n!=\"string\"){t.emit(\"erro\\\nr\",new TypeError(\"Password must be a string\"));return}this.connectionParameters.\npassword=this.password=n}else this.connectionParameters.password=this.password=null;\ne()}).catch(n=>{t.emit(\"error\",n)}):this.password!==null?e():wc(this.connectionParameters,\nn=>{n!==void 0&&(this.connectionParameters.password=this.password=n),e()})}_handleAuthCleartextPassword(e){\nthis._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){\nthis._checkPgPass(()=>{let t=gc.postgresMd5PasswordHash(this.user,this.password,\ne.salt);this.connection.password(t)})}_handleAuthSASL(e){this._checkPgPass(()=>{\nthis.saslSession=ln.startSession(e.mechanisms),this.connection.sendSASLInitialResponseMessage(\nthis.saslSession.mechanism,this.saslSession.response)})}_handleAuthSASLContinue(e){\nln.continueSession(this.saslSession,this.password,e.data),this.connection.sendSCRAMClientFinalMessage(\nthis.saslSession.response)}_handleAuthSASLFinal(e){ln.finalizeSession(this.saslSession,\ne.data),this.saslSession=null}_handleBackendKeyData(e){this.processID=e.processID,\nthis.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=\n!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&\n(this._connectionCallback(null,this),this._connectionCallback=null),this.emit(\"c\\\nonnect\"));let{activeQuery:t}=this;this.activeQuery=null,this.readyForQuery=!0,t&&\nt.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){\nif(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),\nthis._connectionCallback)return this._connectionCallback(e);this.emit(\"error\",e)}}_handleErrorEvent(e){\nif(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,\nthis._errorAllQueries(e),this.emit(\"error\",e)}_handleErrorMessage(e){if(this._connecting)\nreturn this._handleErrorWhileConnecting(e);let t=this.activeQuery;if(!t){this._handleErrorEvent(\ne);return}this.activeQuery=null,t.handleError(e,this.connection)}_handleRowDescription(e){\nthis.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(\ne)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){\nthis.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){this.\nactiveQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(e){this.\nactiveQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.\nactiveQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(\nthis.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){\nthis.emit(\"notification\",e)}_handleNotice(e){this.emit(\"notice\",e)}getStartupConf(){\nvar e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name||\ne.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication=\n\"\"+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,\n10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&\n(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,\n10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){var n=this.\nconnection;this.host&&this.host.indexOf(\"/\")===0?n.connect(this.host+\"/.s.PGSQL.\"+\nthis.port):n.connect(this.port,this.host),n.on(\"connect\",function(){n.cancel(e.processID,\ne.secretKey)})}else e.queryQueue.indexOf(t)!==-1&&e.queryQueue.splice(e.queryQueue.\nindexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){\nreturn this._types.getTypeParser(e,t)}escapeIdentifier(e){return'\"'+e.replace(/\"/g,\n'\"\"')+'\"'}escapeLiteral(e){for(var t=!1,n=\"'\",i=0;i{this.activeQuery.handleError(e,this.connection),this.readyForQuery=\n!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.\nemit(\"drain\"))}query(e,t,n){var i,s,o,u,c;if(e==null)throw new TypeError(\"Client\\\n was passed a null or undefined query\");return typeof e.submit==\"function\"?(o=e.\nquery_timeout||this.connectionParameters.query_timeout,s=i=e,typeof t==\"function\"&&\n(i.callback=i.callback||t)):(o=this.connectionParameters.query_timeout,i=new Is(\ne,t,n),i.callback||(s=new this._Promise((h,l)=>{i.callback=(d,b)=>d?l(d):h(b)}))),\no&&(c=i.callback,u=setTimeout(()=>{var h=new Error(\"Query read timeout\");m.nextTick(\n()=>{i.handleError(h,this.connection)}),c(h),i.callback=()=>{};var l=this.queryQueue.\nindexOf(i);l>-1&&this.queryQueue.splice(l,1),this._pulseQueryQueue()},o),i.callback=\n(h,l)=>{clearTimeout(u),c(h,l)}),this.binary&&!i.binary&&(i.binary=!0),i._result&&\n!i._result._types&&(i._result._types=this._types),this._queryable?this._ending?(m.\nnextTick(()=>{i.handleError(new Error(\"Client was closed and is not queryable\"),\nthis.connection)}),s):(this.queryQueue.push(i),this._pulseQueryQueue(),s):(m.nextTick(\n()=>{i.handleError(new Error(\"Client has encountered a connection error and is n\\\not queryable\"),this.connection)}),s)}ref(){this.connection.ref()}unref(){this.connection.\nunref()}end(e){if(this._ending=!0,!this.connection._connecting)if(e)e();else return this.\n_Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.\ndestroy():this.connection.end(),e)this.connection.once(\"end\",e);else return new this.\n_Promise(t=>{this.connection.once(\"end\",t)})}};a(fn,\"Client\");var _t=fn;_t.Query=\nIs;Ps.exports=_t});var Ms=I((cf,Fs)=>{\"use strict\";p();var Ec=we().EventEmitter,Ls=a(function(){},\"\\\nNOOP\"),Rs=a((r,e)=>{let t=r.findIndex(e);return t===-1?void 0:r.splice(t,1)[0]},\n\"removeWhere\"),yn=class yn{constructor(e,t,n){this.client=e,this.idleListener=t,\nthis.timeoutId=n}};a(yn,\"IdleItem\");var pn=yn,mn=class mn{constructor(e){this.callback=\ne}};a(mn,\"PendingItem\");var Ne=mn;function _c(){throw new Error(\"Release called \\\non client which has already been released to the pool.\")}a(_c,\"throwOnDoubleRele\\\nase\");function At(r,e){if(e)return{callback:e,result:void 0};let t,n,i=a(function(o,u){\no?t(o):n(u)},\"cb\"),s=new r(function(o,u){n=o,t=u}).catch(o=>{throw Error.captureStackTrace(\no),o});return{callback:i,result:s}}a(At,\"promisify\");function Ac(r,e){return a(function t(n){\nn.client=e,e.removeListener(\"error\",t),e.on(\"error\",()=>{r.log(\"additional clien\\\nt error after disconnection due to error\",n)}),r._remove(e),r.emit(\"error\",n,e)},\n\"idleListener\")}a(Ac,\"makeIdleListener\");var gn=class gn extends Ec{constructor(e,t){\nsuper(),this.options=Object.assign({},e),e!=null&&\"password\"in e&&Object.defineProperty(\nthis.options,\"password\",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),\ne!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,\"key\",{enumerable:!1}),\nthis.options.max=this.options.max||this.options.poolSize||10,this.options.maxUses=\nthis.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||\n!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.\noptions.log||function(){},this.Client=this.options.Client||t||Ct().Client,this.Promise=\nthis.options.Promise||S.Promise,typeof this.options.idleTimeoutMillis>\"u\"&&(this.\noptions.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,\nthis._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){\nreturn this._clients.length>=this.options.max}_pulseQueue(){if(this.log(\"pulse q\\\nueue\"),this.ended){this.log(\"pulse queue ended\");return}if(this.ending){this.log(\n\"pulse queue on ending\"),this._idle.length&&this._idle.slice().map(t=>{this._remove(\nt.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this.\n_pendingQueue.length){this.log(\"no queued requests\");return}if(!this._idle.length&&\nthis._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this.\n_idle.pop();clearTimeout(t.timeoutId);let n=t.client;n.ref&&n.ref();let i=t.idleListener;\nreturn this._acquireClient(n,e,i,!1)}if(!this._isFull())return this.newClient(e);\nthrow new Error(\"unexpected condition\")}_remove(e){let t=Rs(this._idle,n=>n.client===\ne);t!==void 0&&clearTimeout(t.timeoutId),this._clients=this._clients.filter(n=>n!==\ne),e.end(),this.emit(\"remove\",e)}connect(e){if(this.ending){let i=new Error(\"Can\\\nnot use a pool after calling end on the pool\");return e?e(i):this.Promise.reject(\ni)}let t=At(this.Promise,e),n=t.result;if(this._isFull()||this._idle.length){if(this.\n_idle.length&&m.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)\nreturn this._pendingQueue.push(new Ne(t.callback)),n;let i=a((u,c,h)=>{clearTimeout(\no),t.callback(u,c,h)},\"queueCallback\"),s=new Ne(i),o=setTimeout(()=>{Rs(this._pendingQueue,\nu=>u.callback===i),s.timedOut=!0,t.callback(new Error(\"timeout exceeded when try\\\ning to connect\"))},this.options.connectionTimeoutMillis);return this._pendingQueue.\npush(s),n}return this.newClient(new Ne(t.callback)),n}newClient(e){let t=new this.\nClient(this.options);this._clients.push(t);let n=Ac(this,t);this.log(\"checking c\\\nlient timeout\");let i,s=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{\nthis.log(\"ending client due to timeout\"),s=!0,t.connection?t.connection.stream.destroy():\nt.end()},this.options.connectionTimeoutMillis)),this.log(\"connecting new client\"),\nt.connect(o=>{if(i&&clearTimeout(i),t.on(\"error\",n),o)this.log(\"client failed to\\\n connect\",o),this._clients=this._clients.filter(u=>u!==t),s&&(o.message=\"Connect\\\nion terminated due to connection timeout\"),this._pulseQueue(),e.timedOut||e.callback(\no,void 0,Ls);else{if(this.log(\"new client connected\"),this.options.maxLifetimeSeconds!==\n0){let u=setTimeout(()=>{this.log(\"ending client due to expired lifetime\"),this.\n_expired.add(t),this._idle.findIndex(h=>h.client===t)!==-1&&this._acquireClient(\nt,new Ne((h,l,d)=>d()),n,!1)},this.options.maxLifetimeSeconds*1e3);u.unref(),t.once(\n\"end\",()=>clearTimeout(u))}return this._acquireClient(t,e,n,!0)}})}_acquireClient(e,t,n,i){\ni&&this.emit(\"connect\",e),this.emit(\"acquire\",e),e.release=this._releaseOnce(e,n),\ne.removeListener(\"error\",n),t.timedOut?i&&this.options.verify?this.options.verify(\ne,e.release):e.release():i&&this.options.verify?this.options.verify(e,s=>{if(s)return e.\nrelease(s),t.callback(s,void 0,Ls);t.callback(void 0,e,e.release)}):t.callback(void 0,\ne,e.release)}_releaseOnce(e,t){let n=!1;return i=>{n&&_c(),n=!0,this._release(e,\nt,i)}}_release(e,t,n){if(e.on(\"error\",t),e._poolUseCount=(e._poolUseCount||0)+1,\nthis.emit(\"release\",n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=\nthis.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log(\"remove ex\\\npended client\"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){\nthis.log(\"remove expired client\"),this._expired.delete(e),this._remove(e),this._pulseQueue();\nreturn}let s;this.options.idleTimeoutMillis&&(s=setTimeout(()=>{this.log(\"remove\\\n idle client\"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&\ns.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new pn(e,t,s)),\nthis._pulseQueue()}query(e,t,n){if(typeof e==\"function\"){let s=At(this.Promise,e);\nreturn x(function(){return s.callback(new Error(\"Passing a function as the first\\\n parameter to pool.query is not supported\"))}),s.result}typeof t==\"function\"&&(n=\nt,t=void 0);let i=At(this.Promise,n);return n=i.callback,this.connect((s,o)=>{if(s)\nreturn n(s);let u=!1,c=a(h=>{u||(u=!0,o.release(h),n(h))},\"onError\");o.once(\"err\\\nor\",c),this.log(\"dispatching query\");try{o.query(e,t,(h,l)=>{if(this.log(\"query \\\ndispatched\"),o.removeListener(\"error\",c),!u)return u=!0,o.release(h),h?n(h):n(void 0,\nl)})}catch(h){return o.release(h),n(h)}}),i.result}end(e){if(this.log(\"ending\"),\nthis.ending){let n=new Error(\"Called end on pool more than once\");return e?e(n):\nthis.Promise.reject(n)}this.ending=!0;let t=At(this.Promise,e);return this._endCallback=\nt.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.\nlength}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.\nreduce((e,t)=>e+(this._expired.has(t)?1:0),0)}get totalCount(){return this._clients.\nlength}};a(gn,\"Pool\");var dn=gn;Fs.exports=dn});var Ds={};ie(Ds,{default:()=>Cc});var Cc,ks=z(()=>{\"use strict\";p();Cc={}});var Us=I((pf,Tc)=>{Tc.exports={name:\"pg\",version:\"8.8.0\",description:\"PostgreSQL\\\n client - pure javascript & libpq with the same API\",keywords:[\"database\",\"libpq\",\n\"pg\",\"postgre\",\"postgres\",\"postgresql\",\"rdbms\"],homepage:\"https://github.com/bri\\\nanc/node-postgres\",repository:{type:\"git\",url:\"git://github.com/brianc/node-post\\\ngres.git\",directory:\"packages/pg\"},author:\"Brian Carlson \",main:\"./lib\",dependencies:{\"buffer-writer\":\"2.0.0\",\"packet-reader\":\"1.0.0\",\n\"pg-connection-string\":\"^2.5.0\",\"pg-pool\":\"^3.5.2\",\"pg-protocol\":\"^1.5.0\",\"pg-ty\\\npes\":\"^2.1.0\",pgpass:\"1.x\"},devDependencies:{async:\"2.6.4\",bluebird:\"3.5.2\",co:\"\\\n4.6.0\",\"pg-copy-streams\":\"0.3.0\"},peerDependencies:{\"pg-native\":\">=3.0.1\"},peerDependenciesMeta:{\n\"pg-native\":{optional:!0}},scripts:{test:\"make test-all\"},files:[\"lib\",\"SPONSORS\\\n.md\"],license:\"MIT\",engines:{node:\">= 8.0.0\"},gitHead:\"c99fb2c127ddf8d712500db2c\\\n7b9a5491a178655\"}});var qs=I((df,Ns)=>{\"use strict\";p();var Os=we().EventEmitter,Ic=(He(),N(je)),wn=et(),\nqe=Ns.exports=function(r,e,t){Os.call(this),r=wn.normalizeQueryConfig(r,e,t),this.\ntext=r.text,this.values=r.values,this.name=r.name,this.callback=r.callback,this.\nstate=\"new\",this._arrayMode=r.rowMode===\"array\",this._emitRowEvents=!1,this.on(\"\\\nnewListener\",function(n){n===\"row\"&&(this._emitRowEvents=!0)}.bind(this))};Ic.inherits(\nqe,Os);var Pc={sqlState:\"code\",statementPosition:\"position\",messagePrimary:\"mess\\\nage\",context:\"where\",schemaName:\"schema\",tableName:\"table\",columnName:\"column\",dataTypeName:\"\\\ndataType\",constraintName:\"constraint\",sourceFile:\"file\",sourceLine:\"line\",sourceFunction:\"\\\nroutine\"};qe.prototype.handleError=function(r){var e=this.native.pq.resultErrorFields();\nif(e)for(var t in e){var n=Pc[t]||t;r[n]=e[t]}this.callback?this.callback(r):this.\nemit(\"error\",r),this.state=\"error\"};qe.prototype.then=function(r,e){return this.\n_getPromise().then(r,e)};qe.prototype.catch=function(r){return this._getPromise().\ncatch(r)};qe.prototype._getPromise=function(){return this._promise?this._promise:\n(this._promise=new Promise(function(r,e){this._once(\"end\",r),this._once(\"error\",\ne)}.bind(this)),this._promise)};qe.prototype.submit=function(r){this.state=\"runn\\\ning\";var e=this;this.native=r.native,r.native.arrayMode=this._arrayMode;var t=a(\nfunction(s,o,u){if(r.native.arrayMode=!1,x(function(){e.emit(\"_done\")}),s)return e.\nhandleError(s);e._emitRowEvents&&(u.length>1?o.forEach((c,h)=>{c.forEach(l=>{e.emit(\n\"row\",l,u[h])})}):o.forEach(function(c){e.emit(\"row\",c,u)})),e.state=\"end\",e.emit(\n\"end\",u),e.callback&&e.callback(null,u)},\"after\");if(m.domain&&(t=m.domain.bind(\nt)),this.name){this.name.length>63&&(console.error(\"Warning! Postgres only suppo\\\nrts 63 characters for query names.\"),console.error(\"You supplied %s (%s)\",this.name,\nthis.name.length),console.error(\"This can cause conflicts and silent errors exec\\\nuting queries\"));var n=(this.values||[]).map(wn.prepareValue);if(r.namedQueries[this.\nname]){if(this.text&&r.namedQueries[this.name]!==this.text){let s=new Error(`Pre\\\npared statements must be unique - '${this.name}' was used for a different statem\\\nent`);return t(s)}return r.native.execute(this.name,n,t)}return r.native.prepare(\nthis.name,this.text,n.length,function(s){return s?t(s):(r.namedQueries[e.name]=e.\ntext,e.native.execute(e.name,n,t))})}else if(this.values){if(!Array.isArray(this.\nvalues)){let s=new Error(\"Query values must be an array\");return t(s)}var i=this.\nvalues.map(wn.prepareValue);r.native.query(this.text,i,t)}else r.native.query(this.\ntext,t)}});var Hs=I((wf,js)=>{\"use strict\";p();var Bc=(ks(),N(Ds)),Lc=mt(),gf=Us(),Qs=we().\nEventEmitter,Rc=(He(),N(je)),Fc=gt(),Ws=qs(),J=js.exports=function(r){Qs.call(this),\nr=r||{},this._Promise=r.Promise||S.Promise,this._types=new Lc(r.types),this.native=\nnew Bc({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=\n!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new Fc(\nr);this.user=e.user,Object.defineProperty(this,\"password\",{configurable:!0,enumerable:!1,\nwritable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=\ne.port,this.namedQueries={}};J.Query=Ws;Rc.inherits(J,Qs);J.prototype._errorAllQueries=\nfunction(r){let e=a(t=>{m.nextTick(()=>{t.native=this.native,t.handleError(r)})},\n\"enqueueError\");this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=\nnull),this._queryQueue.forEach(e),this._queryQueue.length=0};J.prototype._connect=\nfunction(r){var e=this;if(this._connecting){m.nextTick(()=>r(new Error(\"Client h\\\nas already been connected. You cannot reuse a client.\")));return}this._connecting=\n!0,this.connectionParameters.getLibpqConnectionString(function(t,n){if(t)return r(\nt);e.native.connect(n,function(i){if(i)return e.native.end(),r(i);e._connected=!0,\ne.native.on(\"error\",function(s){e._queryable=!1,e._errorAllQueries(s),e.emit(\"er\\\nror\",s)}),e.native.on(\"notification\",function(s){e.emit(\"notification\",{channel:s.\nrelname,payload:s.extra})}),e.emit(\"connect\"),e._pulseQueryQueue(!0),r()})})};J.\nprototype.connect=function(r){if(r){this._connect(r);return}return new this._Promise(\n(e,t)=>{this._connect(n=>{n?t(n):e()})})};J.prototype.query=function(r,e,t){var n,\ni,s,o,u;if(r==null)throw new TypeError(\"Client was passed a null or undefined qu\\\nery\");if(typeof r.submit==\"function\")s=r.query_timeout||this.connectionParameters.\nquery_timeout,i=n=r,typeof e==\"function\"&&(r.callback=e);else if(s=this.connectionParameters.\nquery_timeout,n=new Ws(r,e,t),!n.callback){let c,h;i=new this._Promise((l,d)=>{c=\nl,h=d}),n.callback=(l,d)=>l?h(l):c(d)}return s&&(u=n.callback,o=setTimeout(()=>{\nvar c=new Error(\"Query read timeout\");m.nextTick(()=>{n.handleError(c,this.connection)}),\nu(c),n.callback=()=>{};var h=this._queryQueue.indexOf(n);h>-1&&this._queryQueue.\nsplice(h,1),this._pulseQueryQueue()},s),n.callback=(c,h)=>{clearTimeout(o),u(c,h)}),\nthis._queryable?this._ending?(n.native=this.native,m.nextTick(()=>{n.handleError(\nnew Error(\"Client was closed and is not queryable\"))}),i):(this._queryQueue.push(\nn),this._pulseQueryQueue(),i):(n.native=this.native,m.nextTick(()=>{n.handleError(\nnew Error(\"Client has encountered a connection error and is not queryable\"))}),i)};\nJ.prototype.end=function(r){var e=this;this._ending=!0,this._connected||this.once(\n\"connect\",this.end.bind(this,r));var t;return r||(t=new this._Promise(function(n,i){\nr=a(s=>s?i(s):n(),\"cb\")})),this.native.end(function(){e._errorAllQueries(new Error(\n\"Connection terminated\")),m.nextTick(()=>{e.emit(\"end\"),r&&r()})}),t};J.prototype.\n_hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!==\"\\\nerror\"&&this._activeQuery.state!==\"end\"};J.prototype._pulseQueryQueue=function(r){\nif(this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){\nr||this.emit(\"drain\");return}this._activeQuery=e,e.submit(this);var t=this;e.once(\n\"_done\",function(){t._pulseQueryQueue()})}};J.prototype.cancel=function(r){this.\n_activeQuery===r?this.native.cancel(function(){}):this._queryQueue.indexOf(r)!==\n-1&&this._queryQueue.splice(this._queryQueue.indexOf(r),1)};J.prototype.ref=function(){};\nJ.prototype.unref=function(){};J.prototype.setTypeParser=function(r,e,t){return this.\n_types.setTypeParser(r,e,t)};J.prototype.getTypeParser=function(r,e){return this.\n_types.getTypeParser(r,e)}});var bn=I((xf,Gs)=>{\"use strict\";p();Gs.exports=Hs()});var Ct=I((Ef,rt)=>{\"use strict\";p();var Mc=Bs(),Dc=Xe(),kc=hn(),Uc=Ms(),{DatabaseError:Oc}=an(),\nNc=a(r=>{var e;return e=class extends Uc{constructor(n){super(n,r)}},a(e,\"BoundP\\\nool\"),e},\"poolFactory\"),Sn=a(function(r){this.defaults=Dc,this.Client=r,this.Query=\nthis.Client.Query,this.Pool=Nc(this.Client),this._pools=[],this.Connection=kc,this.\ntypes=Je(),this.DatabaseError=Oc},\"PG\");typeof m.env.NODE_PG_FORCE_NATIVE<\"u\"?rt.\nexports=new Sn(bn()):(rt.exports=new Sn(Mc),Object.defineProperty(rt.exports,\"na\\\ntive\",{configurable:!0,enumerable:!1,get(){var r=null;try{r=new Sn(bn())}catch(e){\nif(e.code!==\"MODULE_NOT_FOUND\")throw e}return Object.defineProperty(rt.exports,\"\\\nnative\",{value:r}),r}}))});p();var Tt=Te(Ct());wt();p();pr();wt();var Ks=Te(et()),zs=Te(mt());var xn=class xn extends Error{constructor(){super(...arguments);_(this,\"name\",\"N\\\neonDbError\");_(this,\"severity\");_(this,\"code\");_(this,\"detail\");_(this,\"hint\");_(\nthis,\"position\");_(this,\"internalPosition\");_(this,\"internalQuery\");_(this,\"wher\\\ne\");_(this,\"schema\");_(this,\"table\");_(this,\"column\");_(this,\"dataType\");_(this,\n\"constraint\");_(this,\"file\");_(this,\"line\");_(this,\"routine\");_(this,\"sourceErro\\\nr\")}};a(xn,\"NeonDbError\");var Ae=xn,$s=\"transaction() expects an array of querie\\\ns, or a function returning an array of queries\",qc=[\"severity\",\"code\",\"detail\",\"\\\nhint\",\"position\",\"internalPosition\",\"internalQuery\",\"where\",\"schema\",\"table\",\"co\\\nlumn\",\"dataType\",\"constraint\",\"file\",\"line\",\"routine\"];function Ys(r,{arrayMode:e,\nfullResults:t,fetchOptions:n,isolationLevel:i,readOnly:s,deferrable:o,queryCallback:u,\nresultCallback:c}={}){if(!r)throw new Error(\"No database connection string was p\\\nrovided to `neon()`. Perhaps an environment variable has not been set?\");let h;try{\nh=fr(r)}catch{throw new Error(\"Database connection string provided to `neon()` i\\\ns not a valid URL. Connection string: \"+String(r))}let{protocol:l,username:d,password:b,\nhostname:C,port:B,pathname:W}=h;if(l!==\"postgres:\"&&l!==\"postgresql:\"||!d||!b||!C||\n!W)throw new Error(\"Database connection string format for `neon()` should be: po\\\nstgresql://user:password@host.tld/dbname?option=value\");function X(A,...w){let P,\nV;if(typeof A==\"string\")P=A,V=w[1],w=w[0]??[];else{P=\"\";for(let j=0;j(0,Ks.prepareValue)(j));let k={query:P,\nparams:w};return u&&u(k),Qc(de,k,V)}a(X,\"resolve\"),X.transaction=async(A,w)=>{if(typeof A==\n\"function\"&&(A=A(X)),!Array.isArray(A))throw new Error($s);A.forEach(k=>{if(k[Symbol.\ntoStringTag]!==\"NeonQueryPromise\")throw new Error($s)});let P=A.map(k=>k.parameterizedQuery),\nV=A.map(k=>k.opts??{});return de(P,V,w)};async function de(A,w,P){let{fetchEndpoint:V,\nfetchFunction:k}=_e,j=typeof V==\"function\"?V(C,B):V,ce=Array.isArray(A)?{queries:A}:\nA,ee=n??{},R=e??!1,G=t??!1,he=i,ye=s,xe=o;P!==void 0&&(P.fetchOptions!==void 0&&\n(ee={...ee,...P.fetchOptions}),P.arrayMode!==void 0&&(R=P.arrayMode),P.fullResults!==\nvoid 0&&(G=P.fullResults),P.isolationLevel!==void 0&&(he=P.isolationLevel),P.readOnly!==\nvoid 0&&(ye=P.readOnly),P.deferrable!==void 0&&(xe=P.deferrable)),w!==void 0&&!Array.\nisArray(w)&&w.fetchOptions!==void 0&&(ee={...ee,...w.fetchOptions});let me={\"Neo\\\nn-Connection-String\":r,\"Neon-Raw-Text-Output\":\"true\",\"Neon-Array-Mode\":\"true\"};Array.\nisArray(A)&&(he!==void 0&&(me[\"Neon-Batch-Isolation-Level\"]=he),ye!==void 0&&(me[\"\\\nNeon-Batch-Read-Only\"]=String(ye)),xe!==void 0&&(me[\"Neon-Batch-Deferrable\"]=String(\nxe)));let se;try{se=await(k??fetch)(j,{method:\"POST\",body:JSON.stringify(ce),headers:me,\n...ee})}catch(oe){let U=new Ae(`Error connecting to database: ${oe.message}`);throw U.\nsourceError=oe,U}if(se.ok){let oe=await se.json();if(Array.isArray(A)){let U=oe.\nresults;if(!Array.isArray(U))throw new Ae(\"Neon internal error: unexpected resul\\\nt format\");return U.map((K,le)=>{let It=w[le]??{},Xs=It.arrayMode??R,eo=It.fullResults??\nG;return Vs(K,{arrayMode:Xs,fullResults:eo,parameterizedQuery:A[le],resultCallback:c,\ntypes:It.types})})}else{let U=w??{},K=U.arrayMode??R,le=U.fullResults??G;return Vs(\noe,{arrayMode:K,fullResults:le,parameterizedQuery:A,resultCallback:c,types:U.types})}}else{\nlet{status:oe}=se;if(oe===400){let U=await se.json(),K=new Ae(U.message);for(let le of qc)\nK[le]=U[le]??void 0;throw K}else{let U=await se.text();throw new Ae(`Server erro\\\nr (HTTP status ${oe}): ${U}`)}}}return a(de,\"execute\"),X}a(Ys,\"neon\");function Qc(r,e,t){\nreturn{[Symbol.toStringTag]:\"NeonQueryPromise\",parameterizedQuery:e,opts:t,then:a(\n(n,i)=>r(e,t).then(n,i),\"then\"),catch:a(n=>r(e,t).catch(n),\"catch\"),finally:a(n=>r(\ne,t).finally(n),\"finally\")}}a(Qc,\"createNeonQueryPromise\");function Vs(r,{arrayMode:e,\nfullResults:t,parameterizedQuery:n,resultCallback:i,types:s}){let o=new zs.default(\ns),u=r.fields.map(l=>l.name),c=r.fields.map(l=>o.getTypeParser(l.dataTypeID)),h=e===\n!0?r.rows.map(l=>l.map((d,b)=>d===null?null:c[b](d))):r.rows.map(l=>Object.fromEntries(\nl.map((d,b)=>[u[b],d===null?null:c[b](d)])));return i&&i(n,r,h,{arrayMode:e,fullResults:t}),\nt?(r.viaNeonFetch=!0,r.rowAsArray=e,r.rows=h,r._parsers=c,r._types=o,r):h}a(Vs,\"\\\nprocessQueryResult\");var Js=Te(gt()),Qe=Te(Ct());var En=class En extends Tt.Client{constructor(t){super(t);this.config=t}get neonConfig(){\nreturn this.connection.stream}connect(t){let{neonConfig:n}=this;n.forceDisablePgSSL&&\n(this.ssl=this.connection.ssl=!1),this.ssl&&n.useSecureWebSocket&&console.warn(\"\\\nSSL is enabled for both Postgres (e.g. ?sslmode=require in the connection string\\\n + forceDisablePgSSL = false) and the WebSocket tunnel (useSecureWebSocket = tru\\\ne). Double encryption will increase latency and CPU usage. It may be appropriate\\\n to disable SSL in the Postgres connection parameters or set forceDisablePgSSL =\\\n true.\");let i=this.config?.host!==void 0||this.config?.connectionString!==void 0||\nm.env.PGHOST!==void 0,s=m.env.USER??m.env.USERNAME;if(!i&&this.host===\"localhost\"&&\nthis.user===s&&this.database===s&&this.password===null)throw new Error(`No datab\\\nase host or connection string was set, and key parameters have default values (h\\\nost: localhost, user: ${s}, db: ${s}, password: null). Is an environment variabl\\\ne missing? Alternatively, if you intended to connect with these parameters, plea\\\nse set the host to 'localhost' explicitly.`);let o=super.connect(t),u=n.pipelineTLS&&\nthis.ssl,c=n.pipelineConnect===\"password\";if(!u&&!n.pipelineConnect)return o;let h=this.\nconnection;if(u&&h.on(\"connect\",()=>h.stream.emit(\"data\",\"S\")),c){h.removeAllListeners(\n\"authenticationCleartextPassword\"),h.removeAllListeners(\"readyForQuery\"),h.once(\n\"readyForQuery\",()=>h.on(\"readyForQuery\",this._handleReadyForQuery.bind(this)));\nlet l=this.ssl?\"sslconnect\":\"connect\";h.on(l,()=>{this._handleAuthCleartextPassword(),\nthis._handleReadyForQuery()})}return o}async _handleAuthSASLContinue(t){let n=this.\nsaslSession,i=this.password,s=t.data;if(n.message!==\"SASLInitialResponse\"||typeof i!=\n\"string\"||typeof s!=\"string\")throw new Error(\"SASL: protocol error\");let o=Object.\nfromEntries(s.split(\",\").map(U=>{if(!/^.=/.test(U))throw new Error(\"SASL: Invali\\\nd attribute pair entry\");let K=U[0],le=U.substring(2);return[K,le]})),u=o.r,c=o.\ns,h=o.i;if(!u||!/^[!-+--~]+$/.test(u))throw new Error(\"SASL: SCRAM-SERVER-FIRST-\\\nMESSAGE: nonce missing/unprintable\");if(!c||!/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.\ntest(c))throw new Error(\"SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing/not base\\\n64\");if(!h||!/^[1-9][0-9]*$/.test(h))throw new Error(\"SASL: SCRAM-SERVER-FIRST-M\\\nESSAGE: missing/invalid iteration count\");if(!u.startsWith(n.clientNonce))throw new Error(\n\"SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce\");\nif(u.length===n.clientNonce.length)throw new Error(\"SASL: SCRAM-SERVER-FIRST-MES\\\nSAGE: server nonce is too short\");let l=parseInt(h,10),d=y.from(c,\"base64\"),b=new TextEncoder,\nC=b.encode(i),B=await g.subtle.importKey(\"raw\",C,{name:\"HMAC\",hash:{name:\"SHA-25\\\n6\"}},!1,[\"sign\"]),W=new Uint8Array(await g.subtle.sign(\"HMAC\",B,y.concat([d,y.from(\n[0,0,0,1])]))),X=W;for(var de=0;deX[K]^W[K]));let A=X,w=await g.subtle.importKey(\n\"raw\",A,{name:\"HMAC\",hash:{name:\"SHA-256\"}},!1,[\"sign\"]),P=new Uint8Array(await g.\nsubtle.sign(\"HMAC\",w,b.encode(\"Client Key\"))),V=await g.subtle.digest(\"SHA-256\",\nP),k=\"n=*,r=\"+n.clientNonce,j=\"r=\"+u+\",s=\"+c+\",i=\"+l,ce=\"c=biws,r=\"+u,ee=k+\",\"+j+\n\",\"+ce,R=await g.subtle.importKey(\"raw\",V,{name:\"HMAC\",hash:{name:\"SHA-256\"}},!1,\n[\"sign\"]);var G=new Uint8Array(await g.subtle.sign(\"HMAC\",R,b.encode(ee))),he=y.\nfrom(P.map((U,K)=>P[K]^G[K])),ye=he.toString(\"base64\");let xe=await g.subtle.importKey(\n\"raw\",A,{name:\"HMAC\",hash:{name:\"SHA-256\"}},!1,[\"sign\"]),me=await g.subtle.sign(\n\"HMAC\",xe,b.encode(\"Server Key\")),se=await g.subtle.importKey(\"raw\",me,{name:\"HM\\\nAC\",hash:{name:\"SHA-256\"}},!1,[\"sign\"]);var oe=y.from(await g.subtle.sign(\"HMAC\",\nse,b.encode(ee)));n.message=\"SASLResponse\",n.serverSignature=oe.toString(\"base64\"),\nn.response=ce+\",p=\"+ye,this.connection.sendSCRAMClientFinalMessage(this.saslSession.\nresponse)}};a(En,\"NeonClient\");var vn=En;function Wc(r,e){if(e)return{callback:e,\nresult:void 0};let t,n,i=a(function(o,u){o?t(o):n(u)},\"cb\"),s=new r(function(o,u){\nn=o,t=u});return{callback:i,result:s}}a(Wc,\"promisify\");var _n=class _n extends Tt.Pool{constructor(){\nsuper(...arguments);_(this,\"Client\",vn);_(this,\"hasFetchUnsupportedListeners\",!1)}on(t,n){\nreturn t!==\"error\"&&(this.hasFetchUnsupportedListeners=!0),super.on(t,n)}query(t,n,i){\nif(!_e.poolQueryViaFetch||this.hasFetchUnsupportedListeners||typeof t==\"function\")\nreturn super.query(t,n,i);typeof n==\"function\"&&(i=n,n=void 0);let s=Wc(this.Promise,\ni);i=s.callback;try{let o=new Js.default(this.options),u=encodeURIComponent,c=encodeURI,\nh=`postgresql://${u(o.user)}:${u(o.password)}@${u(o.host)}/${c(o.database)}`,l=typeof t==\n\"string\"?t:t.text,d=n??t.values??[];Ys(h,{fullResults:!0,arrayMode:t.rowMode===\"\\\narray\"})(l,d,{types:t.types??this.options?.types}).then(C=>i(void 0,C)).catch(C=>i(\nC))}catch(o){i(o)}return s.result}};a(_n,\"NeonPool\");var Zs=_n;var export_ClientBase=Qe.ClientBase;var export_Connection=Qe.Connection;var export_DatabaseError=Qe.DatabaseError;\nvar export_Query=Qe.Query;var export_defaults=Qe.defaults;var export_types=Qe.types;\nexport{vn as Client,export_ClientBase as ClientBase,export_Connection as Connection,\nexport_DatabaseError as DatabaseError,Ae as NeonDbError,Zs as Pool,export_Query as Query,\nexport_defaults as defaults,Ys as neon,_e as neonConfig,export_types as types};\n/*! Bundled license information:\n\nieee754/index.js:\n (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *)\n\nbuffer/index.js:\n (*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n *)\n*/\n", "import type { NeonQueryFunction } from '@neondatabase/serverless';\nimport { types } from '@neondatabase/serverless';\nimport type { BatchItem, BatchResponse } from '~/batch.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { Logger } from '~/logger.ts';\nimport { DefaultLogger } from '~/logger.ts';\nimport { PgDatabase } from '~/pg-core/db.ts';\nimport { PgDialect } from '~/pg-core/dialect.ts';\nimport { createTableRelationsHelpers, extractTablesRelationalConfig } from '~/relations.ts';\nimport type { ExtractTablesWithRelations, RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';\nimport type { DrizzleConfig } from '~/utils.ts';\nimport { type NeonHttpClient, type NeonHttpQueryResultHKT, NeonHttpSession } from './session.ts';\n\nexport interface NeonDriverOptions {\n\tlogger?: Logger;\n}\n\nexport class NeonHttpDriver {\n\tstatic readonly [entityKind]: string = 'NeonDriver';\n\n\tconstructor(\n\t\tprivate client: NeonHttpClient,\n\t\tprivate dialect: PgDialect,\n\t\tprivate options: NeonDriverOptions = {},\n\t) {\n\t\tthis.initMappers();\n\t}\n\n\tcreateSession(\n\t\tschema: RelationalSchemaConfig | undefined,\n\t): NeonHttpSession, TablesRelationalConfig> {\n\t\treturn new NeonHttpSession(this.client, this.dialect, schema, { logger: this.options.logger });\n\t}\n\n\tinitMappers() {\n\t\ttypes.setTypeParser(types.builtins.TIMESTAMPTZ, (val) => val);\n\t\ttypes.setTypeParser(types.builtins.TIMESTAMP, (val) => val);\n\t\ttypes.setTypeParser(types.builtins.DATE, (val) => val);\n\t\ttypes.setTypeParser(types.builtins.INTERVAL, (val) => val);\n\t}\n}\n\nexport class NeonHttpDatabase<\n\tTSchema extends Record = Record,\n> extends PgDatabase {\n\tstatic readonly [entityKind]: string = 'NeonHttpDatabase';\n\n\t/** @internal */\n\tdeclare readonly session: NeonHttpSession>;\n\n\tasync batch, T extends Readonly<[U, ...U[]]>>(\n\t\tbatch: T,\n\t): Promise> {\n\t\treturn this.session.batch(batch) as Promise>;\n\t}\n}\n\nexport function drizzle = Record>(\n\tclient: NeonQueryFunction,\n\tconfig: DrizzleConfig = {},\n): NeonHttpDatabase {\n\tconst dialect = new PgDialect();\n\tlet logger;\n\tif (config.logger === true) {\n\t\tlogger = new DefaultLogger();\n\t} else if (config.logger !== false) {\n\t\tlogger = config.logger;\n\t}\n\n\tlet schema: RelationalSchemaConfig | undefined;\n\tif (config.schema) {\n\t\tconst tablesConfig = extractTablesRelationalConfig(\n\t\t\tconfig.schema,\n\t\t\tcreateTableRelationsHelpers,\n\t\t);\n\t\tschema = {\n\t\t\tfullSchema: config.schema,\n\t\t\tschema: tablesConfig.tables,\n\t\t\ttableNamesMap: tablesConfig.tableNamesMap,\n\t\t};\n\t}\n\n\tconst driver = new NeonHttpDriver(client, dialect, { logger });\n\tconst session = driver.createSession(schema);\n\n\treturn new NeonHttpDatabase(\n\t\tdialect,\n\t\tsession,\n\t\tschema as RelationalSchemaConfig> | undefined,\n\t);\n}\n", "import type { FullQueryResults, NeonQueryFunction, NeonQueryPromise } from '@neondatabase/serverless';\nimport type { BatchItem } from '~/batch.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { Logger } from '~/logger.ts';\nimport { NoopLogger } from '~/logger.ts';\nimport type { PgDialect } from '~/pg-core/dialect.ts';\nimport { PgTransaction } from '~/pg-core/index.ts';\nimport type { SelectedFieldsOrdered } from '~/pg-core/query-builders/select.types.ts';\nimport type { PgQueryResultHKT, PgTransactionConfig, PreparedQueryConfig } from '~/pg-core/session.ts';\nimport { PgPreparedQuery as PgPreparedQuery, PgSession } from '~/pg-core/session.ts';\nimport type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport { fillPlaceholders, type Query } from '~/sql/sql.ts';\nimport { mapResultRow } from '~/utils.ts';\n\nexport type NeonHttpClient = NeonQueryFunction;\n\nconst rawQueryConfig = {\n\tarrayMode: false,\n\tfullResults: true,\n} as const;\nconst queryConfig = {\n\tarrayMode: true,\n\tfullResults: true,\n} as const;\n\nexport class NeonHttpPreparedQuery extends PgPreparedQuery {\n\tstatic readonly [entityKind]: string = 'NeonHttpPreparedQuery';\n\n\tconstructor(\n\t\tprivate client: NeonHttpClient,\n\t\tquery: Query,\n\t\tprivate logger: Logger,\n\t\tprivate fields: SelectedFieldsOrdered | undefined,\n\t\tprivate _isResponseInArrayMode: boolean,\n\t\tprivate customResultMapper?: (rows: unknown[][]) => T['execute'],\n\t) {\n\t\tsuper(query);\n\t}\n\n\tasync execute(placeholderValues: Record | undefined = {}): Promise {\n\t\tconst params = fillPlaceholders(this.query.params, placeholderValues);\n\n\t\tthis.logger.logQuery(this.query.sql, params);\n\n\t\tconst { fields, client, query, customResultMapper } = this;\n\n\t\tif (!fields && !customResultMapper) {\n\t\t\treturn client(query.sql, params, rawQueryConfig);\n\t\t}\n\n\t\tconst result = await client(query.sql, params, queryConfig);\n\n\t\treturn this.mapResult(result);\n\t}\n\n\toverride mapResult(result: unknown): unknown {\n\t\tif (!this.fields && !this.customResultMapper) {\n\t\t\treturn result;\n\t\t}\n\n\t\tconst rows = (result as FullQueryResults).rows;\n\n\t\tif (this.customResultMapper) {\n\t\t\treturn this.customResultMapper(rows);\n\t\t}\n\n\t\treturn rows.map((row) => mapResultRow(this.fields!, row, this.joinsNotNullableMap));\n\t}\n\n\tall(placeholderValues: Record | undefined = {}): Promise {\n\t\tconst params = fillPlaceholders(this.query.params, placeholderValues);\n\t\tthis.logger.logQuery(this.query.sql, params);\n\t\treturn this.client(this.query.sql, params, rawQueryConfig).then((result) => result.rows);\n\t}\n\n\tvalues(placeholderValues: Record | undefined = {}): Promise {\n\t\tconst params = fillPlaceholders(this.query.params, placeholderValues);\n\t\tthis.logger.logQuery(this.query.sql, params);\n\t\treturn this.client(this.query.sql, params, { arrayMode: true, fullResults: true }).then((result) => result.rows);\n\t}\n\n\t/** @internal */\n\tisResponseInArrayMode() {\n\t\treturn this._isResponseInArrayMode;\n\t}\n}\n\nexport interface NeonHttpSessionOptions {\n\tlogger?: Logger;\n}\n\nexport class NeonHttpSession<\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> extends PgSession {\n\tstatic readonly [entityKind]: string = 'NeonHttpSession';\n\n\tprivate logger: Logger;\n\n\tconstructor(\n\t\tprivate client: NeonHttpClient,\n\t\tdialect: PgDialect,\n\t\tprivate schema: RelationalSchemaConfig | undefined,\n\t\tprivate options: NeonHttpSessionOptions = {},\n\t) {\n\t\tsuper(dialect);\n\t\tthis.logger = options.logger ?? new NoopLogger();\n\t}\n\n\tprepareQuery(\n\t\tquery: Query,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\tname: string | undefined,\n\t\tisResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][]) => T['execute'],\n\t): PgPreparedQuery {\n\t\treturn new NeonHttpPreparedQuery(\n\t\t\tthis.client,\n\t\t\tquery,\n\t\t\tthis.logger,\n\t\t\tfields,\n\t\t\tisResponseInArrayMode,\n\t\t\tcustomResultMapper,\n\t\t);\n\t}\n\n\tasync batch, T extends Readonly<[U, ...U[]]>>(queries: T) {\n\t\tconst preparedQueries: PreparedQuery[] = [];\n\t\tconst builtQueries: NeonQueryPromise[] = [];\n\n\t\tfor (const query of queries) {\n\t\t\tconst preparedQuery = query._prepare();\n\t\t\tconst builtQuery = preparedQuery.getQuery();\n\t\t\tpreparedQueries.push(preparedQuery);\n\t\t\tbuiltQueries.push(\n\t\t\t\tthis.client(builtQuery.sql, builtQuery.params, {\n\t\t\t\t\tfullResults: true,\n\t\t\t\t\tarrayMode: preparedQuery.isResponseInArrayMode(),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tconst batchResults = await this.client.transaction(builtQueries, queryConfig);\n\n\t\treturn batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true));\n\t}\n\n\t// change return type to QueryRows\n\tasync query(query: string, params: unknown[]): Promise> {\n\t\tthis.logger.logQuery(query, params);\n\t\tconst result = await this.client(query, params, { arrayMode: true, fullResults: true });\n\t\treturn result;\n\t}\n\n\t// change return type to QueryRows\n\tasync queryObjects(\n\t\tquery: string,\n\t\tparams: unknown[],\n\t): Promise> {\n\t\treturn this.client(query, params, { arrayMode: false, fullResults: true });\n\t}\n\n\toverride async transaction(\n\t\t_transaction: (tx: NeonTransaction) => Promise,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\t_config: PgTransactionConfig = {},\n\t): Promise {\n\t\tthrow new Error('No transactions support in neon-http driver');\n\t}\n}\n\nexport class NeonTransaction<\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> extends PgTransaction {\n\tstatic readonly [entityKind]: string = 'NeonHttpTransaction';\n\n\toverride async transaction(_transaction: (tx: NeonTransaction) => Promise): Promise {\n\t\tthrow new Error('No transactions support in neon-http driver');\n\t\t// const savepointName = `sp${this.nestedIndex + 1}`;\n\t\t// const tx = new NeonTransaction(this.dialect, this.session, this.schema, this.nestedIndex + 1);\n\t\t// await tx.execute(sql.raw(`savepoint ${savepointName}`));\n\t\t// try {\n\t\t// \tconst result = await transaction(tx);\n\t\t// \tawait tx.execute(sql.raw(`release savepoint ${savepointName}`));\n\t\t// \treturn result;\n\t\t// } catch (e) {\n\t\t// \tawait tx.execute(sql.raw(`rollback to savepoint ${savepointName}`));\n\t\t// \tthrow e;\n\t\t// }\n\t}\n}\n\nexport type NeonHttpQueryResult = Omit, 'rows'> & { rows: T[] };\n\nexport interface NeonHttpQueryResultHKT extends PgQueryResultHKT {\n\ttype: NeonHttpQueryResult;\n}\n", "// src/helper/factory/index.ts\nimport { Hono } from \"../../hono.js\";\nvar Factory = class {\n initApp;\n constructor(init) {\n this.initApp = init?.initApp;\n }\n createApp = () => {\n const app = new Hono();\n if (this.initApp) {\n this.initApp(app);\n }\n return app;\n };\n createMiddleware = (middleware) => middleware;\n createHandlers = (...handlers) => {\n return handlers.filter((handler) => handler !== void 0);\n };\n};\nvar createFactory = (init) => new Factory(init);\nvar createMiddleware = (middleware) => createFactory().createMiddleware(middleware);\nexport {\n Factory,\n createFactory,\n createMiddleware\n};\n", "import { Octokit } from \"@octokit/core\";\nimport { createMiddleware } from \"hono/factory\";\n\nimport type {\n FetchRepoWithUsersAndEvents,\n FetchUserById,\n HonoEnv,\n} from \"../types\";\n\nlet octokitInstance: Octokit | undefined;\n\nfunction getOctokitInstance(token: string) {\n if (!octokitInstance) {\n octokitInstance = new Octokit({ auth: token });\n }\n\n return octokitInstance;\n}\n\n/**\n * Middleware to interact with the Github API. It exposes the `fetchUserById`\n * function on the context.\n */\nexport const githubApiMiddleware = createMiddleware(\n async (c, next) => {\n const githubToken = c.env.GITHUB_API_TOKEN;\n const octokit = getOctokitInstance(githubToken);\n const fetchRepoWithUsersAndEvents: FetchRepoWithUsersAndEvents = async ({\n owner,\n repo,\n count,\n }) => {\n try {\n const { repository } = await octokit.graphql<{\n repository: ReturnType;\n }>(\n `\n query lastUsersWithInteractions($owner: String!, $repo: String!, $count: Int!) {\n repository(owner: $owner, name: $repo) {\n id: databaseId,\n fullName: nameWithOwner,\n name,\n description,\n stargazerCount,\n stargazers(last: $count) {\n users: nodes {\n id: databaseId,\n avatar: avatarUrl,\n handle: login,\n name,\n location,\n company,\n email,\n twitterUsername\n }\n }\n watchers(last: $count) {\n totalCount,\n users: nodes {\n id: databaseId,\n avatar: avatarUrl,\n handle: login,\n name,\n location,\n company,\n email,\n twitterUsername\n }\n }\n }\n }\n `,\n {\n count,\n owner,\n repo,\n },\n );\n return repository;\n } catch (error) {\n throw new Error(`Github API: error fetching stargazers: ${error}`);\n }\n };\n\n const fetchUserById: FetchUserById = async (id) => {\n try {\n const { data } = await octokit.request(\"GET /user/{id}\", { id });\n return data;\n } catch (error) {\n throw new Error(`Github API: error fetching user by id: ${error}`);\n }\n };\n\n c.set(\"fetchRepoWithUsersAndEvents\", fetchRepoWithUsersAndEvents);\n c.set(\"fetchUserById\", fetchUserById);\n\n await next();\n },\n);\n", "import { getUserAgent } from \"universal-user-agent\";\nimport Hook from \"before-after-hook\";\nimport { request } from \"@octokit/request\";\nimport { withCustomRequest } from \"@octokit/graphql\";\nimport { createTokenAuth } from \"@octokit/auth-token\";\nimport { VERSION } from \"./version.js\";\nconst noop = () => {\n};\nconst consoleWarn = console.warn.bind(console);\nconst consoleError = console.error.bind(console);\nconst userAgentTrail = `octokit-core.js/${VERSION} ${getUserAgent()}`;\nclass Octokit {\n static VERSION = VERSION;\n static defaults(defaults) {\n const OctokitWithDefaults = class extends this {\n constructor(...args) {\n const options = args[0] || {};\n if (typeof defaults === \"function\") {\n super(defaults(options));\n return;\n }\n super(\n Object.assign(\n {},\n defaults,\n options,\n options.userAgent && defaults.userAgent ? {\n userAgent: `${options.userAgent} ${defaults.userAgent}`\n } : null\n )\n );\n }\n };\n return OctokitWithDefaults;\n }\n static plugins = [];\n /**\n * Attach a plugin (or many) to your Octokit instance.\n *\n * @example\n * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)\n */\n static plugin(...newPlugins) {\n const currentPlugins = this.plugins;\n const NewOctokit = class extends this {\n static plugins = currentPlugins.concat(\n newPlugins.filter((plugin) => !currentPlugins.includes(plugin))\n );\n };\n return NewOctokit;\n }\n constructor(options = {}) {\n const hook = new Hook.Collection();\n const requestDefaults = {\n baseUrl: request.endpoint.DEFAULTS.baseUrl,\n headers: {},\n request: Object.assign({}, options.request, {\n // @ts-ignore internal usage only, no need to type\n hook: hook.bind(null, \"request\")\n }),\n mediaType: {\n previews: [],\n format: \"\"\n }\n };\n requestDefaults.headers[\"user-agent\"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;\n if (options.baseUrl) {\n requestDefaults.baseUrl = options.baseUrl;\n }\n if (options.previews) {\n requestDefaults.mediaType.previews = options.previews;\n }\n if (options.timeZone) {\n requestDefaults.headers[\"time-zone\"] = options.timeZone;\n }\n this.request = request.defaults(requestDefaults);\n this.graphql = withCustomRequest(this.request).defaults(requestDefaults);\n this.log = Object.assign(\n {\n debug: noop,\n info: noop,\n warn: consoleWarn,\n error: consoleError\n },\n options.log\n );\n this.hook = hook;\n if (!options.authStrategy) {\n if (!options.auth) {\n this.auth = async () => ({\n type: \"unauthenticated\"\n });\n } else {\n const auth = createTokenAuth(options.auth);\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n } else {\n const { authStrategy, ...otherOptions } = options;\n const auth = authStrategy(\n Object.assign(\n {\n request: this.request,\n log: this.log,\n // we pass the current octokit instance as well as its constructor options\n // to allow for authentication strategies that return a new octokit instance\n // that shares the same internal state as the current one. The original\n // requirement for this was the \"event-octokit\" authentication strategy\n // of https://github.com/probot/octokit-auth-probot.\n octokit: this,\n octokitOptions: otherOptions\n },\n options.auth\n )\n );\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n const classConstructor = this.constructor;\n for (let i = 0; i < classConstructor.plugins.length; ++i) {\n Object.assign(this, classConstructor.plugins[i](this, options));\n }\n }\n // assigned during constructor\n request;\n graphql;\n log;\n hook;\n // TODO: type `octokit.auth` based on passed options.authStrategy\n auth;\n}\nexport {\n Octokit\n};\n", "export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${\n process.arch\n })`;\n }\n\n return \"\";\n}\n", "// @ts-check\n\nimport { register } from \"./lib/register.js\";\nimport { addHook } from \"./lib/add.js\";\nimport { removeHook } from \"./lib/remove.js\";\n\n// bind with array of arguments: https://stackoverflow.com/a/21792913\nconst bind = Function.bind;\nconst bindable = bind.bind(bind);\n\nfunction bindApi(hook, state, name) {\n const removeHookRef = bindable(removeHook, null).apply(\n null,\n name ? [state, name] : [state]\n );\n hook.api = { remove: removeHookRef };\n hook.remove = removeHookRef;\n [\"before\", \"error\", \"after\", \"wrap\"].forEach((kind) => {\n const args = name ? [state, kind, name] : [state, kind];\n hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args);\n });\n}\n\nfunction Singular() {\n const singularHookName = Symbol(\"Singular\");\n const singularHookState = {\n registry: {},\n };\n const singularHook = register.bind(null, singularHookState, singularHookName);\n bindApi(singularHook, singularHookState, singularHookName);\n return singularHook;\n}\n\nfunction Collection() {\n const state = {\n registry: {},\n };\n\n const hook = register.bind(null, state);\n bindApi(hook, state);\n\n return hook;\n}\n\nexport default { Singular, Collection };\n", "// @ts-check\n\nexport function register(state, name, method, options) {\n if (typeof method !== \"function\") {\n throw new Error(\"method for before hook must be a function\");\n }\n\n if (!options) {\n options = {};\n }\n\n if (Array.isArray(name)) {\n return name.reverse().reduce((callback, name) => {\n return register.bind(null, state, name, callback, options);\n }, method)();\n }\n\n return Promise.resolve().then(() => {\n if (!state.registry[name]) {\n return method(options);\n }\n\n return state.registry[name].reduce((method, registered) => {\n return registered.hook.bind(null, method, options);\n }, method)();\n });\n}\n", "// @ts-check\n\nexport function addHook(state, kind, name, hook) {\n const orig = hook;\n if (!state.registry[name]) {\n state.registry[name] = [];\n }\n\n if (kind === \"before\") {\n hook = (method, options) => {\n return Promise.resolve()\n .then(orig.bind(null, options))\n .then(method.bind(null, options));\n };\n }\n\n if (kind === \"after\") {\n hook = (method, options) => {\n let result;\n return Promise.resolve()\n .then(method.bind(null, options))\n .then((result_) => {\n result = result_;\n return orig(result, options);\n })\n .then(() => {\n return result;\n });\n };\n }\n\n if (kind === \"error\") {\n hook = (method, options) => {\n return Promise.resolve()\n .then(method.bind(null, options))\n .catch((error) => {\n return orig(error, options);\n });\n };\n }\n\n state.registry[name].push({\n hook: hook,\n orig: orig,\n });\n}\n", "// @ts-check\n\nexport function removeHook(state, name, method) {\n if (!state.registry[name]) {\n return;\n }\n\n const index = state.registry[name]\n .map((registered) => {\n return registered.orig;\n })\n .indexOf(method);\n\n if (index === -1) {\n return;\n }\n\n state.registry[name].splice(index, 1);\n}\n", "// pkg/dist-src/index.js\nimport { endpoint } from \"@octokit/endpoint\";\n\n// pkg/dist-src/defaults.js\nimport { getUserAgent } from \"universal-user-agent\";\n\n// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/defaults.js\nvar defaults_default = {\n headers: {\n \"user-agent\": `octokit-request.js/${VERSION} ${getUserAgent()}`\n }\n};\n\n// pkg/dist-src/is-plain-object.js\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null) return false;\n if (Object.prototype.toString.call(value) !== \"[object Object]\") return false;\n const proto = Object.getPrototypeOf(value);\n if (proto === null) return true;\n const Ctor = Object.prototype.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof Ctor === \"function\" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);\n}\n\n// pkg/dist-src/fetch-wrapper.js\nimport { RequestError } from \"@octokit/request-error\";\nasync function fetchWrapper(requestOptions) {\n const fetch = requestOptions.request?.fetch || globalThis.fetch;\n if (!fetch) {\n throw new Error(\n \"fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing\"\n );\n }\n const log = requestOptions.request?.log || console;\n const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false;\n const body = isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body) ? JSON.stringify(requestOptions.body) : requestOptions.body;\n const requestHeaders = Object.fromEntries(\n Object.entries(requestOptions.headers).map(([name, value]) => [\n name,\n String(value)\n ])\n );\n let fetchResponse;\n try {\n fetchResponse = await fetch(requestOptions.url, {\n method: requestOptions.method,\n body,\n redirect: requestOptions.request?.redirect,\n headers: requestHeaders,\n signal: requestOptions.request?.signal,\n // duplex must be set if request.body is ReadableStream or Async Iterables.\n // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.\n ...requestOptions.body && { duplex: \"half\" }\n });\n } catch (error) {\n let message = \"Unknown Error\";\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n error.status = 500;\n throw error;\n }\n message = error.message;\n if (error.name === \"TypeError\" && \"cause\" in error) {\n if (error.cause instanceof Error) {\n message = error.cause.message;\n } else if (typeof error.cause === \"string\") {\n message = error.cause;\n }\n }\n }\n const requestError = new RequestError(message, 500, {\n request: requestOptions\n });\n requestError.cause = error;\n throw requestError;\n }\n const status = fetchResponse.status;\n const url = fetchResponse.url;\n const responseHeaders = {};\n for (const [key, value] of fetchResponse.headers) {\n responseHeaders[key] = value;\n }\n const octokitResponse = {\n url,\n status,\n headers: responseHeaders,\n data: \"\"\n };\n if (\"deprecation\" in responseHeaders) {\n const matches = responseHeaders.link && responseHeaders.link.match(/<([^>]+)>; rel=\"deprecation\"/);\n const deprecationLink = matches && matches.pop();\n log.warn(\n `[@octokit/request] \"${requestOptions.method} ${requestOptions.url}\" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : \"\"}`\n );\n }\n if (status === 204 || status === 205) {\n return octokitResponse;\n }\n if (requestOptions.method === \"HEAD\") {\n if (status < 400) {\n return octokitResponse;\n }\n throw new RequestError(fetchResponse.statusText, status, {\n response: octokitResponse,\n request: requestOptions\n });\n }\n if (status === 304) {\n octokitResponse.data = await getResponseData(fetchResponse);\n throw new RequestError(\"Not modified\", status, {\n response: octokitResponse,\n request: requestOptions\n });\n }\n if (status >= 400) {\n octokitResponse.data = await getResponseData(fetchResponse);\n throw new RequestError(toErrorMessage(octokitResponse.data), status, {\n response: octokitResponse,\n request: requestOptions\n });\n }\n octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body;\n return octokitResponse;\n}\nasync function getResponseData(response) {\n const contentType = response.headers.get(\"content-type\");\n if (/application\\/json/.test(contentType)) {\n return response.json().catch(() => response.text()).catch(() => \"\");\n }\n if (!contentType || /^text\\/|charset=utf-8$/.test(contentType)) {\n return response.text();\n }\n return response.arrayBuffer();\n}\nfunction toErrorMessage(data) {\n if (typeof data === \"string\") {\n return data;\n }\n if (data instanceof ArrayBuffer) {\n return \"Unknown error\";\n }\n if (\"message\" in data) {\n const suffix = \"documentation_url\" in data ? ` - ${data.documentation_url}` : \"\";\n return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(\", \")}${suffix}` : `${data.message}${suffix}`;\n }\n return `Unknown error: ${JSON.stringify(data)}`;\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldEndpoint, newDefaults) {\n const endpoint2 = oldEndpoint.defaults(newDefaults);\n const newApi = function(route, parameters) {\n const endpointOptions = endpoint2.merge(route, parameters);\n if (!endpointOptions.request || !endpointOptions.request.hook) {\n return fetchWrapper(endpoint2.parse(endpointOptions));\n }\n const request2 = (route2, parameters2) => {\n return fetchWrapper(\n endpoint2.parse(endpoint2.merge(route2, parameters2))\n );\n };\n Object.assign(request2, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n return endpointOptions.request.hook(request2, endpointOptions);\n };\n return Object.assign(newApi, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n}\n\n// pkg/dist-src/index.js\nvar request = withDefaults(endpoint, defaults_default);\nexport {\n request\n};\n", "// pkg/dist-src/defaults.js\nimport { getUserAgent } from \"universal-user-agent\";\n\n// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/defaults.js\nvar userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;\nvar DEFAULTS = {\n method: \"GET\",\n baseUrl: \"https://api.github.com\",\n headers: {\n accept: \"application/vnd.github.v3+json\",\n \"user-agent\": userAgent\n },\n mediaType: {\n format: \"\"\n }\n};\n\n// pkg/dist-src/util/lowercase-keys.js\nfunction lowercaseKeys(object) {\n if (!object) {\n return {};\n }\n return Object.keys(object).reduce((newObj, key) => {\n newObj[key.toLowerCase()] = object[key];\n return newObj;\n }, {});\n}\n\n// pkg/dist-src/util/is-plain-object.js\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null)\n return false;\n if (Object.prototype.toString.call(value) !== \"[object Object]\")\n return false;\n const proto = Object.getPrototypeOf(value);\n if (proto === null)\n return true;\n const Ctor = Object.prototype.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof Ctor === \"function\" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);\n}\n\n// pkg/dist-src/util/merge-deep.js\nfunction mergeDeep(defaults, options) {\n const result = Object.assign({}, defaults);\n Object.keys(options).forEach((key) => {\n if (isPlainObject(options[key])) {\n if (!(key in defaults))\n Object.assign(result, { [key]: options[key] });\n else\n result[key] = mergeDeep(defaults[key], options[key]);\n } else {\n Object.assign(result, { [key]: options[key] });\n }\n });\n return result;\n}\n\n// pkg/dist-src/util/remove-undefined-properties.js\nfunction removeUndefinedProperties(obj) {\n for (const key in obj) {\n if (obj[key] === void 0) {\n delete obj[key];\n }\n }\n return obj;\n}\n\n// pkg/dist-src/merge.js\nfunction merge(defaults, route, options) {\n if (typeof route === \"string\") {\n let [method, url] = route.split(\" \");\n options = Object.assign(url ? { method, url } : { url: method }, options);\n } else {\n options = Object.assign({}, route);\n }\n options.headers = lowercaseKeys(options.headers);\n removeUndefinedProperties(options);\n removeUndefinedProperties(options.headers);\n const mergedOptions = mergeDeep(defaults || {}, options);\n if (options.url === \"/graphql\") {\n if (defaults && defaults.mediaType.previews?.length) {\n mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(\n (preview) => !mergedOptions.mediaType.previews.includes(preview)\n ).concat(mergedOptions.mediaType.previews);\n }\n mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, \"\"));\n }\n return mergedOptions;\n}\n\n// pkg/dist-src/util/add-query-parameters.js\nfunction addQueryParameters(url, parameters) {\n const separator = /\\?/.test(url) ? \"&\" : \"?\";\n const names = Object.keys(parameters);\n if (names.length === 0) {\n return url;\n }\n return url + separator + names.map((name) => {\n if (name === \"q\") {\n return \"q=\" + parameters.q.split(\"+\").map(encodeURIComponent).join(\"+\");\n }\n return `${name}=${encodeURIComponent(parameters[name])}`;\n }).join(\"&\");\n}\n\n// pkg/dist-src/util/extract-url-variable-names.js\nvar urlVariableRegex = /\\{[^}]+\\}/g;\nfunction removeNonChars(variableName) {\n return variableName.replace(/^\\W+|\\W+$/g, \"\").split(/,/);\n}\nfunction extractUrlVariableNames(url) {\n const matches = url.match(urlVariableRegex);\n if (!matches) {\n return [];\n }\n return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);\n}\n\n// pkg/dist-src/util/omit.js\nfunction omit(object, keysToOmit) {\n const result = { __proto__: null };\n for (const key of Object.keys(object)) {\n if (keysToOmit.indexOf(key) === -1) {\n result[key] = object[key];\n }\n }\n return result;\n}\n\n// pkg/dist-src/util/url-template.js\nfunction encodeReserved(str) {\n return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {\n if (!/%[0-9A-Fa-f]/.test(part)) {\n part = encodeURI(part).replace(/%5B/g, \"[\").replace(/%5D/g, \"]\");\n }\n return part;\n }).join(\"\");\n}\nfunction encodeUnreserved(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return \"%\" + c.charCodeAt(0).toString(16).toUpperCase();\n });\n}\nfunction encodeValue(operator, value, key) {\n value = operator === \"+\" || operator === \"#\" ? encodeReserved(value) : encodeUnreserved(value);\n if (key) {\n return encodeUnreserved(key) + \"=\" + value;\n } else {\n return value;\n }\n}\nfunction isDefined(value) {\n return value !== void 0 && value !== null;\n}\nfunction isKeyOperator(operator) {\n return operator === \";\" || operator === \"&\" || operator === \"?\";\n}\nfunction getValues(context, operator, key, modifier) {\n var value = context[key], result = [];\n if (isDefined(value) && value !== \"\") {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n value = value.toString();\n if (modifier && modifier !== \"*\") {\n value = value.substring(0, parseInt(modifier, 10));\n }\n result.push(\n encodeValue(operator, value, isKeyOperator(operator) ? key : \"\")\n );\n } else {\n if (modifier === \"*\") {\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n result.push(\n encodeValue(operator, value2, isKeyOperator(operator) ? key : \"\")\n );\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n result.push(encodeValue(operator, value[k], k));\n }\n });\n }\n } else {\n const tmp = [];\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n tmp.push(encodeValue(operator, value2));\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n tmp.push(encodeUnreserved(k));\n tmp.push(encodeValue(operator, value[k].toString()));\n }\n });\n }\n if (isKeyOperator(operator)) {\n result.push(encodeUnreserved(key) + \"=\" + tmp.join(\",\"));\n } else if (tmp.length !== 0) {\n result.push(tmp.join(\",\"));\n }\n }\n }\n } else {\n if (operator === \";\") {\n if (isDefined(value)) {\n result.push(encodeUnreserved(key));\n }\n } else if (value === \"\" && (operator === \"&\" || operator === \"?\")) {\n result.push(encodeUnreserved(key) + \"=\");\n } else if (value === \"\") {\n result.push(\"\");\n }\n }\n return result;\n}\nfunction parseUrl(template) {\n return {\n expand: expand.bind(null, template)\n };\n}\nfunction expand(template, context) {\n var operators = [\"+\", \"#\", \".\", \"/\", \";\", \"?\", \"&\"];\n template = template.replace(\n /\\{([^\\{\\}]+)\\}|([^\\{\\}]+)/g,\n function(_, expression, literal) {\n if (expression) {\n let operator = \"\";\n const values = [];\n if (operators.indexOf(expression.charAt(0)) !== -1) {\n operator = expression.charAt(0);\n expression = expression.substr(1);\n }\n expression.split(/,/g).forEach(function(variable) {\n var tmp = /([^:\\*]*)(?::(\\d+)|(\\*))?/.exec(variable);\n values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));\n });\n if (operator && operator !== \"+\") {\n var separator = \",\";\n if (operator === \"?\") {\n separator = \"&\";\n } else if (operator !== \"#\") {\n separator = operator;\n }\n return (values.length !== 0 ? operator : \"\") + values.join(separator);\n } else {\n return values.join(\",\");\n }\n } else {\n return encodeReserved(literal);\n }\n }\n );\n if (template === \"/\") {\n return template;\n } else {\n return template.replace(/\\/$/, \"\");\n }\n}\n\n// pkg/dist-src/parse.js\nfunction parse(options) {\n let method = options.method.toUpperCase();\n let url = (options.url || \"/\").replace(/:([a-z]\\w+)/g, \"{$1}\");\n let headers = Object.assign({}, options.headers);\n let body;\n let parameters = omit(options, [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"mediaType\"\n ]);\n const urlVariableNames = extractUrlVariableNames(url);\n url = parseUrl(url).expand(parameters);\n if (!/^http/.test(url)) {\n url = options.baseUrl + url;\n }\n const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat(\"baseUrl\");\n const remainingParameters = omit(parameters, omittedParameters);\n const isBinaryRequest = /application\\/octet-stream/i.test(headers.accept);\n if (!isBinaryRequest) {\n if (options.mediaType.format) {\n headers.accept = headers.accept.split(/,/).map(\n (format) => format.replace(\n /application\\/vnd(\\.\\w+)(\\.v3)?(\\.\\w+)?(\\+json)?$/,\n `application/vnd$1$2.${options.mediaType.format}`\n )\n ).join(\",\");\n }\n if (url.endsWith(\"/graphql\")) {\n if (options.mediaType.previews?.length) {\n const previewsFromAcceptHeader = headers.accept.match(/[\\w-]+(?=-preview)/g) || [];\n headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {\n const format = options.mediaType.format ? `.${options.mediaType.format}` : \"+json\";\n return `application/vnd.github.${preview}-preview${format}`;\n }).join(\",\");\n }\n }\n }\n if ([\"GET\", \"HEAD\"].includes(method)) {\n url = addQueryParameters(url, remainingParameters);\n } else {\n if (\"data\" in remainingParameters) {\n body = remainingParameters.data;\n } else {\n if (Object.keys(remainingParameters).length) {\n body = remainingParameters;\n }\n }\n }\n if (!headers[\"content-type\"] && typeof body !== \"undefined\") {\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n }\n if ([\"PATCH\", \"PUT\"].includes(method) && typeof body === \"undefined\") {\n body = \"\";\n }\n return Object.assign(\n { method, url, headers },\n typeof body !== \"undefined\" ? { body } : null,\n options.request ? { request: options.request } : null\n );\n}\n\n// pkg/dist-src/endpoint-with-defaults.js\nfunction endpointWithDefaults(defaults, route, options) {\n return parse(merge(defaults, route, options));\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldDefaults, newDefaults) {\n const DEFAULTS2 = merge(oldDefaults, newDefaults);\n const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);\n return Object.assign(endpoint2, {\n DEFAULTS: DEFAULTS2,\n defaults: withDefaults.bind(null, DEFAULTS2),\n merge: merge.bind(null, DEFAULTS2),\n parse\n });\n}\n\n// pkg/dist-src/index.js\nvar endpoint = withDefaults(null, DEFAULTS);\nexport {\n endpoint\n};\n", "class RequestError extends Error {\n name;\n /**\n * http status code\n */\n status;\n /**\n * Request options that lead to the error.\n */\n request;\n /**\n * Response object if a response was received\n */\n response;\n constructor(message, statusCode, options) {\n super(message);\n this.name = \"HttpError\";\n this.status = Number.parseInt(statusCode);\n if (Number.isNaN(this.status)) {\n this.status = 0;\n }\n if (\"response\" in options) {\n this.response = options.response;\n }\n const requestCopy = Object.assign({}, options.request);\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(\n / .*$/,\n \" [REDACTED]\"\n )\n });\n }\n requestCopy.url = requestCopy.url.replace(/\\bclient_secret=\\w+/g, \"client_secret=[REDACTED]\").replace(/\\baccess_token=\\w+/g, \"access_token=[REDACTED]\");\n this.request = requestCopy;\n }\n}\nexport {\n RequestError\n};\n", "// pkg/dist-src/index.js\nimport { request } from \"@octokit/request\";\nimport { getUserAgent } from \"universal-user-agent\";\n\n// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/with-defaults.js\nimport { request as Request2 } from \"@octokit/request\";\n\n// pkg/dist-src/graphql.js\nimport { request as Request } from \"@octokit/request\";\n\n// pkg/dist-src/error.js\nfunction _buildMessageForResponseErrors(data) {\n return `Request failed due to following response errors:\n` + data.errors.map((e) => ` - ${e.message}`).join(\"\\n\");\n}\nvar GraphqlResponseError = class extends Error {\n constructor(request2, headers, response) {\n super(_buildMessageForResponseErrors(response));\n this.request = request2;\n this.headers = headers;\n this.response = response;\n this.errors = response.errors;\n this.data = response.data;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n name = \"GraphqlResponseError\";\n errors;\n data;\n};\n\n// pkg/dist-src/graphql.js\nvar NON_VARIABLE_OPTIONS = [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"query\",\n \"mediaType\"\n];\nvar FORBIDDEN_VARIABLE_OPTIONS = [\"query\", \"method\", \"url\"];\nvar GHES_V3_SUFFIX_REGEX = /\\/api\\/v3\\/?$/;\nfunction graphql(request2, query, options) {\n if (options) {\n if (typeof query === \"string\" && \"query\" in options) {\n return Promise.reject(\n new Error(`[@octokit/graphql] \"query\" cannot be used as variable name`)\n );\n }\n for (const key in options) {\n if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))\n continue;\n return Promise.reject(\n new Error(\n `[@octokit/graphql] \"${key}\" cannot be used as variable name`\n )\n );\n }\n }\n const parsedOptions = typeof query === \"string\" ? Object.assign({ query }, options) : query;\n const requestOptions = Object.keys(\n parsedOptions\n ).reduce((result, key) => {\n if (NON_VARIABLE_OPTIONS.includes(key)) {\n result[key] = parsedOptions[key];\n return result;\n }\n if (!result.variables) {\n result.variables = {};\n }\n result.variables[key] = parsedOptions[key];\n return result;\n }, {});\n const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;\n if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {\n requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, \"/api/graphql\");\n }\n return request2(requestOptions).then((response) => {\n if (response.data.errors) {\n const headers = {};\n for (const key of Object.keys(response.headers)) {\n headers[key] = response.headers[key];\n }\n throw new GraphqlResponseError(\n requestOptions,\n headers,\n response.data\n );\n }\n return response.data.data;\n });\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(request2, newDefaults) {\n const newRequest = request2.defaults(newDefaults);\n const newApi = (query, options) => {\n return graphql(newRequest, query, options);\n };\n return Object.assign(newApi, {\n defaults: withDefaults.bind(null, newRequest),\n endpoint: newRequest.endpoint\n });\n}\n\n// pkg/dist-src/index.js\nvar graphql2 = withDefaults(request, {\n headers: {\n \"user-agent\": `octokit-graphql.js/${VERSION} ${getUserAgent()}`\n },\n method: \"POST\",\n url: \"/graphql\"\n});\nfunction withCustomRequest(customRequest) {\n return withDefaults(customRequest, {\n method: \"POST\",\n url: \"/graphql\"\n });\n}\nexport {\n GraphqlResponseError,\n graphql2 as graphql,\n withCustomRequest\n};\n", "// pkg/dist-src/auth.js\nvar REGEX_IS_INSTALLATION_LEGACY = /^v1\\./;\nvar REGEX_IS_INSTALLATION = /^ghs_/;\nvar REGEX_IS_USER_TO_SERVER = /^ghu_/;\nasync function auth(token) {\n const isApp = token.split(/\\./).length === 3;\n const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);\n const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);\n const tokenType = isApp ? \"app\" : isInstallation ? \"installation\" : isUserToServer ? \"user-to-server\" : \"oauth\";\n return {\n type: \"token\",\n token,\n tokenType\n };\n}\n\n// pkg/dist-src/with-authorization-prefix.js\nfunction withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n\n// pkg/dist-src/hook.js\nasync function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(\n route,\n parameters\n );\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n\n// pkg/dist-src/index.js\nvar createTokenAuth = function createTokenAuth2(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\n \"[@octokit/auth-token] Token passed to createTokenAuth is not a string\"\n );\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\nexport {\n createTokenAuth\n};\n", "const VERSION = \"6.1.2\";\nexport {\n VERSION\n};\n", "import { Webhooks } from \"@octokit/webhooks\";\nimport { createMiddleware } from \"hono/factory\";\n\nimport type { HonoEnv, WebhookEventName } from \"../types\";\n\nlet webhooks: Webhooks | undefined;\n\nfunction getWebhooksInstance(secret: string) {\n if (!webhooks) {\n webhooks = new Webhooks({ secret });\n }\n\n return webhooks;\n}\n\n/**\n * Middleware to verify and handle Github Webhook requests. It exposes the\n * `webhooks` object on the context.\n */\nexport const githubWebhooksMiddleware = createMiddleware(\n async (c, next) => {\n const secret = c.env.GITHUB_WEBHOOK_SECRET;\n const webhooks = getWebhooksInstance(secret);\n\n c.set(\"webhooks\", webhooks);\n\n await next();\n\n const id = c.req.header(\"x-github-delivery\");\n const signature = c.req.header(\"x-hub-signature-256\");\n const name = c.req.header(\"x-github-event\") as WebhookEventName;\n\n if (!(id && name && signature)) {\n return c.text(\"Invalid webhook request\", 403);\n }\n\n const payload = await c.req.text();\n\n try {\n await webhooks.verifyAndReceive({\n id,\n name,\n signature,\n payload,\n });\n return c.text(\"Webhook received & verified\", 201);\n } catch (error) {\n return c.text(`Failed to verify Github Webhook request: ${error}`, 400);\n }\n },\n);\n", "// pkg/dist-src/createLogger.js\nvar createLogger = (logger) => ({\n debug: () => {\n },\n info: () => {\n },\n warn: console.warn.bind(console),\n error: console.error.bind(console),\n ...logger\n});\n\n// pkg/dist-src/generated/webhook-names.js\nvar emitterEventNames = [\n \"branch_protection_configuration\",\n \"branch_protection_configuration.disabled\",\n \"branch_protection_configuration.enabled\",\n \"branch_protection_rule\",\n \"branch_protection_rule.created\",\n \"branch_protection_rule.deleted\",\n \"branch_protection_rule.edited\",\n \"check_run\",\n \"check_run.completed\",\n \"check_run.created\",\n \"check_run.requested_action\",\n \"check_run.rerequested\",\n \"check_suite\",\n \"check_suite.completed\",\n \"check_suite.requested\",\n \"check_suite.rerequested\",\n \"code_scanning_alert\",\n \"code_scanning_alert.appeared_in_branch\",\n \"code_scanning_alert.closed_by_user\",\n \"code_scanning_alert.created\",\n \"code_scanning_alert.fixed\",\n \"code_scanning_alert.reopened\",\n \"code_scanning_alert.reopened_by_user\",\n \"commit_comment\",\n \"commit_comment.created\",\n \"create\",\n \"custom_property\",\n \"custom_property.created\",\n \"custom_property.deleted\",\n \"custom_property.updated\",\n \"custom_property_values\",\n \"custom_property_values.updated\",\n \"delete\",\n \"dependabot_alert\",\n \"dependabot_alert.auto_dismissed\",\n \"dependabot_alert.auto_reopened\",\n \"dependabot_alert.created\",\n \"dependabot_alert.dismissed\",\n \"dependabot_alert.fixed\",\n \"dependabot_alert.reintroduced\",\n \"dependabot_alert.reopened\",\n \"deploy_key\",\n \"deploy_key.created\",\n \"deploy_key.deleted\",\n \"deployment\",\n \"deployment.created\",\n \"deployment_protection_rule\",\n \"deployment_protection_rule.requested\",\n \"deployment_review\",\n \"deployment_review.approved\",\n \"deployment_review.rejected\",\n \"deployment_review.requested\",\n \"deployment_status\",\n \"deployment_status.created\",\n \"discussion\",\n \"discussion.answered\",\n \"discussion.category_changed\",\n \"discussion.closed\",\n \"discussion.created\",\n \"discussion.deleted\",\n \"discussion.edited\",\n \"discussion.labeled\",\n \"discussion.locked\",\n \"discussion.pinned\",\n \"discussion.reopened\",\n \"discussion.transferred\",\n \"discussion.unanswered\",\n \"discussion.unlabeled\",\n \"discussion.unlocked\",\n \"discussion.unpinned\",\n \"discussion_comment\",\n \"discussion_comment.created\",\n \"discussion_comment.deleted\",\n \"discussion_comment.edited\",\n \"fork\",\n \"github_app_authorization\",\n \"github_app_authorization.revoked\",\n \"gollum\",\n \"installation\",\n \"installation.created\",\n \"installation.deleted\",\n \"installation.new_permissions_accepted\",\n \"installation.suspend\",\n \"installation.unsuspend\",\n \"installation_repositories\",\n \"installation_repositories.added\",\n \"installation_repositories.removed\",\n \"installation_target\",\n \"installation_target.renamed\",\n \"issue_comment\",\n \"issue_comment.created\",\n \"issue_comment.deleted\",\n \"issue_comment.edited\",\n \"issues\",\n \"issues.assigned\",\n \"issues.closed\",\n \"issues.deleted\",\n \"issues.demilestoned\",\n \"issues.edited\",\n \"issues.labeled\",\n \"issues.locked\",\n \"issues.milestoned\",\n \"issues.opened\",\n \"issues.pinned\",\n \"issues.reopened\",\n \"issues.transferred\",\n \"issues.unassigned\",\n \"issues.unlabeled\",\n \"issues.unlocked\",\n \"issues.unpinned\",\n \"label\",\n \"label.created\",\n \"label.deleted\",\n \"label.edited\",\n \"marketplace_purchase\",\n \"marketplace_purchase.cancelled\",\n \"marketplace_purchase.changed\",\n \"marketplace_purchase.pending_change\",\n \"marketplace_purchase.pending_change_cancelled\",\n \"marketplace_purchase.purchased\",\n \"member\",\n \"member.added\",\n \"member.edited\",\n \"member.removed\",\n \"membership\",\n \"membership.added\",\n \"membership.removed\",\n \"merge_group\",\n \"merge_group.checks_requested\",\n \"merge_group.destroyed\",\n \"meta\",\n \"meta.deleted\",\n \"milestone\",\n \"milestone.closed\",\n \"milestone.created\",\n \"milestone.deleted\",\n \"milestone.edited\",\n \"milestone.opened\",\n \"org_block\",\n \"org_block.blocked\",\n \"org_block.unblocked\",\n \"organization\",\n \"organization.deleted\",\n \"organization.member_added\",\n \"organization.member_invited\",\n \"organization.member_removed\",\n \"organization.renamed\",\n \"package\",\n \"package.published\",\n \"package.updated\",\n \"page_build\",\n \"personal_access_token_request\",\n \"personal_access_token_request.approved\",\n \"personal_access_token_request.cancelled\",\n \"personal_access_token_request.created\",\n \"personal_access_token_request.denied\",\n \"ping\",\n \"project\",\n \"project.closed\",\n \"project.created\",\n \"project.deleted\",\n \"project.edited\",\n \"project.reopened\",\n \"project_card\",\n \"project_card.converted\",\n \"project_card.created\",\n \"project_card.deleted\",\n \"project_card.edited\",\n \"project_card.moved\",\n \"project_column\",\n \"project_column.created\",\n \"project_column.deleted\",\n \"project_column.edited\",\n \"project_column.moved\",\n \"projects_v2\",\n \"projects_v2.closed\",\n \"projects_v2.created\",\n \"projects_v2.deleted\",\n \"projects_v2.edited\",\n \"projects_v2.reopened\",\n \"projects_v2_item\",\n \"projects_v2_item.archived\",\n \"projects_v2_item.converted\",\n \"projects_v2_item.created\",\n \"projects_v2_item.deleted\",\n \"projects_v2_item.edited\",\n \"projects_v2_item.reordered\",\n \"projects_v2_item.restored\",\n \"public\",\n \"pull_request\",\n \"pull_request.assigned\",\n \"pull_request.auto_merge_disabled\",\n \"pull_request.auto_merge_enabled\",\n \"pull_request.closed\",\n \"pull_request.converted_to_draft\",\n \"pull_request.demilestoned\",\n \"pull_request.dequeued\",\n \"pull_request.edited\",\n \"pull_request.enqueued\",\n \"pull_request.labeled\",\n \"pull_request.locked\",\n \"pull_request.milestoned\",\n \"pull_request.opened\",\n \"pull_request.ready_for_review\",\n \"pull_request.reopened\",\n \"pull_request.review_request_removed\",\n \"pull_request.review_requested\",\n \"pull_request.synchronize\",\n \"pull_request.unassigned\",\n \"pull_request.unlabeled\",\n \"pull_request.unlocked\",\n \"pull_request_review\",\n \"pull_request_review.dismissed\",\n \"pull_request_review.edited\",\n \"pull_request_review.submitted\",\n \"pull_request_review_comment\",\n \"pull_request_review_comment.created\",\n \"pull_request_review_comment.deleted\",\n \"pull_request_review_comment.edited\",\n \"pull_request_review_thread\",\n \"pull_request_review_thread.resolved\",\n \"pull_request_review_thread.unresolved\",\n \"push\",\n \"registry_package\",\n \"registry_package.published\",\n \"registry_package.updated\",\n \"release\",\n \"release.created\",\n \"release.deleted\",\n \"release.edited\",\n \"release.prereleased\",\n \"release.published\",\n \"release.released\",\n \"release.unpublished\",\n \"repository\",\n \"repository.archived\",\n \"repository.created\",\n \"repository.deleted\",\n \"repository.edited\",\n \"repository.privatized\",\n \"repository.publicized\",\n \"repository.renamed\",\n \"repository.transferred\",\n \"repository.unarchived\",\n \"repository_advisory\",\n \"repository_advisory.published\",\n \"repository_advisory.reported\",\n \"repository_dispatch\",\n \"repository_dispatch.sample.collected\",\n \"repository_import\",\n \"repository_ruleset\",\n \"repository_ruleset.created\",\n \"repository_ruleset.deleted\",\n \"repository_ruleset.edited\",\n \"repository_vulnerability_alert\",\n \"repository_vulnerability_alert.create\",\n \"repository_vulnerability_alert.dismiss\",\n \"repository_vulnerability_alert.reopen\",\n \"repository_vulnerability_alert.resolve\",\n \"secret_scanning_alert\",\n \"secret_scanning_alert.created\",\n \"secret_scanning_alert.reopened\",\n \"secret_scanning_alert.resolved\",\n \"secret_scanning_alert.revoked\",\n \"secret_scanning_alert.validated\",\n \"secret_scanning_alert_location\",\n \"secret_scanning_alert_location.created\",\n \"security_advisory\",\n \"security_advisory.published\",\n \"security_advisory.updated\",\n \"security_advisory.withdrawn\",\n \"security_and_analysis\",\n \"sponsorship\",\n \"sponsorship.cancelled\",\n \"sponsorship.created\",\n \"sponsorship.edited\",\n \"sponsorship.pending_cancellation\",\n \"sponsorship.pending_tier_change\",\n \"sponsorship.tier_changed\",\n \"star\",\n \"star.created\",\n \"star.deleted\",\n \"status\",\n \"team\",\n \"team.added_to_repository\",\n \"team.created\",\n \"team.deleted\",\n \"team.edited\",\n \"team.removed_from_repository\",\n \"team_add\",\n \"watch\",\n \"watch.started\",\n \"workflow_dispatch\",\n \"workflow_job\",\n \"workflow_job.completed\",\n \"workflow_job.in_progress\",\n \"workflow_job.queued\",\n \"workflow_job.waiting\",\n \"workflow_run\",\n \"workflow_run.completed\",\n \"workflow_run.in_progress\",\n \"workflow_run.requested\"\n];\n\n// pkg/dist-src/event-handler/on.js\nfunction handleEventHandlers(state, webhookName, handler) {\n if (!state.hooks[webhookName]) {\n state.hooks[webhookName] = [];\n }\n state.hooks[webhookName].push(handler);\n}\nfunction receiverOn(state, webhookNameOrNames, handler) {\n if (Array.isArray(webhookNameOrNames)) {\n webhookNameOrNames.forEach(\n (webhookName) => receiverOn(state, webhookName, handler)\n );\n return;\n }\n if ([\"*\", \"error\"].includes(webhookNameOrNames)) {\n const webhookName = webhookNameOrNames === \"*\" ? \"any\" : webhookNameOrNames;\n const message = `Using the \"${webhookNameOrNames}\" event with the regular Webhooks.on() function is not supported. Please use the Webhooks.on${webhookName.charAt(0).toUpperCase() + webhookName.slice(1)}() method instead`;\n throw new Error(message);\n }\n if (!emitterEventNames.includes(webhookNameOrNames)) {\n state.log.warn(\n `\"${webhookNameOrNames}\" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)`\n );\n }\n handleEventHandlers(state, webhookNameOrNames, handler);\n}\nfunction receiverOnAny(state, handler) {\n handleEventHandlers(state, \"*\", handler);\n}\nfunction receiverOnError(state, handler) {\n handleEventHandlers(state, \"error\", handler);\n}\n\n// pkg/dist-src/event-handler/wrap-error-handler.js\nfunction wrapErrorHandler(handler, error) {\n let returnValue;\n try {\n returnValue = handler(error);\n } catch (error2) {\n console.log('FATAL: Error occurred in \"error\" event handler');\n console.log(error2);\n }\n if (returnValue && returnValue.catch) {\n returnValue.catch((error2) => {\n console.log('FATAL: Error occurred in \"error\" event handler');\n console.log(error2);\n });\n }\n}\n\n// pkg/dist-src/event-handler/receive.js\nfunction getHooks(state, eventPayloadAction, eventName) {\n const hooks = [state.hooks[eventName], state.hooks[\"*\"]];\n if (eventPayloadAction) {\n hooks.unshift(state.hooks[`${eventName}.${eventPayloadAction}`]);\n }\n return [].concat(...hooks.filter(Boolean));\n}\nfunction receiverHandle(state, event) {\n const errorHandlers = state.hooks.error || [];\n if (event instanceof Error) {\n const error = Object.assign(new AggregateError([event], event.message), {\n event\n });\n errorHandlers.forEach((handler) => wrapErrorHandler(handler, error));\n return Promise.reject(error);\n }\n if (!event || !event.name) {\n const error = new Error(\"Event name not passed\");\n throw new AggregateError([error], error.message);\n }\n if (!event.payload) {\n const error = new Error(\"Event name not passed\");\n throw new AggregateError([error], error.message);\n }\n const hooks = getHooks(\n state,\n \"action\" in event.payload ? event.payload.action : null,\n event.name\n );\n if (hooks.length === 0) {\n return Promise.resolve();\n }\n const errors = [];\n const promises = hooks.map((handler) => {\n let promise = Promise.resolve(event);\n if (state.transform) {\n promise = promise.then(state.transform);\n }\n return promise.then((event2) => {\n return handler(event2);\n }).catch((error) => errors.push(Object.assign(error, { event })));\n });\n return Promise.all(promises).then(() => {\n if (errors.length === 0) {\n return;\n }\n const error = new AggregateError(\n errors,\n errors.map((error2) => error2.message).join(\"\\n\")\n );\n Object.assign(error, {\n event\n });\n errorHandlers.forEach((handler) => wrapErrorHandler(handler, error));\n throw error;\n });\n}\n\n// pkg/dist-src/event-handler/remove-listener.js\nfunction removeListener(state, webhookNameOrNames, handler) {\n if (Array.isArray(webhookNameOrNames)) {\n webhookNameOrNames.forEach(\n (webhookName) => removeListener(state, webhookName, handler)\n );\n return;\n }\n if (!state.hooks[webhookNameOrNames]) {\n return;\n }\n for (let i = state.hooks[webhookNameOrNames].length - 1; i >= 0; i--) {\n if (state.hooks[webhookNameOrNames][i] === handler) {\n state.hooks[webhookNameOrNames].splice(i, 1);\n return;\n }\n }\n}\n\n// pkg/dist-src/event-handler/index.js\nfunction createEventHandler(options) {\n const state = {\n hooks: {},\n log: createLogger(options && options.log)\n };\n if (options && options.transform) {\n state.transform = options.transform;\n }\n return {\n on: receiverOn.bind(null, state),\n onAny: receiverOnAny.bind(null, state),\n onError: receiverOnError.bind(null, state),\n removeListener: removeListener.bind(null, state),\n receive: receiverHandle.bind(null, state)\n };\n}\n\n// pkg/dist-src/index.js\nimport { sign, verify as verify2 } from \"@octokit/webhooks-methods\";\n\n// pkg/dist-src/verify-and-receive.js\nimport { verify } from \"@octokit/webhooks-methods\";\nasync function verifyAndReceive(state, event) {\n const matchesSignature = await verify(\n state.secret,\n event.payload,\n event.signature\n ).catch(() => false);\n if (!matchesSignature) {\n const error = new Error(\n \"[@octokit/webhooks] signature does not match event payload and secret\"\n );\n return state.eventHandler.receive(\n Object.assign(error, { event, status: 400 })\n );\n }\n let payload;\n try {\n payload = JSON.parse(event.payload);\n } catch (error) {\n error.message = \"Invalid JSON\";\n error.status = 400;\n throw new AggregateError([error], error.message);\n }\n return state.eventHandler.receive({\n id: event.id,\n name: event.name,\n payload\n });\n}\n\n// pkg/dist-src/middleware/node/get-missing-headers.js\nvar WEBHOOK_HEADERS = [\n \"x-github-event\",\n \"x-hub-signature-256\",\n \"x-github-delivery\"\n];\nfunction getMissingHeaders(request) {\n return WEBHOOK_HEADERS.filter((header) => !(header in request.headers));\n}\n\n// pkg/dist-src/middleware/node/get-payload.js\nfunction getPayload(request) {\n if (typeof request.body === \"object\" && \"rawBody\" in request && request.rawBody instanceof Buffer) {\n return Promise.resolve(request.rawBody.toString(\"utf8\"));\n } else if (typeof request.body === \"string\") {\n return Promise.resolve(request.body);\n }\n return new Promise((resolve, reject) => {\n let data = [];\n request.on(\n \"error\",\n (error) => reject(new AggregateError([error], error.message))\n );\n request.on(\"data\", (chunk) => data.push(chunk));\n request.on(\n \"end\",\n () => (\n // setImmediate improves the throughput by reducing the pressure from\n // the event loop\n setImmediate(\n resolve,\n data.length === 1 ? data[0].toString(\"utf8\") : Buffer.concat(data).toString(\"utf8\")\n )\n )\n );\n });\n}\n\n// pkg/dist-src/middleware/node/on-unhandled-request-default.js\nfunction onUnhandledRequestDefault(request, response) {\n response.writeHead(404, {\n \"content-type\": \"application/json\"\n });\n response.end(\n JSON.stringify({\n error: `Unknown route: ${request.method} ${request.url}`\n })\n );\n}\n\n// pkg/dist-src/middleware/node/middleware.js\nasync function middleware(webhooks, options, request, response, next) {\n let pathname;\n try {\n pathname = new URL(request.url, \"http://localhost\").pathname;\n } catch (error) {\n response.writeHead(422, {\n \"content-type\": \"application/json\"\n });\n response.end(\n JSON.stringify({\n error: `Request URL could not be parsed: ${request.url}`\n })\n );\n return true;\n }\n if (pathname !== options.path) {\n next?.();\n return false;\n } else if (request.method !== \"POST\") {\n onUnhandledRequestDefault(request, response);\n return true;\n }\n if (!request.headers[\"content-type\"] || !request.headers[\"content-type\"].startsWith(\"application/json\")) {\n response.writeHead(415, {\n \"content-type\": \"application/json\",\n accept: \"application/json\"\n });\n response.end(\n JSON.stringify({\n error: `Unsupported \"Content-Type\" header value. Must be \"application/json\"`\n })\n );\n return true;\n }\n const missingHeaders = getMissingHeaders(request).join(\", \");\n if (missingHeaders) {\n response.writeHead(400, {\n \"content-type\": \"application/json\"\n });\n response.end(\n JSON.stringify({\n error: `Required headers missing: ${missingHeaders}`\n })\n );\n return true;\n }\n const eventName = request.headers[\"x-github-event\"];\n const signatureSHA256 = request.headers[\"x-hub-signature-256\"];\n const id = request.headers[\"x-github-delivery\"];\n options.log.debug(`${eventName} event received (id: ${id})`);\n let didTimeout = false;\n const timeout = setTimeout(() => {\n didTimeout = true;\n response.statusCode = 202;\n response.end(\"still processing\\n\");\n }, 9e3).unref();\n try {\n const payload = await getPayload(request);\n await webhooks.verifyAndReceive({\n id,\n name: eventName,\n payload,\n signature: signatureSHA256\n });\n clearTimeout(timeout);\n if (didTimeout) return true;\n response.end(\"ok\\n\");\n return true;\n } catch (error) {\n clearTimeout(timeout);\n if (didTimeout) return true;\n const err = Array.from(error.errors)[0];\n const errorMessage = err.message ? `${err.name}: ${err.message}` : \"Error: An Unspecified error occurred\";\n response.statusCode = typeof err.status !== \"undefined\" ? err.status : 500;\n options.log.error(error);\n response.end(\n JSON.stringify({\n error: errorMessage\n })\n );\n return true;\n }\n}\n\n// pkg/dist-src/middleware/node/index.js\nfunction createNodeMiddleware(webhooks, {\n path = \"/api/github/webhooks\",\n log = createLogger()\n} = {}) {\n return middleware.bind(null, webhooks, {\n path,\n log\n });\n}\n\n// pkg/dist-src/index.js\nvar Webhooks = class {\n sign;\n verify;\n on;\n onAny;\n onError;\n removeListener;\n receive;\n verifyAndReceive;\n constructor(options) {\n if (!options || !options.secret) {\n throw new Error(\"[@octokit/webhooks] options.secret required\");\n }\n const state = {\n eventHandler: createEventHandler(options),\n secret: options.secret,\n hooks: {},\n log: createLogger(options.log)\n };\n this.sign = sign.bind(null, options.secret);\n this.verify = verify2.bind(null, options.secret);\n this.on = state.eventHandler.on;\n this.onAny = state.eventHandler.onAny;\n this.onError = state.eventHandler.onError;\n this.removeListener = state.eventHandler.removeListener;\n this.receive = state.eventHandler.receive;\n this.verifyAndReceive = verifyAndReceive.bind(null, state);\n }\n};\nexport {\n Webhooks,\n createEventHandler,\n createNodeMiddleware,\n emitterEventNames\n};\n", "// pkg/dist-src/web.js\nvar enc = new TextEncoder();\nfunction hexToUInt8Array(string) {\n const pairs = string.match(/[\\dA-F]{2}/gi);\n const integers = pairs.map(function(s) {\n return parseInt(s, 16);\n });\n return new Uint8Array(integers);\n}\nfunction UInt8ArrayToHex(signature) {\n return Array.prototype.map.call(new Uint8Array(signature), (x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\nasync function importKey(secret) {\n return crypto.subtle.importKey(\n \"raw\",\n // raw format of the key - should be Uint8Array\n enc.encode(secret),\n {\n // algorithm details\n name: \"HMAC\",\n hash: { name: \"SHA-256\" }\n },\n false,\n // export = false\n [\"sign\", \"verify\"]\n // what this key can do\n );\n}\nasync function sign(secret, payload) {\n if (!secret || !payload) {\n throw new TypeError(\n \"[@octokit/webhooks-methods] secret & payload required for sign()\"\n );\n }\n if (typeof payload !== \"string\") {\n throw new TypeError(\"[@octokit/webhooks-methods] payload must be a string\");\n }\n const algorithm = \"sha256\";\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n await importKey(secret),\n enc.encode(payload)\n );\n return `${algorithm}=${UInt8ArrayToHex(signature)}`;\n}\nasync function verify(secret, eventPayload, signature) {\n if (!secret || !eventPayload || !signature) {\n throw new TypeError(\n \"[@octokit/webhooks-methods] secret, eventPayload & signature required\"\n );\n }\n if (typeof eventPayload !== \"string\") {\n throw new TypeError(\n \"[@octokit/webhooks-methods] eventPayload must be a string\"\n );\n }\n const algorithm = \"sha256\";\n return await crypto.subtle.verify(\n \"HMAC\",\n await importKey(secret),\n hexToUInt8Array(signature.replace(`${algorithm}=`, \"\")),\n enc.encode(eventPayload)\n );\n}\nexport {\n sign,\n verify\n};\n", "import { reactRenderer } from \"@hono/react-renderer\";\nimport { ColorSchemeScript } from \"@mantine/core\";\nimport type { Manifest } from \"vite\";\n\nexport const reactRendererMiddleware = reactRenderer(\n ({ children, clientComponent, title }) => {\n const documentTitle = `Github Tracker${title ? ` | ${title}` : \"\"}`;\n const propsData = JSON.stringify(clientComponent);\n\n // Import the manifest file to get the list of built assets by Vite. This\n // is only done in production mode & when `build.manifest` is enabled in\n // vite.config.ts\n // Idea borrowed from Honox's link component:\n // https://github.com/honojs/honox/blob/main/src/server/components/link.tsx\n const assetImportTags = (() => {\n // HACK - Not going to prod here...\n if (true || !import.meta.env.PROD) {\n return