diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..64ab260 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = tab +tab_width = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.yml] +indent_style = space diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..5c7b5d3 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,6 @@ +{ + "printWidth": 140, + "singleQuote": true, + "semi": true, + "useTabs": true +} diff --git a/node_modules/.bin/acorn b/node_modules/.bin/acorn new file mode 100644 index 0000000..46a3e61 --- /dev/null +++ b/node_modules/.bin/acorn @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../acorn/bin/acorn" "$@" +else + exec node "$basedir/../acorn/bin/acorn" "$@" +fi diff --git a/node_modules/.bin/acorn.cmd b/node_modules/.bin/acorn.cmd new file mode 100644 index 0000000..a9324df --- /dev/null +++ b/node_modules/.bin/acorn.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\acorn\bin\acorn" %* diff --git a/node_modules/.bin/acorn.ps1 b/node_modules/.bin/acorn.ps1 new file mode 100644 index 0000000..6f6dcdd --- /dev/null +++ b/node_modules/.bin/acorn.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args + } else { + & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../acorn/bin/acorn" $args + } else { + & "node$exe" "$basedir/../acorn/bin/acorn" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/esbuild b/node_modules/.bin/esbuild new file mode 100644 index 0000000..26bef54 --- /dev/null +++ b/node_modules/.bin/esbuild @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../esbuild/bin/esbuild" "$@" +else + exec node "$basedir/../esbuild/bin/esbuild" "$@" +fi diff --git a/node_modules/.bin/esbuild.cmd b/node_modules/.bin/esbuild.cmd new file mode 100644 index 0000000..cc920c5 --- /dev/null +++ b/node_modules/.bin/esbuild.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esbuild\bin\esbuild" %* diff --git a/node_modules/.bin/esbuild.ps1 b/node_modules/.bin/esbuild.ps1 new file mode 100644 index 0000000..81ffbf9 --- /dev/null +++ b/node_modules/.bin/esbuild.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args + } else { + & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../esbuild/bin/esbuild" $args + } else { + & "node$exe" "$basedir/../esbuild/bin/esbuild" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 100644 index 0000000..0a62a1b --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../mime/cli.js" "$@" +else + exec node "$basedir/../mime/cli.js" "$@" +fi diff --git a/node_modules/.bin/mime.cmd b/node_modules/.bin/mime.cmd new file mode 100644 index 0000000..54491f1 --- /dev/null +++ b/node_modules/.bin/mime.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mime\cli.js" %* diff --git a/node_modules/.bin/mime.ps1 b/node_modules/.bin/mime.ps1 new file mode 100644 index 0000000..2222f40 --- /dev/null +++ b/node_modules/.bin/mime.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../mime/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../mime/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../mime/cli.js" $args + } else { + & "node$exe" "$basedir/../mime/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/mustache b/node_modules/.bin/mustache new file mode 100644 index 0000000..7bc1d34 --- /dev/null +++ b/node_modules/.bin/mustache @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../mustache/bin/mustache" "$@" +else + exec node "$basedir/../mustache/bin/mustache" "$@" +fi diff --git a/node_modules/.bin/mustache.cmd b/node_modules/.bin/mustache.cmd new file mode 100644 index 0000000..92cf68d --- /dev/null +++ b/node_modules/.bin/mustache.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mustache\bin\mustache" %* diff --git a/node_modules/.bin/mustache.ps1 b/node_modules/.bin/mustache.ps1 new file mode 100644 index 0000000..ec52dfe --- /dev/null +++ b/node_modules/.bin/mustache.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../mustache/bin/mustache" $args + } else { + & "$basedir/node$exe" "$basedir/../mustache/bin/mustache" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../mustache/bin/mustache" $args + } else { + & "node$exe" "$basedir/../mustache/bin/mustache" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid new file mode 100644 index 0000000..23254eb --- /dev/null +++ b/node_modules/.bin/nanoid @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../nanoid/bin/nanoid.cjs" "$@" +else + exec node "$basedir/../nanoid/bin/nanoid.cjs" "$@" +fi diff --git a/node_modules/.bin/nanoid.cmd b/node_modules/.bin/nanoid.cmd new file mode 100644 index 0000000..9c40107 --- /dev/null +++ b/node_modules/.bin/nanoid.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nanoid\bin\nanoid.cjs" %* diff --git a/node_modules/.bin/nanoid.ps1 b/node_modules/.bin/nanoid.ps1 new file mode 100644 index 0000000..d8a4d7a --- /dev/null +++ b/node_modules/.bin/nanoid.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } else { + & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } else { + & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/workerd b/node_modules/.bin/workerd new file mode 100644 index 0000000..6c7a5e5 --- /dev/null +++ b/node_modules/.bin/workerd @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../workerd/bin/workerd" "$@" +else + exec node "$basedir/../workerd/bin/workerd" "$@" +fi diff --git a/node_modules/.bin/workerd.cmd b/node_modules/.bin/workerd.cmd new file mode 100644 index 0000000..2370fc7 --- /dev/null +++ b/node_modules/.bin/workerd.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\workerd\bin\workerd" %* diff --git a/node_modules/.bin/workerd.ps1 b/node_modules/.bin/workerd.ps1 new file mode 100644 index 0000000..830bb71 --- /dev/null +++ b/node_modules/.bin/workerd.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../workerd/bin/workerd" $args + } else { + & "$basedir/node$exe" "$basedir/../workerd/bin/workerd" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../workerd/bin/workerd" $args + } else { + & "node$exe" "$basedir/../workerd/bin/workerd" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/wrangler b/node_modules/.bin/wrangler new file mode 100644 index 0000000..3e1e221 --- /dev/null +++ b/node_modules/.bin/wrangler @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../wrangler/bin/wrangler.js" "$@" +else + exec node "$basedir/../wrangler/bin/wrangler.js" "$@" +fi diff --git a/node_modules/.bin/wrangler.cmd b/node_modules/.bin/wrangler.cmd new file mode 100644 index 0000000..8dc54c4 --- /dev/null +++ b/node_modules/.bin/wrangler.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\wrangler\bin\wrangler.js" %* diff --git a/node_modules/.bin/wrangler.ps1 b/node_modules/.bin/wrangler.ps1 new file mode 100644 index 0000000..4dae06c --- /dev/null +++ b/node_modules/.bin/wrangler.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../wrangler/bin/wrangler.js" $args + } else { + & "$basedir/node$exe" "$basedir/../wrangler/bin/wrangler.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../wrangler/bin/wrangler.js" $args + } else { + & "node$exe" "$basedir/../wrangler/bin/wrangler.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/wrangler2 b/node_modules/.bin/wrangler2 new file mode 100644 index 0000000..3e1e221 --- /dev/null +++ b/node_modules/.bin/wrangler2 @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../wrangler/bin/wrangler.js" "$@" +else + exec node "$basedir/../wrangler/bin/wrangler.js" "$@" +fi diff --git a/node_modules/.bin/wrangler2.cmd b/node_modules/.bin/wrangler2.cmd new file mode 100644 index 0000000..8dc54c4 --- /dev/null +++ b/node_modules/.bin/wrangler2.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\wrangler\bin\wrangler.js" %* diff --git a/node_modules/.bin/wrangler2.ps1 b/node_modules/.bin/wrangler2.ps1 new file mode 100644 index 0000000..4dae06c --- /dev/null +++ b/node_modules/.bin/wrangler2.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../wrangler/bin/wrangler.js" $args + } else { + & "$basedir/node$exe" "$basedir/../wrangler/bin/wrangler.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../wrangler/bin/wrangler.js" $args + } else { + & "node$exe" "$basedir/../wrangler/bin/wrangler.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..707d6fb --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,733 @@ +{ + "name": "RSS-Worker", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@cloudflare/kv-asset-handler": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.2.0.tgz", + "integrity": "sha512-MVbXLbTcAotOPUj0pAMhVtJ+3/kFkwJqc5qNOleOZTv6QkZZABDMS21dSrSlVswEHwrpWC03e4fWytjqKvuE2A==", + "dev": true, + "dependencies": { + "mime": "^3.0.0" + } + }, + "node_modules/@cloudflare/workerd-windows-64": { + "version": "1.20230922.0", + "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20230922.0.tgz", + "integrity": "sha512-Tzoq64YMcHjXRheGyWKHNAfklHS9Us2M1lNZ/6y6ziNB0tF06RNRuD5yRhH1LulSOMxVH/KQAqZ0pNEpt3XyPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16" + } + }, + "node_modules/@esbuild-plugins/node-globals-polyfill": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@esbuild-plugins/node-globals-polyfill/-/node-globals-polyfill-0.2.3.tgz", + "integrity": "sha512-r3MIryXDeXDOZh7ih1l/yE9ZLORCd5e8vWg02azWRGj5SPTuoh69A2AIyn0Z31V/kHBfZ4HgWJ+OK3GTTwLmnw==", + "dev": true, + "peerDependencies": { + "esbuild": "*" + } + }, + "node_modules/@esbuild-plugins/node-modules-polyfill": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/@esbuild-plugins/node-modules-polyfill/-/node-modules-polyfill-0.2.2.tgz", + "integrity": "sha512-LXV7QsWJxRuMYvKbiznh+U1ilIop3g2TeKRzUxOG5X3YITc8JyyTa90BmLwqqv0YnX4v32CSlG+vsziZp9dMvA==", + "dev": true, + "dependencies": { + "escape-string-regexp": "^4.0.0", + "rollup-plugin-node-polyfills": "^0.2.1" + }, + "peerDependencies": { + "esbuild": "*" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", + "integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/acorn": { + "version": "8.10.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", + "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/as-table": { + "version": "1.0.55", + "resolved": "https://registry.npmjs.org/as-table/-/as-table-1.0.55.tgz", + "integrity": "sha512-xvsWESUJn0JN421Xb9MQw6AsMHRCUknCe0Wjlxvjud80mU4E6hQf1A6NzQKcYNmYw62MfzEtXc+badstZP3JpQ==", + "dev": true, + "dependencies": { + "printable-characters": "^1.0.42" + } + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/blake3-wasm": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", + "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==", + "dev": true + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dev": true, + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/capnp-ts": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/capnp-ts/-/capnp-ts-0.7.0.tgz", + "integrity": "sha512-XKxXAC3HVPv7r674zP0VC3RTXz+/JKhfyw94ljvF80yynK6VkTnqE3jMuN8b3dUVmmc43TjyxjW4KTsmB3c86g==", + "dev": true, + "dependencies": { + "debug": "^4.3.1", + "tslib": "^2.2.0" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-2.0.2.tgz", + "integrity": "sha512-ND9qDTLc6diwj+Xe5cdAgVTbLVdXbtxTJRXRhli8Mowuaan+0EJOtdqJ0QCHNSSPyoXGx9HX2/VMnKeC34AChA==", + "dev": true + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/esbuild": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.19.tgz", + "integrity": "sha512-XQ0jAPFkK/u3LcVRcvVHQcTIqD6E2H1fvZMA5dQPSOWb3suUbWbfbRf94pjc0bNzRYLfIrDRQXr7X+LHIm5oHw==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/android-arm": "0.17.19", + "@esbuild/android-arm64": "0.17.19", + "@esbuild/android-x64": "0.17.19", + "@esbuild/darwin-arm64": "0.17.19", + "@esbuild/darwin-x64": "0.17.19", + "@esbuild/freebsd-arm64": "0.17.19", + "@esbuild/freebsd-x64": "0.17.19", + "@esbuild/linux-arm": "0.17.19", + "@esbuild/linux-arm64": "0.17.19", + "@esbuild/linux-ia32": "0.17.19", + "@esbuild/linux-loong64": "0.17.19", + "@esbuild/linux-mips64el": "0.17.19", + "@esbuild/linux-ppc64": "0.17.19", + "@esbuild/linux-riscv64": "0.17.19", + "@esbuild/linux-s390x": "0.17.19", + "@esbuild/linux-x64": "0.17.19", + "@esbuild/netbsd-x64": "0.17.19", + "@esbuild/openbsd-x64": "0.17.19", + "@esbuild/sunos-x64": "0.17.19", + "@esbuild/win32-arm64": "0.17.19", + "@esbuild/win32-ia32": "0.17.19", + "@esbuild/win32-x64": "0.17.19" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/estree-walker": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", + "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", + "dev": true + }, + "node_modules/exit-hook": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-2.2.1.tgz", + "integrity": "sha512-eNTPlAD67BmP31LDINZ3U7HSF8l57TxOY2PmBJ1shpCvpnxBF93mWCE8YHBnXs8qiUZJc9WDcWIeC3a2HIAMfw==", + "dev": true, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/get-source": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/get-source/-/get-source-2.0.12.tgz", + "integrity": "sha512-X5+4+iD+HoSeEED+uwrQ07BOQr0kEDFMVqqpBuI+RaZBpBpHCuXxo70bjar6f0b0u/DQJsJ7ssurpP0V60Az+w==", + "dev": true, + "dependencies": { + "data-uri-to-buffer": "^2.0.0", + "source-map": "^0.6.1" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/magic-string": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz", + "integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.8" + } + }, + "node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "dev": true, + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/miniflare": { + "version": "3.20230922.0", + "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-3.20230922.0.tgz", + "integrity": "sha512-1h8c7b0Ouoml7TmU2mtJo4k/DKMX4ift1vOxyfcktPY/0lqeiRNYulcOCPcF94maI4uATdBIO6Fx/zN2c2Ew0A==", + "dev": true, + "dependencies": { + "acorn": "^8.8.0", + "acorn-walk": "^8.2.0", + "capnp-ts": "^0.7.0", + "exit-hook": "^2.2.1", + "glob-to-regexp": "^0.4.1", + "source-map-support": "0.5.21", + "stoppable": "^1.1.0", + "undici": "^5.22.1", + "workerd": "1.20230922.0", + "ws": "^8.11.0", + "youch": "^3.2.2", + "zod": "^3.20.6" + }, + "engines": { + "node": ">=16.13" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "dev": true, + "bin": { + "mustache": "bin/mustache" + } + }, + "node_modules/nanoid": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz", + "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-forge": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.1.tgz", + "integrity": "sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==", + "dev": true, + "engines": { + "node": ">= 6.13.0" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-to-regexp": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.2.1.tgz", + "integrity": "sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==", + "dev": true + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/printable-characters": { + "version": "1.0.42", + "resolved": "https://registry.npmjs.org/printable-characters/-/printable-characters-1.0.42.tgz", + "integrity": "sha512-dKp+C4iXWK4vVYZmYSd0KBH5F/h1HoZRsbJ82AVKRO3PEo8L4lBS/vLwhVtpwwuYcoIsVY+1JYKR268yn480uQ==", + "dev": true + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/rollup-plugin-inject": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rollup-plugin-inject/-/rollup-plugin-inject-3.0.2.tgz", + "integrity": "sha512-ptg9PQwzs3orn4jkgXJ74bfs5vYz1NCZlSQMBUA0wKcGp5i5pA1AO3fOUEte8enhGUC+iapTCzEWw2jEFFUO/w==", + "deprecated": "This package has been deprecated and is no longer maintained. Please use @rollup/plugin-inject.", + "dev": true, + "dependencies": { + "estree-walker": "^0.6.1", + "magic-string": "^0.25.3", + "rollup-pluginutils": "^2.8.1" + } + }, + "node_modules/rollup-plugin-node-polyfills": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/rollup-plugin-node-polyfills/-/rollup-plugin-node-polyfills-0.2.1.tgz", + "integrity": "sha512-4kCrKPTJ6sK4/gLL/U5QzVT8cxJcofO0OU74tnB19F40cmuAKSzH5/siithxlofFEjwvw1YAhPmbvGNA6jEroA==", + "dev": true, + "dependencies": { + "rollup-plugin-inject": "^3.0.0" + } + }, + "node_modules/rollup-pluginutils": { + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", + "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", + "dev": true, + "dependencies": { + "estree-walker": "^0.6.1" + } + }, + "node_modules/selfsigned": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-2.1.1.tgz", + "integrity": "sha512-GSL3aowiF7wa/WtSFwnUrludWFoNhftq8bUkH9pkzjpN2XSPOAYEgg6e0sS9s0rZwgJzJiQRPU18A6clnoW5wQ==", + "dev": true, + "dependencies": { + "node-forge": "^1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/sourcemap-codec": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", + "integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==", + "deprecated": "Please use @jridgewell/sourcemap-codec instead", + "dev": true + }, + "node_modules/stacktracey": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/stacktracey/-/stacktracey-2.1.8.tgz", + "integrity": "sha512-Kpij9riA+UNg7TnphqjH7/CzctQ/owJGNbFkfEeve4Z4uxT5+JapVLFXcsurIfN34gnTWZNJ/f7NMG0E8JDzTw==", + "dev": true, + "dependencies": { + "as-table": "^1.0.36", + "get-source": "^2.0.12" + } + }, + "node_modules/stoppable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz", + "integrity": "sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw==", + "dev": true, + "engines": { + "node": ">=4", + "npm": ">=6" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "dev": true, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==", + "dev": true + }, + "node_modules/undici": { + "version": "5.25.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.25.2.tgz", + "integrity": "sha512-tch8RbCfn1UUH1PeVCXva4V8gDpGAud/w0WubD6sHC46vYQ3KDxL+xv1A2UxK0N6jrVedutuPHxe1XIoqerwMw==", + "dev": true, + "dependencies": { + "busboy": "^1.6.0" + }, + "engines": { + "node": ">=14.0" + } + }, + "node_modules/workerd": { + "version": "1.20230922.0", + "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20230922.0.tgz", + "integrity": "sha512-iFe0tqoHsxgZXCaURVNKYtc0QnWdjORZJ0WzaasdSK4STOwV1aD7yC2v5o3HwnNTaJOpNt7H09AYWKB3y1ju8A==", + "dev": true, + "hasInstallScript": true, + "bin": { + "workerd": "bin/workerd" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "@cloudflare/workerd-darwin-64": "1.20230922.0", + "@cloudflare/workerd-darwin-arm64": "1.20230922.0", + "@cloudflare/workerd-linux-64": "1.20230922.0", + "@cloudflare/workerd-linux-arm64": "1.20230922.0", + "@cloudflare/workerd-windows-64": "1.20230922.0" + } + }, + "node_modules/wrangler": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-3.10.1.tgz", + "integrity": "sha512-k7BUIinKVYFHJYo8HVeVjDncjTQIu6Z6/CNnTB9WcsGlJ0MFTsFWdWspWSPgef1vOTrzkfbweZpZCY3YXIew3g==", + "dev": true, + "dependencies": { + "@cloudflare/kv-asset-handler": "^0.2.0", + "@esbuild-plugins/node-globals-polyfill": "^0.2.3", + "@esbuild-plugins/node-modules-polyfill": "^0.2.2", + "blake3-wasm": "^2.1.5", + "chokidar": "^3.5.3", + "esbuild": "0.17.19", + "miniflare": "3.20230922.0", + "nanoid": "^3.3.3", + "path-to-regexp": "^6.2.0", + "selfsigned": "^2.0.1", + "source-map": "0.6.1", + "source-map-support": "0.5.21", + "xxhash-wasm": "^1.0.1" + }, + "bin": { + "wrangler": "bin/wrangler.js", + "wrangler2": "bin/wrangler.js" + }, + "engines": { + "node": ">=16.13.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/ws": { + "version": "8.14.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz", + "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==", + "dev": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xxhash-wasm": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.0.2.tgz", + "integrity": "sha512-ibF0Or+FivM9lNrg+HGJfVX8WJqgo+kCLDc4vx6xMeTce7Aj+DLttKbxxRR/gNLSAelRc1omAPlJ77N/Jem07A==", + "dev": true + }, + "node_modules/youch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/youch/-/youch-3.3.2.tgz", + "integrity": "sha512-9cwz/z7abtcHOIuH45nzmUFCZbyJA1nLqlirKvyNRx4wDMhqsBaifAJzBej7L4fsVPjFxYq3NK3GAcfvZsydFw==", + "dev": true, + "dependencies": { + "cookie": "^0.5.0", + "mustache": "^4.2.0", + "stacktracey": "^2.1.8" + } + }, + "node_modules/zod": { + "version": "3.22.2", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.22.2.tgz", + "integrity": "sha512-wvWkphh5WQsJbVk1tbx1l1Ly4yg+XecD+Mq280uBGt9wa5BKSWf4Mhp6GmrkPixhMxmabYY7RbzlwVP32pbGCg==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/node_modules/@cloudflare/kv-asset-handler/LICENSE_APACHE b/node_modules/@cloudflare/kv-asset-handler/LICENSE_APACHE new file mode 100644 index 0000000..a7e77cb --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/LICENSE_APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/node_modules/@cloudflare/kv-asset-handler/LICENSE_MIT b/node_modules/@cloudflare/kv-asset-handler/LICENSE_MIT new file mode 100644 index 0000000..abf2bc7 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/LICENSE_MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Ashley Williams + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@cloudflare/kv-asset-handler/README.md b/node_modules/@cloudflare/kv-asset-handler/README.md new file mode 100644 index 0000000..d5baa0a --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/README.md @@ -0,0 +1,329 @@ +# @cloudflare/kv-asset-handler + +[![npm](https://img.shields.io/npm/v/@cloudflare/kv-asset-handler.svg)](https://www.npmjs.com/package/@cloudflare/kv-asset-handler)   +[![Run npm tests](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml)   +[![Lint Markdown](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml)   + +`kv-asset-handler` is an open-source library for managing the retrieval of static assets from [Workers KV](https://developers.cloudflare.com/workers/runtime-apis/kv) inside of a [Cloudflare Workers](https://workers.dev) function. `kv-asset-handler` is designed for use with [Workers Sites](https://developers.cloudflare.com/workers/platform/sites), a feature included in [Wrangler](https://github.com/cloudflare/wrangler), our command-line tool for deploying Workers projects. + +`kv-asset-handler` runs as part of a Cloudflare Workers function, so it allows you to customize _how_ and _when_ your static assets are loaded, as well as customize how those assets behave before they're sent to the client. + +Most users and sites will not need these customizations, and just want to serve their statically built applications. For that simple use-case, you can check out [Cloudflare Pages](https://pages.cloudflare.com), our batteries-included approach to deploying static sites on Cloudflare's edge network. Workers Sites was designed as a precursor to Cloudflare Pages, so check out Pages if you just want to deploy your static site without any special customizations! + +For users who _do_ want to customize their assets, and want to build complex experiences on top of their static assets, `kv-asset-handler` (and the default [Workers Sites template](https://github.com/cloudflare/worker-sites-template), which is provided for use with Wrangler + Workers Sites) allows you to customize caching behavior, headers, and anything else about how your Workers function loads the static assets for your site stored in Workers KV. + +The Cloudflare Workers Discord server is an active place where Workers users get help, share feedback, and collaborate on making our platform better. The `#workers-sites` channel in particular is a great place to chat about `kv-asset-handler`, and building cool experiences for your users using these tools! If you have questions, want to share what you're working on, or give feedback, [join us in Discord and say hello](https://discord.gg/cloudflaredev)! + +- [Installation](#installation) +- [Usage](#usage) +- [`getAssetFromKV`](#-getassetfromkv) + - [Example](#example) + * [Return](#return) + * [Optional Arguments](#optional-arguments) + - [`mapRequestToAsset`](#-maprequesttoasset) + - [Example](#example-1) + - [`cacheControl`](#-cachecontrol) + - [`browserTTL`](#browserttl) + - [`edgeTTL`](#edgettl) + - [`bypassCache`](#bypasscache) + - [`ASSET_NAMESPACE` (required for ES Modules)](#asset_namespace-required-for-es-modules) + - [`ASSET_MANIFEST` (required for ES Modules)](#asset_manifest-required-for-es-modules) + +* [Helper functions](#helper-functions) + - [`mapRequestToAsset`](#maprequesttoasset-1) + - [`serveSinglePageApp`](#servesinglepageapp) +* [Cache revalidation and etags](#cache-revalidation-and-etags) + +## Installation + +Add this package to your `package.json` by running this in the root of your +project's directory: + +``` +npm i @cloudflare/kv-asset-handler +``` + +## Usage + +This package was designed to work with [Worker Sites](https://workers.cloudflare.com/sites). + +## `getAssetFromKV` + +getAssetFromKV(Evt) => Promise + +`getAssetFromKV` is an async function that takes an `Evt` object (containing a `Request` and a [`waitUntil`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#waituntil)) and returns a `Response` object if the request matches an asset in KV, otherwise it will throw a `KVError`. + +#### Example + +This example checks for the existence of a value in KV, and returns it if it's there, and returns a 404 if it is not. It also serves index.html from `/`. + +### Return + +`getAssetFromKV` returns a `Promise` with `Response` being the body of the asset requested. + +Known errors to be thrown are: + +- MethodNotAllowedError +- NotFoundError +- InternalError + +#### ES Modules + +```js +import { getAssetFromKV, NotFoundError, MethodNotAllowedError } from '@cloudflare/kv-asset-handler' +import manifestJSON from '__STATIC_CONTENT_MANIFEST' +const assetManifest = JSON.parse(manifestJSON) + +export default { + async fetch(request, env, ctx) { + if (request.url.includes('/docs')) { + try { + return await getAssetFromKV( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise) + }, + }, + { + ASSET_NAMESPACE: env.__STATIC_CONTENT, + ASSET_MANIFEST: assetManifest, + }, + ) + } catch (e) { + if (e instanceof NotFoundError) { + // ... + } else if (e instanceof MethodNotAllowedError) { + // ... + } else { + return new Response('An unexpected error occurred', { status: 500 }) + } + } + } else return fetch(request) + }, +} +``` + +#### Service Worker + +```js +import { getAssetFromKV, NotFoundError, MethodNotAllowedError } from '@cloudflare/kv-asset-handler' + +addEventListener('fetch', (event) => { + event.respondWith(handleEvent(event)) +}) + +async function handleEvent(event) { + if (event.request.url.includes('/docs')) { + try { + return await getAssetFromKV(event) + } catch (e) { + if (e instanceof NotFoundError) { + // ... + } else if (e instanceof MethodNotAllowedError) { + // ... + } else { + return new Response('An unexpected error occurred', { status: 500 }) + } + } + } else return fetch(event.request) +} +``` + +### Optional Arguments + +You can customize the behavior of `getAssetFromKV` by passing the following properties as an object into the second argument. + +``` +getAssetFromKV(event, { mapRequestToAsset: ... }) +``` + +#### `mapRequestToAsset` + +mapRequestToAsset(Request) => Request + +Maps the incoming request to the value that will be looked up in Cloudflare's KV + +By default, mapRequestToAsset is set to the exported function [`mapRequestToAsset`](#maprequesttoasset-1). This works for most static site generators, but you can customize this behavior by passing your own function as `mapRequestToAsset`. The function should take a `Request` object as its only argument, and return a new `Request` object with an updated path to be looked up in the asset manifest/KV. + +For SPA mapping pass in the [`serveSinglePageApp`](#servesinglepageapp) function + +#### Example + +Strip `/docs` from any incoming request before looking up an asset in Cloudflare's KV. + +```js +import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler' +... +const customKeyModifier = request => { + let url = request.url + //custom key mapping optional + url = url.replace('/docs', '').replace(/^\/+/, '') + return mapRequestToAsset(new Request(url, request)) +} +let asset = await getAssetFromKV(event, { mapRequestToAsset: customKeyModifier }) +``` + +#### `cacheControl` + +type: object + +`cacheControl` allows you to configure options for both the Cloudflare Cache accessed by your Worker, and the browser cache headers sent along with your Workers' responses. The default values are as follows: + +```javascript +let cacheControl = { + browserTTL: null, // do not set cache control ttl on responses + edgeTTL: 2 * 60 * 60 * 24, // 2 days + bypassCache: false, // do not bypass Cloudflare's cache +} +``` + +##### `browserTTL` + +type: number | null +nullable: true + +Sets the `Cache-Control: max-age` header on the response returned from the Worker. By default set to `null` which will not add the header at all. + +##### `edgeTTL` + +type: number | null +nullable: true + +Sets the `Cache-Control: max-age` header on the response used as the edge cache key. By default set to 2 days (`2 * 60 * 60 * 24`). When null will not cache on the edge at all. + +##### `bypassCache` + +type: boolean + +Determines whether to cache requests on Cloudflare's edge cache. By default set to `false` (recommended for production builds). Useful for development when you need to eliminate the cache's effect on testing. + +#### `ASSET_NAMESPACE` (required for ES Modules) + +type: KV Namespace Binding + +The binding name to the KV Namespace populated with key/value entries of files for the Worker to serve. By default, Workers Sites uses a [binding to a Workers KV Namespace](https://developers.cloudflare.com/workers/reference/storage/api/#namespaces) named `__STATIC_CONTENT`. + +It is further assumed that this namespace consists of static assets such as HTML, CSS, JavaScript, or image files, keyed off of a relative path that roughly matches the assumed URL pathname of the incoming request. + +In ES Modules format, this argument is required, and can be gotten from `env`. + +##### ES Module + +```js +return getAssetFromKV( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise) + }, + }, + { + ASSET_NAMESPACE: env.__STATIC_CONTENT, + }, +) +``` + +##### Service Worker + +``` +return getAssetFromKV(event, { ASSET_NAMESPACE: MY_NAMESPACE }) +``` + +#### `ASSET_MANIFEST` (required for ES Modules) + +type: text blob (JSON formatted) or object + +The mapping of requested file path to the key stored on Cloudflare. + +Workers Sites with Wrangler bundles up a text blob that maps request paths to content-hashed keys that are generated by Wrangler as a cache-busting measure. If this option/binding is not present, the function will fallback to using the raw pathname to look up your asset in KV. If, for whatever reason, you have rolled your own implementation of this, you can include your own by passing a stringified JSON object where the keys are expected paths, and the values are the expected keys in your KV namespace. + +In ES Modules format, this argument is required, and can be imported. + +##### ES Module + +```js +import manifestJSON from '__STATIC_CONTENT_MANIFEST' +let manifest = JSON.parse(manifestJSON) +manifest['index.html'] = 'index.special.html' + +return getAssetFromKV( + { + request, + waitUntil(promise) { + return ctx.waitUntil(promise) + }, + }, + { + ASSET_MANIFEST: manifest, + // ... + }, +) +``` + +##### Service Worker + +``` +let assetManifest = { "index.html": "index.special.html" } +return getAssetFromKV(event, { ASSET_MANIFEST: assetManifest }) +``` + +#### `defaultMimeType` (optional) + +type: string + +This is the mime type that will be used for files with unrecognized or missing extensions. The default value is `'text/plain'`. + +If you are serving a static site and would like to use extensionless HTML files instead of index.html files, set this to `'text/html'`. + +#### `defaultDocument` (optional) + +type: string + +This is the default document that will be concatenated for requests ends in `'/'` or without a valid mime type like `'/about'` or `'/about.me'`. The default value is `'index.html'`. + +# Helper functions + +## `mapRequestToAsset` + +mapRequestToAsset(Request) => Request + +The default function for mapping incoming requests to keys in Cloudflare's KV. + +Takes any path that ends in `/` or evaluates to an HTML file and appends `index.html` or `/index.html` for lookup in your Workers KV namespace. + +## `serveSinglePageApp` + +serveSinglePageApp(Request) => Request + +A custom handler for mapping requests to a single root: `index.html`. The most common use case is single-page applications - frameworks with in-app routing - such as React Router, VueJS, etc. It takes zero arguments. + +```js +import { getAssetFromKV, serveSinglePageApp } from '@cloudflare/kv-asset-handler' +... +let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp }) +``` + +# Cache revalidation and etags + +All responses served from cache (including those with `cf-cache-status: MISS`) include an `etag` response header that identifies the version of the resource. The `etag` value is identical to the path key used in the `ASSET_MANIFEST`. It is updated each time an asset changes and looks like this: `etag: ..` (ex. `etag: index.54321.html`). + +Resources served with an `etag` allow browsers to use the `if-none-match` request header to make conditional requests for that resource in the future. This has two major benefits: + +- When a request's `if-none-match` value matches the `etag` of the resource in Cloudflare cache, Cloudflare will send a `304 Not Modified` response without a body, saving bandwidth. +- Changes to a file on the server are immediately reflected in the browser - even when the cache control directive `max-age` is unexpired. + +#### Disable the `etag` + +To turn `etags` **off**, you must bypass cache: + +```js +/* Turn etags off */ +let cacheControl = { + bypassCache: true, +} +``` + +#### Syntax and comparison context + +`kv-asset-handler` sets and evaluates etags as [strong validators](https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests#Strong_validation). To preserve `etag` integrity, the format of the value deviates from the [RFC2616 recommendation to enclose the `etag` with quotation marks](https://tools.ietf.org/html/rfc2616#section-3.11). This is intentional. Cloudflare cache applies the `W/` prefix to all `etags` that use quoted-strings -- a process that converts the `etag` to a "weak validator" when served to a client. diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts new file mode 100644 index 0000000..7820e62 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts @@ -0,0 +1,36 @@ +import { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError } from './types'; +declare global { + var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string; +} +/** + * maps the path of incoming request to the request pathKey to look up + * in bucket and in cache + * e.g. for a path '/' returns '/index.html' which serves + * the content of bucket/index.html + * @param {Request} request incoming request + */ +declare const mapRequestToAsset: (request: Request, options?: Partial) => Request; +/** + * maps the path of incoming request to /index.html if it evaluates to + * any HTML file. + * @param {Request} request incoming request + */ +declare function serveSinglePageApp(request: Request, options?: Partial): Request; +/** + * takes the path of the incoming request, gathers the appropriate content from KV, and returns + * the response + * + * @param {FetchEvent} event the fetch event of the triggered request + * @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options + * @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser + * @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up + * @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references + * @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV + * */ +declare type Evt = { + request: Request; + waitUntil: (promise: Promise) => void; +}; +declare const getAssetFromKV: (event: Evt, options?: Partial) => Promise; +export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp }; +export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError }; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/index.js b/node_modules/@cloudflare/kv-asset-handler/dist/index.js new file mode 100644 index 0000000..5f80b5e --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/index.js @@ -0,0 +1,267 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.serveSinglePageApp = exports.mapRequestToAsset = exports.getAssetFromKV = void 0; +const mime = require("mime"); +const types_1 = require("./types"); +Object.defineProperty(exports, "MethodNotAllowedError", { enumerable: true, get: function () { return types_1.MethodNotAllowedError; } }); +Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return types_1.NotFoundError; } }); +Object.defineProperty(exports, "InternalError", { enumerable: true, get: function () { return types_1.InternalError; } }); +const defaultCacheControl = { + browserTTL: null, + edgeTTL: 2 * 60 * 60 * 24, + bypassCache: false, // do not bypass Cloudflare's cache +}; +const parseStringAsObject = (maybeString) => typeof maybeString === 'string' ? JSON.parse(maybeString) : maybeString; +const getAssetFromKVDefaultOptions = { + ASSET_NAMESPACE: typeof __STATIC_CONTENT !== 'undefined' ? __STATIC_CONTENT : undefined, + ASSET_MANIFEST: typeof __STATIC_CONTENT_MANIFEST !== 'undefined' + ? parseStringAsObject(__STATIC_CONTENT_MANIFEST) + : {}, + cacheControl: defaultCacheControl, + defaultMimeType: 'text/plain', + defaultDocument: 'index.html', + pathIsEncoded: false, +}; +function assignOptions(options) { + // Assign any missing options passed in to the default + // options.mapRequestToAsset is handled manually later + return Object.assign({}, getAssetFromKVDefaultOptions, options); +} +/** + * maps the path of incoming request to the request pathKey to look up + * in bucket and in cache + * e.g. for a path '/' returns '/index.html' which serves + * the content of bucket/index.html + * @param {Request} request incoming request + */ +const mapRequestToAsset = (request, options) => { + options = assignOptions(options); + const parsedUrl = new URL(request.url); + let pathname = parsedUrl.pathname; + if (pathname.endsWith('/')) { + // If path looks like a directory append options.defaultDocument + // e.g. If path is /about/ -> /about/index.html + pathname = pathname.concat(options.defaultDocument); + } + else if (!mime.getType(pathname)) { + // If path doesn't look like valid content + // e.g. /about.me -> /about.me/index.html + pathname = pathname.concat('/' + options.defaultDocument); + } + parsedUrl.pathname = pathname; + return new Request(parsedUrl.toString(), request); +}; +exports.mapRequestToAsset = mapRequestToAsset; +/** + * maps the path of incoming request to /index.html if it evaluates to + * any HTML file. + * @param {Request} request incoming request + */ +function serveSinglePageApp(request, options) { + options = assignOptions(options); + // First apply the default handler, which already has logic to detect + // paths that should map to HTML files. + request = mapRequestToAsset(request, options); + const parsedUrl = new URL(request.url); + // Detect if the default handler decided to map to + // a HTML file in some specific directory. + if (parsedUrl.pathname.endsWith('.html')) { + // If expected HTML file was missing, just return the root index.html (or options.defaultDocument) + return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request); + } + else { + // The default handler decided this is not an HTML page. It's probably + // an image, CSS, or JS file. Leave it as-is. + return request; + } +} +exports.serveSinglePageApp = serveSinglePageApp; +const getAssetFromKV = async (event, options) => { + options = assignOptions(options); + const request = event.request; + const ASSET_NAMESPACE = options.ASSET_NAMESPACE; + const ASSET_MANIFEST = parseStringAsObject(options.ASSET_MANIFEST); + if (typeof ASSET_NAMESPACE === 'undefined') { + throw new types_1.InternalError(`there is no KV namespace bound to the script`); + } + const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, ''); // strip any preceding /'s + let pathIsEncoded = options.pathIsEncoded; + let requestKey; + // if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions + // otherwise handle request as normal, with default mapRequestToAsset below + if (options.mapRequestToAsset) { + requestKey = options.mapRequestToAsset(request); + } + else if (ASSET_MANIFEST[rawPathKey]) { + requestKey = request; + } + else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) { + pathIsEncoded = true; + requestKey = request; + } + else { + const mappedRequest = mapRequestToAsset(request); + const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, ''); + if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) { + pathIsEncoded = true; + requestKey = mappedRequest; + } + else { + // use default mapRequestToAsset + requestKey = mapRequestToAsset(request, options); + } + } + const SUPPORTED_METHODS = ['GET', 'HEAD']; + if (!SUPPORTED_METHODS.includes(requestKey.method)) { + throw new types_1.MethodNotAllowedError(`${requestKey.method} is not a valid request method`); + } + const parsedUrl = new URL(requestKey.url); + const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname; // decode percentage encoded path only when necessary + // pathKey is the file path to look up in the manifest + let pathKey = pathname.replace(/^\/+/, ''); // remove prepended / + // @ts-ignore + const cache = caches.default; + let mimeType = mime.getType(pathKey) || options.defaultMimeType; + if (mimeType.startsWith('text') || mimeType === 'application/javascript') { + mimeType += '; charset=utf-8'; + } + let shouldEdgeCache = false; // false if storing in KV by raw file path i.e. no hash + // check manifest for map from file path to hash + if (typeof ASSET_MANIFEST !== 'undefined') { + if (ASSET_MANIFEST[pathKey]) { + pathKey = ASSET_MANIFEST[pathKey]; + // if path key is in asset manifest, we can assume it contains a content hash and can be cached + shouldEdgeCache = true; + } + } + // TODO this excludes search params from cache, investigate ideal behavior + let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request); + // if argument passed in for cacheControl is a function then + // evaluate that function. otherwise return the Object passed in + // or default Object + const evalCacheOpts = (() => { + switch (typeof options.cacheControl) { + case 'function': + return options.cacheControl(request); + case 'object': + return options.cacheControl; + default: + return defaultCacheControl; + } + })(); + // formats the etag depending on the response context. if the entityId + // is invalid, returns an empty string (instead of null) to prevent the + // the potentially disastrous scenario where the value of the Etag resp + // header is "null". Could be modified in future to base64 encode etc + const formatETag = (entityId = pathKey, validatorType = 'strong') => { + if (!entityId) { + return ''; + } + switch (validatorType) { + case 'weak': + if (!entityId.startsWith('W/')) { + return `W/${entityId}`; + } + return entityId; + case 'strong': + if (entityId.startsWith(`W/"`)) { + entityId = entityId.replace('W/', ''); + } + if (!entityId.endsWith(`"`)) { + entityId = `"${entityId}"`; + } + return entityId; + default: + return ''; + } + }; + options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts); + // override shouldEdgeCache if options say to bypassCache + if (options.cacheControl.bypassCache || + options.cacheControl.edgeTTL === null || + request.method == 'HEAD') { + shouldEdgeCache = false; + } + // only set max-age if explicitly passed in a number as an arg + const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === 'number'; + let response = null; + if (shouldEdgeCache) { + response = await cache.match(cacheKey); + } + if (response) { + if (response.status > 300 && response.status < 400) { + if (response.body && 'cancel' in Object.getPrototypeOf(response.body)) { + // Body exists and environment supports readable streams + response.body.cancel(); + } + else { + // Environment doesnt support readable streams, or null repsonse body. Nothing to do + } + response = new Response(null, response); + } + else { + // fixes #165 + let opts = { + headers: new Headers(response.headers), + status: 0, + statusText: '', + }; + opts.headers.set('cf-cache-status', 'HIT'); + if (response.status) { + opts.status = response.status; + opts.statusText = response.statusText; + } + else if (opts.headers.has('Content-Range')) { + opts.status = 206; + opts.statusText = 'Partial Content'; + } + else { + opts.status = 200; + opts.statusText = 'OK'; + } + response = new Response(response.body, opts); + } + } + else { + const body = await ASSET_NAMESPACE.get(pathKey, 'arrayBuffer'); + if (body === null) { + throw new types_1.NotFoundError(`could not find ${pathKey} in your content namespace`); + } + response = new Response(body); + if (shouldEdgeCache) { + response.headers.set('Accept-Ranges', 'bytes'); + response.headers.set('Content-Length', body.length); + // set etag before cache insertion + if (!response.headers.has('etag')) { + response.headers.set('etag', formatETag(pathKey, 'strong')); + } + // determine Cloudflare cache behavior + response.headers.set('Cache-Control', `max-age=${options.cacheControl.edgeTTL}`); + event.waitUntil(cache.put(cacheKey, response.clone())); + response.headers.set('CF-Cache-Status', 'MISS'); + } + } + response.headers.set('Content-Type', mimeType); + if (response.status === 304) { + let etag = formatETag(response.headers.get('etag'), 'strong'); + let ifNoneMatch = cacheKey.headers.get('if-none-match'); + let proxyCacheStatus = response.headers.get('CF-Cache-Status'); + if (etag) { + if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === 'MISS') { + response.headers.set('CF-Cache-Status', 'EXPIRED'); + } + else { + response.headers.set('CF-Cache-Status', 'REVALIDATED'); + } + response.headers.set('etag', formatETag(etag, 'weak')); + } + } + if (shouldSetBrowserCache) { + response.headers.set('Cache-Control', `max-age=${options.cacheControl.browserTTL}`); + } + else { + response.headers.delete('Cache-Control'); + } + return response; +}; +exports.getAssetFromKV = getAssetFromKV; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts new file mode 100644 index 0000000..f829335 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts @@ -0,0 +1,14 @@ +export declare const getEvent: (request: Request) => any; +export declare const mockKV: (store: any) => { + get: (path: string) => any; +}; +export declare const mockManifest: () => string; +export declare const mockCaches: () => { + default: { + match(key: any): Promise; + put(key: any, val: Response): Promise; + }; +}; +export declare function mockRequestScope(): void; +export declare function mockGlobalScope(): void; +export declare const sleep: (milliseconds: number) => Promise; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/mocks.js b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.js new file mode 100644 index 0000000..0f7a338 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/mocks.js @@ -0,0 +1,146 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sleep = exports.mockGlobalScope = exports.mockRequestScope = exports.mockCaches = exports.mockManifest = exports.mockKV = exports.getEvent = void 0; +const makeServiceWorkerEnv = require('service-worker-mock'); +const HASH = '123HASHBROWN'; +const getEvent = (request) => { + const waitUntil = async (callback) => { + await callback; + }; + return { + request, + waitUntil, + }; +}; +exports.getEvent = getEvent; +const store = { + 'key1.123HASHBROWN.txt': 'val1', + 'key1.123HASHBROWN.png': 'val1', + 'index.123HASHBROWN.html': 'index.html', + 'cache.123HASHBROWN.html': 'cache me if you can', + '测试.123HASHBROWN.html': 'My filename is non-ascii', + '%not-really-percent-encoded.123HASHBROWN.html': 'browser percent encoded', + '%2F.123HASHBROWN.html': 'user percent encoded', + '你好.123HASHBROWN.html': 'I shouldnt be served', + '%E4%BD%A0%E5%A5%BD.123HASHBROWN.html': 'Im important', + 'nohash.txt': 'no hash but still got some result', + 'sub/blah.123HASHBROWN.png': 'picturedis', + 'sub/index.123HASHBROWN.html': 'picturedis', + 'client.123HASHBROWN': 'important file', + 'client.123HASHBROWN/index.html': 'Im here but serve my big bro above', + 'image.123HASHBROWN.png': 'imagepng', + 'image.123HASHBROWN.webp': 'imagewebp', + '你好/index.123HASHBROWN.html': 'My path is non-ascii', +}; +const mockKV = (store) => { + return { + get: (path) => store[path] || null, + }; +}; +exports.mockKV = mockKV; +const mockManifest = () => { + return JSON.stringify({ + 'key1.txt': `key1.${HASH}.txt`, + 'key1.png': `key1.${HASH}.png`, + 'cache.html': `cache.${HASH}.html`, + '测试.html': `测试.${HASH}.html`, + '你好.html': `你好.${HASH}.html`, + '%not-really-percent-encoded.html': `%not-really-percent-encoded.${HASH}.html`, + '%2F.html': `%2F.${HASH}.html`, + '%E4%BD%A0%E5%A5%BD.html': `%E4%BD%A0%E5%A5%BD.${HASH}.html`, + 'index.html': `index.${HASH}.html`, + 'sub/blah.png': `sub/blah.${HASH}.png`, + 'sub/index.html': `sub/index.${HASH}.html`, + client: `client.${HASH}`, + 'client/index.html': `client.${HASH}`, + 'image.png': `image.${HASH}.png`, + 'image.webp': `image.${HASH}.webp`, + '你好/index.html': `你好/index.${HASH}.html`, + }); +}; +exports.mockManifest = mockManifest; +let cacheStore = new Map(); +const mockCaches = () => { + return { + default: { + async match(key) { + let cacheKey = { + url: key.url, + headers: {}, + }; + let response; + if (key.headers.has('if-none-match')) { + let makeStrongEtag = key.headers.get('if-none-match').replace('W/', ''); + Reflect.set(cacheKey.headers, 'etag', makeStrongEtag); + response = cacheStore.get(JSON.stringify(cacheKey)); + } + else { + // if client doesn't send if-none-match, we need to iterate through these keys + // and just test the URL + const activeCacheKeys = Array.from(cacheStore.keys()); + for (const cacheStoreKey of activeCacheKeys) { + if (JSON.parse(cacheStoreKey).url === key.url) { + response = cacheStore.get(cacheStoreKey); + } + } + } + // TODO: write test to accomodate for rare scenarios with where range requests accomodate etags + if (response && !key.headers.has('if-none-match')) { + // this appears overly verbose, but is necessary to document edge cache behavior + // The Range request header triggers the response header Content-Range ... + const range = key.headers.get('range'); + if (range) { + response.headers.set('content-range', `bytes ${range.split('=').pop()}/${response.headers.get('content-length')}`); + } + // ... which we are using in this repository to set status 206 + if (response.headers.has('content-range')) { + response.status = 206; + } + else { + response.status = 200; + } + let etag = response.headers.get('etag'); + if (etag && !etag.includes('W/')) { + response.headers.set('etag', `W/${etag}`); + } + } + return response; + }, + async put(key, val) { + let headers = new Headers(val.headers); + let url = new URL(key.url); + let resWithBody = new Response(val.body, { headers, status: 200 }); + let resNoBody = new Response(null, { headers, status: 304 }); + let cacheKey = { + url: key.url, + headers: { + etag: `"${url.pathname.replace('/', '')}"`, + }, + }; + cacheStore.set(JSON.stringify(cacheKey), resNoBody); + cacheKey.headers = {}; + cacheStore.set(JSON.stringify(cacheKey), resWithBody); + return; + }, + }, + }; +}; +exports.mockCaches = mockCaches; +// mocks functionality used inside worker request +function mockRequestScope() { + Object.assign(global, makeServiceWorkerEnv()); + Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() }); + Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) }); + Object.assign(global, { caches: (0, exports.mockCaches)() }); +} +exports.mockRequestScope = mockRequestScope; +// mocks functionality used on global isolate scope. such as the KV namespace bind +function mockGlobalScope() { + Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() }); + Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) }); +} +exports.mockGlobalScope = mockGlobalScope; +const sleep = (milliseconds) => { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +}; +exports.sleep = sleep; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.js b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.js new file mode 100644 index 0000000..83838ad --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ava_1 = require("ava"); +const mocks_1 = require("../mocks"); +(0, mocks_1.mockGlobalScope)(); +// manually reset manifest global, to test optional behaviour +Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined }); +const index_1 = require("../index"); +(0, ava_1.default)('getAssetFromKV return correct val from KV without manifest', async (t) => { + (0, mocks_1.mockRequestScope)(); + // manually reset manifest global, to test optional behaviour + Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined }); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.123HASHBROWN.txt')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'val1'); + t.true(res.headers.get('content-type').includes('text')); + } + else { + t.fail('Response was undefined'); + } +}); diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js new file mode 100644 index 0000000..724c1d1 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js @@ -0,0 +1,446 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ava_1 = require("ava"); +const mocks_1 = require("../mocks"); +(0, mocks_1.mockGlobalScope)(); +const index_1 = require("../index"); +(0, ava_1.default)('getAssetFromKV return correct val from KV and default caching', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.txt')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(res.headers.get('cache-control'), null); + t.is(res.headers.get('cf-cache-status'), 'MISS'); + t.is(await res.text(), 'val1'); + t.true(res.headers.get('content-type').includes('text')); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV evaluated the file matching the extensionless path first /client/ -> client', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client/`)); + const res = await (0, index_1.getAssetFromKV)(event); + t.is(await res.text(), 'important file'); + t.true(res.headers.get('content-type').includes('text')); +}); +(0, ava_1.default)('getAssetFromKV evaluated the file matching the extensionless path first /client -> client', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client`)); + const res = await (0, index_1.getAssetFromKV)(event); + t.is(await res.text(), 'important file'); + t.true(res.headers.get('content-type').includes('text')); +}); +(0, ava_1.default)('getAssetFromKV if not in asset manifest still returns nohash.txt', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/nohash.txt')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'no hash but still got some result'); + t.true(res.headers.get('content-type').includes('text')); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV if no asset manifest /client -> client fails', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client`)); + const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_MANIFEST: {} })); + t.is(error.status, 404); +}); +(0, ava_1.default)('getAssetFromKV if sub/ -> sub/index.html served', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/sub`)); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'picturedis'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV gets index.html by default for / requests', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'index.html'); + t.true(res.headers.get('content-type').includes('html')); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV non ASCII path support', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/测试.html')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'My filename is non-ascii'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV supports browser percent encoded URLs', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://example.com/%not-really-percent-encoded.html')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'browser percent encoded'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV supports user percent encoded URLs', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/%2F.html')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'user percent encoded'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV only decode URL when necessary', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD.html')); + const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/你好.html')); + const res1 = await (0, index_1.getAssetFromKV)(event1); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(await res1.text(), 'Im important'); + t.is(await res2.text(), 'Im important'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV Support for user decode url path', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD/')); + const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/你好/')); + const res1 = await (0, index_1.getAssetFromKV)(event1); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(await res1.text(), 'My path is non-ascii'); + t.is(await res2.text(), 'My path is non-ascii'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV custom key modifier', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/docs/sub/blah.png')); + const customRequestMapper = (request) => { + let defaultModifiedRequest = (0, index_1.mapRequestToAsset)(request); + let url = new URL(defaultModifiedRequest.url); + url.pathname = url.pathname.replace('/docs', ''); + return new Request(url.toString(), request); + }; + const res = await (0, index_1.getAssetFromKV)(event, { mapRequestToAsset: customRequestMapper }); + if (res) { + t.is(await res.text(), 'picturedis'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV request override with existing manifest file', async (t) => { + // see https://github.com/cloudflare/kv-asset-handler/pull/159 for more info + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/image.png')); // real file in manifest + const customRequestMapper = (request) => { + let defaultModifiedRequest = (0, index_1.mapRequestToAsset)(request); + let url = new URL(defaultModifiedRequest.url); + url.pathname = '/image.webp'; // other different file in manifest + return new Request(url.toString(), request); + }; + const res = await (0, index_1.getAssetFromKV)(event, { mapRequestToAsset: customRequestMapper }); + if (res) { + t.is(await res.text(), 'imagewebp'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when setting browser caching', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: 22 } }); + if (res) { + t.is(res.headers.get('cache-control'), 'max-age=22'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when setting custom cache setting', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.png?blah=34')); + const cacheOnlyPngs = (req) => { + if (new URL(req.url).pathname.endsWith('.png')) + return { + browserTTL: 720, + edgeTTL: 720, + }; + else + return { + bypassCache: true, + }; + }; + const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: cacheOnlyPngs }); + const res2 = await (0, index_1.getAssetFromKV)(event2, { cacheControl: cacheOnlyPngs }); + if (res1 && res2) { + t.is(res1.headers.get('cache-control'), null); + t.true(res2.headers.get('content-type').includes('png')); + t.is(res2.headers.get('cache-control'), 'max-age=720'); + t.is(res2.headers.get('cf-cache-status'), 'MISS'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV caches on two sequential requests', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'cache.html'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + })); + const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720, browserTTL: 720 } }); + await (0, mocks_1.sleep)(1); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res1.headers.get('cache-control'), 'max-age=720'); + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV does not store max-age on two sequential requests', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'cache.html'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + })); + const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } }); + await (0, mocks_1.sleep)(100); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res1.headers.get('cache-control'), null); + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED'); + t.is(res2.headers.get('cache-control'), null); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV does not cache on Cloudflare when bypass cache set', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res = await (0, index_1.getAssetFromKV)(event, { cacheControl: { bypassCache: true } }); + if (res) { + t.is(res.headers.get('cache-control'), null); + t.is(res.headers.get('cf-cache-status'), null); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV with no trailing slash on root', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'index.html'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV with no trailing slash on a subdirectory', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/sub/blah.png')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'picturedis'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV no result throws an error', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/random')); + const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event)); + t.is(error.status, 404); +}); +(0, ava_1.default)('getAssetFromKV TTls set to null should not cache on browser or edge', async (t) => { + (0, mocks_1.mockRequestScope)(); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: null, edgeTTL: null } }); + await (0, mocks_1.sleep)(100); + const res2 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: null, edgeTTL: null } }); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), null); + t.is(res1.headers.get('cache-control'), null); + t.is(res2.headers.get('cf-cache-status'), null); + t.is(res2.headers.get('cache-control'), null); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV passing in a custom NAMESPACE serves correct asset', async (t) => { + (0, mocks_1.mockRequestScope)(); + let CUSTOM_NAMESPACE = (0, mocks_1.mockKV)({ + 'key1.123HASHBROWN.txt': 'val1', + }); + Object.assign(global, { CUSTOM_NAMESPACE }); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const res = await (0, index_1.getAssetFromKV)(event); + if (res) { + t.is(await res.text(), 'index.html'); + t.true(res.headers.get('content-type').includes('html')); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when custom namespace without the asset should fail', async (t) => { + (0, mocks_1.mockRequestScope)(); + let CUSTOM_NAMESPACE = (0, mocks_1.mockKV)({ + 'key5.123HASHBROWN.txt': 'customvalu', + }); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com')); + const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_NAMESPACE: CUSTOM_NAMESPACE })); + t.is(error.status, 404); +}); +(0, ava_1.default)('getAssetFromKV when namespace not bound fails', async (t) => { + (0, mocks_1.mockRequestScope)(); + var MY_CUSTOM_NAMESPACE = undefined; + Object.assign(global, { MY_CUSTOM_NAMESPACE }); + const event = (0, mocks_1.getEvent)(new Request('https://blah.com/')); + const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_NAMESPACE: MY_CUSTOM_NAMESPACE })); + t.is(error.status, 500); +}); +(0, ava_1.default)('getAssetFromKV when if-none-match === active resource version, should revalidate', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'key1.png'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `W/"${resourceVersion}"`, + }, + })); + const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } }); + await (0, mocks_1.sleep)(100); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when if-none-match equals etag of stale resource then should bypass cache', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'key1.png'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const req1 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }); + const req2 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}-another-version"`, + }, + }); + const event = (0, mocks_1.getEvent)(req1); + const event2 = (0, mocks_1.getEvent)(req2); + const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } }); + const res2 = await (0, index_1.getAssetFromKV)(event); + const res3 = await (0, index_1.getAssetFromKV)(event2); + if (res1 && res2 && res3) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`); + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED'); + t.not(res3.headers.get('etag'), req2.headers.get('if-none-match')); + t.is(res3.headers.get('cf-cache-status'), 'MISS'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV when resource in cache, etag should be weakened before returned to eyeball', async (t) => { + (0, mocks_1.mockRequestScope)(); + const resourceKey = 'key1.png'; + const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey]; + const req1 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }); + const event = (0, mocks_1.getEvent)(req1); + const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } }); + const res2 = await (0, index_1.getAssetFromKV)(event); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV if-none-match not sent but resource in cache, should return cache hit 200 OK', async (t) => { + const resourceKey = 'cache.html'; + const event = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } }); + await (0, mocks_1.sleep)(1); + const res2 = await (0, index_1.getAssetFromKV)(event); + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS'); + t.is(res1.headers.get('cache-control'), null); + t.is(res2.status, 200); + t.is(res2.headers.get('cf-cache-status'), 'HIT'); + } + else { + t.fail('Response was undefined'); + } +}); +(0, ava_1.default)('getAssetFromKV if range request submitted and resource in cache, request fulfilled', async (t) => { + const resourceKey = 'cache.html'; + const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`)); + const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { headers: { range: 'bytes=0-10' } })); + const res1 = (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } }); + await res1; + await (0, mocks_1.sleep)(2); + const res2 = await (0, index_1.getAssetFromKV)(event2); + if (res2.headers.has('content-range')) { + t.is(res2.status, 206); + } + else { + t.fail('Response was undefined'); + } +}); +ava_1.default.todo('getAssetFromKV when body not empty, should invoke .cancel()'); diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js b/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js new file mode 100644 index 0000000..11be912 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ava_1 = require("ava"); +const mocks_1 = require("../mocks"); +(0, mocks_1.mockGlobalScope)(); +const index_1 = require("../index"); +(0, ava_1.default)('mapRequestToAsset() correctly changes /about -> /about/index.html', async (t) => { + (0, mocks_1.mockRequestScope)(); + let path = '/about'; + let request = new Request(`https://foo.com${path}`); + let newRequest = (0, index_1.mapRequestToAsset)(request); + t.is(newRequest.url, request.url + '/index.html'); +}); +(0, ava_1.default)('mapRequestToAsset() correctly changes /about/ -> /about/index.html', async (t) => { + (0, mocks_1.mockRequestScope)(); + let path = '/about/'; + let request = new Request(`https://foo.com${path}`); + let newRequest = (0, index_1.mapRequestToAsset)(request); + t.is(newRequest.url, request.url + 'index.html'); +}); +(0, ava_1.default)('mapRequestToAsset() correctly changes /about.me/ -> /about.me/index.html', async (t) => { + (0, mocks_1.mockRequestScope)(); + let path = '/about.me/'; + let request = new Request(`https://foo.com${path}`); + let newRequest = (0, index_1.mapRequestToAsset)(request); + t.is(newRequest.url, request.url + 'index.html'); +}); +(0, ava_1.default)('mapRequestToAsset() correctly changes /about -> /about/default.html', async (t) => { + (0, mocks_1.mockRequestScope)(); + let path = '/about'; + let request = new Request(`https://foo.com${path}`); + let newRequest = (0, index_1.mapRequestToAsset)(request, { defaultDocument: 'default.html' }); + t.is(newRequest.url, request.url + '/default.html'); +}); diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js b/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js new file mode 100644 index 0000000..8ee0bfb --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ava_1 = require("ava"); +const mocks_1 = require("../mocks"); +(0, mocks_1.mockGlobalScope)(); +const index_1 = require("../index"); +function testRequest(path) { + (0, mocks_1.mockRequestScope)(); + let url = new URL('https://example.com'); + url.pathname = path; + let request = new Request(url.toString()); + return request; +} +(0, ava_1.default)('serveSinglePageApp returns root asset path when request path ends in .html', async (t) => { + let path = '/foo/thing.html'; + let request = testRequest(path); + let expected_request = testRequest('/index.html'); + let actual_request = (0, index_1.serveSinglePageApp)(request); + t.deepEqual(expected_request, actual_request); +}); +(0, ava_1.default)('serveSinglePageApp returns root asset path when request path does not have extension', async (t) => { + let path = '/foo/thing'; + let request = testRequest(path); + let expected_request = testRequest('/index.html'); + let actual_request = (0, index_1.serveSinglePageApp)(request); + t.deepEqual(expected_request, actual_request); +}); +(0, ava_1.default)('serveSinglePageApp returns requested asset when request path has non-html extension', async (t) => { + let path = '/foo/thing.js'; + let request = testRequest(path); + let expected_request = request; + let actual_request = (0, index_1.serveSinglePageApp)(request); + t.deepEqual(expected_request, actual_request); +}); diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts b/node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts new file mode 100644 index 0000000..eef1bff --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts @@ -0,0 +1,28 @@ +export declare type CacheControl = { + browserTTL: number; + edgeTTL: number; + bypassCache: boolean; +}; +export declare type AssetManifestType = Record; +export declare type Options = { + cacheControl: ((req: Request) => Partial) | Partial; + ASSET_NAMESPACE: any; + ASSET_MANIFEST: AssetManifestType | string; + mapRequestToAsset?: (req: Request, options?: Partial) => Request; + defaultMimeType: string; + defaultDocument: string; + pathIsEncoded: boolean; +}; +export declare class KVError extends Error { + constructor(message?: string, status?: number); + status: number; +} +export declare class MethodNotAllowedError extends KVError { + constructor(message?: string, status?: number); +} +export declare class NotFoundError extends KVError { + constructor(message?: string, status?: number); +} +export declare class InternalError extends KVError { + constructor(message?: string, status?: number); +} diff --git a/node_modules/@cloudflare/kv-asset-handler/dist/types.js b/node_modules/@cloudflare/kv-asset-handler/dist/types.js new file mode 100644 index 0000000..ba08c1b --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/dist/types.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.KVError = void 0; +class KVError extends Error { + constructor(message, status = 500) { + super(message); + // see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain + this.name = KVError.name; // stack traces display correctly now + this.status = status; + } +} +exports.KVError = KVError; +class MethodNotAllowedError extends KVError { + constructor(message = `Not a valid request method`, status = 405) { + super(message, status); + } +} +exports.MethodNotAllowedError = MethodNotAllowedError; +class NotFoundError extends KVError { + constructor(message = `Not Found`, status = 404) { + super(message, status); + } +} +exports.NotFoundError = NotFoundError; +class InternalError extends KVError { + constructor(message = `Internal Error in KV Asset Handler`, status = 500) { + super(message, status); + } +} +exports.InternalError = InternalError; diff --git a/node_modules/@cloudflare/kv-asset-handler/package.json b/node_modules/@cloudflare/kv-asset-handler/package.json new file mode 100644 index 0000000..3ec9c42 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/package.json @@ -0,0 +1,52 @@ +{ + "name": "@cloudflare/kv-asset-handler", + "version": "0.2.0", + "description": "Routes requests to KV assets", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "prepack": "npm run build", + "build": "tsc -d", + "format": "prettier --write \"**/*.{js,ts,json,md}\"", + "pretest": "npm run build", + "lint:code": "prettier --check \"**/*.{js,ts,json,md}\"", + "lint:markdown": "markdownlint \"**/*.md\" --ignore node_modules", + "test": "ava dist/test/*.js --verbose" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/cloudflare/kv-asset-handler.git" + }, + "keywords": [ + "kv", + "cloudflare", + "workers", + "wrangler", + "assets" + ], + "files": [ + "src", + "dist", + "LICENSE_APACHE", + "LICENSE_MIT" + ], + "author": "wrangler@cloudflare.com", + "license": "MIT OR Apache-2.0", + "bugs": { + "url": "https://github.com/cloudflare/kv-asset-handler/issues" + }, + "homepage": "https://github.com/cloudflare/kv-asset-handler#readme", + "dependencies": { + "mime": "^3.0.0" + }, + "devDependencies": { + "@ava/typescript": "^3.0.0", + "@cloudflare/workers-types": "^3.0.0", + "@types/mime": "^2.0.3", + "@types/node": "^15.14.9", + "ava": "^3.15.0", + "prettier": "^2.4.1", + "service-worker-mock": "^2.0.5", + "typescript": "^4.4.4" + } +} diff --git a/node_modules/@cloudflare/kv-asset-handler/src/index.ts b/node_modules/@cloudflare/kv-asset-handler/src/index.ts new file mode 100644 index 0000000..5a91b68 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/index.ts @@ -0,0 +1,312 @@ +import * as mime from 'mime' +import { + Options, + CacheControl, + MethodNotAllowedError, + NotFoundError, + InternalError, + AssetManifestType, +} from './types' + +declare global { + var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string +} + +const defaultCacheControl: CacheControl = { + browserTTL: null, + edgeTTL: 2 * 60 * 60 * 24, // 2 days + bypassCache: false, // do not bypass Cloudflare's cache +} + +const parseStringAsObject = (maybeString: string | T): T => + typeof maybeString === 'string' ? (JSON.parse(maybeString) as T) : maybeString + +const getAssetFromKVDefaultOptions: Partial = { + ASSET_NAMESPACE: typeof __STATIC_CONTENT !== 'undefined' ? __STATIC_CONTENT : undefined, + ASSET_MANIFEST: + typeof __STATIC_CONTENT_MANIFEST !== 'undefined' + ? parseStringAsObject(__STATIC_CONTENT_MANIFEST) + : {}, + cacheControl: defaultCacheControl, + defaultMimeType: 'text/plain', + defaultDocument: 'index.html', + pathIsEncoded: false, +} + +function assignOptions(options?: Partial): Options { + // Assign any missing options passed in to the default + // options.mapRequestToAsset is handled manually later + return Object.assign({}, getAssetFromKVDefaultOptions, options) +} + +/** + * maps the path of incoming request to the request pathKey to look up + * in bucket and in cache + * e.g. for a path '/' returns '/index.html' which serves + * the content of bucket/index.html + * @param {Request} request incoming request + */ +const mapRequestToAsset = (request: Request, options?: Partial) => { + options = assignOptions(options) + + const parsedUrl = new URL(request.url) + let pathname = parsedUrl.pathname + + if (pathname.endsWith('/')) { + // If path looks like a directory append options.defaultDocument + // e.g. If path is /about/ -> /about/index.html + pathname = pathname.concat(options.defaultDocument) + } else if (!mime.getType(pathname)) { + // If path doesn't look like valid content + // e.g. /about.me -> /about.me/index.html + pathname = pathname.concat('/' + options.defaultDocument) + } + + parsedUrl.pathname = pathname + return new Request(parsedUrl.toString(), request) +} + +/** + * maps the path of incoming request to /index.html if it evaluates to + * any HTML file. + * @param {Request} request incoming request + */ +function serveSinglePageApp(request: Request, options?: Partial): Request { + options = assignOptions(options) + + // First apply the default handler, which already has logic to detect + // paths that should map to HTML files. + request = mapRequestToAsset(request, options) + + const parsedUrl = new URL(request.url) + + // Detect if the default handler decided to map to + // a HTML file in some specific directory. + if (parsedUrl.pathname.endsWith('.html')) { + // If expected HTML file was missing, just return the root index.html (or options.defaultDocument) + return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request) + } else { + // The default handler decided this is not an HTML page. It's probably + // an image, CSS, or JS file. Leave it as-is. + return request + } +} + +/** + * takes the path of the incoming request, gathers the appropriate content from KV, and returns + * the response + * + * @param {FetchEvent} event the fetch event of the triggered request + * @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options + * @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser + * @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up + * @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references + * @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV + * */ + +type Evt = { + request: Request + waitUntil: (promise: Promise) => void +} + +const getAssetFromKV = async (event: Evt, options?: Partial): Promise => { + options = assignOptions(options) + + const request = event.request + const ASSET_NAMESPACE = options.ASSET_NAMESPACE + const ASSET_MANIFEST = parseStringAsObject(options.ASSET_MANIFEST) + + if (typeof ASSET_NAMESPACE === 'undefined') { + throw new InternalError(`there is no KV namespace bound to the script`) + } + + const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, '') // strip any preceding /'s + let pathIsEncoded = options.pathIsEncoded + let requestKey + // if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions + // otherwise handle request as normal, with default mapRequestToAsset below + if (options.mapRequestToAsset) { + requestKey = options.mapRequestToAsset(request) + } else if (ASSET_MANIFEST[rawPathKey]) { + requestKey = request + } else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) { + pathIsEncoded = true + requestKey = request + } else { + const mappedRequest = mapRequestToAsset(request) + const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, '') + if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) { + pathIsEncoded = true + requestKey = mappedRequest + } else { + // use default mapRequestToAsset + requestKey = mapRequestToAsset(request, options) + } + } + + const SUPPORTED_METHODS = ['GET', 'HEAD'] + if (!SUPPORTED_METHODS.includes(requestKey.method)) { + throw new MethodNotAllowedError(`${requestKey.method} is not a valid request method`) + } + + const parsedUrl = new URL(requestKey.url) + const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname // decode percentage encoded path only when necessary + + // pathKey is the file path to look up in the manifest + let pathKey = pathname.replace(/^\/+/, '') // remove prepended / + + // @ts-ignore + const cache = caches.default + let mimeType = mime.getType(pathKey) || options.defaultMimeType + if (mimeType.startsWith('text') || mimeType === 'application/javascript') { + mimeType += '; charset=utf-8' + } + + let shouldEdgeCache = false // false if storing in KV by raw file path i.e. no hash + // check manifest for map from file path to hash + if (typeof ASSET_MANIFEST !== 'undefined') { + if (ASSET_MANIFEST[pathKey]) { + pathKey = ASSET_MANIFEST[pathKey] + // if path key is in asset manifest, we can assume it contains a content hash and can be cached + shouldEdgeCache = true + } + } + + // TODO this excludes search params from cache, investigate ideal behavior + let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request) + + // if argument passed in for cacheControl is a function then + // evaluate that function. otherwise return the Object passed in + // or default Object + const evalCacheOpts = (() => { + switch (typeof options.cacheControl) { + case 'function': + return options.cacheControl(request) + case 'object': + return options.cacheControl + default: + return defaultCacheControl + } + })() + + // formats the etag depending on the response context. if the entityId + // is invalid, returns an empty string (instead of null) to prevent the + // the potentially disastrous scenario where the value of the Etag resp + // header is "null". Could be modified in future to base64 encode etc + const formatETag = (entityId: any = pathKey, validatorType: string = 'strong') => { + if (!entityId) { + return '' + } + switch (validatorType) { + case 'weak': + if (!entityId.startsWith('W/')) { + return `W/${entityId}` + } + return entityId + case 'strong': + if (entityId.startsWith(`W/"`)) { + entityId = entityId.replace('W/', '') + } + if (!entityId.endsWith(`"`)) { + entityId = `"${entityId}"` + } + return entityId + default: + return '' + } + } + + options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts) + + // override shouldEdgeCache if options say to bypassCache + if ( + options.cacheControl.bypassCache || + options.cacheControl.edgeTTL === null || + request.method == 'HEAD' + ) { + shouldEdgeCache = false + } + // only set max-age if explicitly passed in a number as an arg + const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === 'number' + + let response = null + if (shouldEdgeCache) { + response = await cache.match(cacheKey) + } + + if (response) { + if (response.status > 300 && response.status < 400) { + if (response.body && 'cancel' in Object.getPrototypeOf(response.body)) { + // Body exists and environment supports readable streams + response.body.cancel() + } else { + // Environment doesnt support readable streams, or null repsonse body. Nothing to do + } + response = new Response(null, response) + } else { + // fixes #165 + let opts = { + headers: new Headers(response.headers), + status: 0, + statusText: '', + } + + opts.headers.set('cf-cache-status', 'HIT') + + if (response.status) { + opts.status = response.status + opts.statusText = response.statusText + } else if (opts.headers.has('Content-Range')) { + opts.status = 206 + opts.statusText = 'Partial Content' + } else { + opts.status = 200 + opts.statusText = 'OK' + } + response = new Response(response.body, opts) + } + } else { + const body = await ASSET_NAMESPACE.get(pathKey, 'arrayBuffer') + if (body === null) { + throw new NotFoundError(`could not find ${pathKey} in your content namespace`) + } + response = new Response(body) + + if (shouldEdgeCache) { + response.headers.set('Accept-Ranges', 'bytes') + response.headers.set('Content-Length', body.length) + // set etag before cache insertion + if (!response.headers.has('etag')) { + response.headers.set('etag', formatETag(pathKey, 'strong')) + } + // determine Cloudflare cache behavior + response.headers.set('Cache-Control', `max-age=${options.cacheControl.edgeTTL}`) + event.waitUntil(cache.put(cacheKey, response.clone())) + response.headers.set('CF-Cache-Status', 'MISS') + } + } + response.headers.set('Content-Type', mimeType) + + if (response.status === 304) { + let etag = formatETag(response.headers.get('etag'), 'strong') + let ifNoneMatch = cacheKey.headers.get('if-none-match') + let proxyCacheStatus = response.headers.get('CF-Cache-Status') + if (etag) { + if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === 'MISS') { + response.headers.set('CF-Cache-Status', 'EXPIRED') + } else { + response.headers.set('CF-Cache-Status', 'REVALIDATED') + } + response.headers.set('etag', formatETag(etag, 'weak')) + } + } + if (shouldSetBrowserCache) { + response.headers.set('Cache-Control', `max-age=${options.cacheControl.browserTTL}`) + } else { + response.headers.delete('Cache-Control') + } + return response +} + +export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp } +export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError } diff --git a/node_modules/@cloudflare/kv-asset-handler/src/mocks.ts b/node_modules/@cloudflare/kv-asset-handler/src/mocks.ts new file mode 100644 index 0000000..b42fb74 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/mocks.ts @@ -0,0 +1,148 @@ +const makeServiceWorkerEnv = require('service-worker-mock') + +const HASH = '123HASHBROWN' + +export const getEvent = (request: Request): any => { + const waitUntil = async (callback: any) => { + await callback + } + return { + request, + waitUntil, + } +} +const store: any = { + 'key1.123HASHBROWN.txt': 'val1', + 'key1.123HASHBROWN.png': 'val1', + 'index.123HASHBROWN.html': 'index.html', + 'cache.123HASHBROWN.html': 'cache me if you can', + '测试.123HASHBROWN.html': 'My filename is non-ascii', + '%not-really-percent-encoded.123HASHBROWN.html': 'browser percent encoded', + '%2F.123HASHBROWN.html': 'user percent encoded', + '你好.123HASHBROWN.html': 'I shouldnt be served', + '%E4%BD%A0%E5%A5%BD.123HASHBROWN.html': 'Im important', + 'nohash.txt': 'no hash but still got some result', + 'sub/blah.123HASHBROWN.png': 'picturedis', + 'sub/index.123HASHBROWN.html': 'picturedis', + 'client.123HASHBROWN': 'important file', + 'client.123HASHBROWN/index.html': 'Im here but serve my big bro above', + 'image.123HASHBROWN.png': 'imagepng', + 'image.123HASHBROWN.webp': 'imagewebp', + '你好/index.123HASHBROWN.html': 'My path is non-ascii', +} +export const mockKV = (store: any) => { + return { + get: (path: string) => store[path] || null, + } +} + +export const mockManifest = () => { + return JSON.stringify({ + 'key1.txt': `key1.${HASH}.txt`, + 'key1.png': `key1.${HASH}.png`, + 'cache.html': `cache.${HASH}.html`, + '测试.html': `测试.${HASH}.html`, + '你好.html': `你好.${HASH}.html`, + '%not-really-percent-encoded.html': `%not-really-percent-encoded.${HASH}.html`, + '%2F.html': `%2F.${HASH}.html`, + '%E4%BD%A0%E5%A5%BD.html': `%E4%BD%A0%E5%A5%BD.${HASH}.html`, + 'index.html': `index.${HASH}.html`, + 'sub/blah.png': `sub/blah.${HASH}.png`, + 'sub/index.html': `sub/index.${HASH}.html`, + client: `client.${HASH}`, + 'client/index.html': `client.${HASH}`, + 'image.png': `image.${HASH}.png`, + 'image.webp': `image.${HASH}.webp`, + '你好/index.html': `你好/index.${HASH}.html`, + }) +} + +let cacheStore: any = new Map() +interface CacheKey { + url: object + headers: object +} +export const mockCaches = () => { + return { + default: { + async match(key: any) { + let cacheKey: CacheKey = { + url: key.url, + headers: {}, + } + let response + if (key.headers.has('if-none-match')) { + let makeStrongEtag = key.headers.get('if-none-match').replace('W/', '') + Reflect.set(cacheKey.headers, 'etag', makeStrongEtag) + response = cacheStore.get(JSON.stringify(cacheKey)) + } else { + // if client doesn't send if-none-match, we need to iterate through these keys + // and just test the URL + const activeCacheKeys: Array = Array.from(cacheStore.keys()) + for (const cacheStoreKey of activeCacheKeys) { + if (JSON.parse(cacheStoreKey).url === key.url) { + response = cacheStore.get(cacheStoreKey) + } + } + } + // TODO: write test to accomodate for rare scenarios with where range requests accomodate etags + if (response && !key.headers.has('if-none-match')) { + // this appears overly verbose, but is necessary to document edge cache behavior + // The Range request header triggers the response header Content-Range ... + const range = key.headers.get('range') + if (range) { + response.headers.set( + 'content-range', + `bytes ${range.split('=').pop()}/${response.headers.get('content-length')}`, + ) + } + // ... which we are using in this repository to set status 206 + if (response.headers.has('content-range')) { + response.status = 206 + } else { + response.status = 200 + } + let etag = response.headers.get('etag') + if (etag && !etag.includes('W/')) { + response.headers.set('etag', `W/${etag}`) + } + } + return response + }, + async put(key: any, val: Response) { + let headers = new Headers(val.headers) + let url = new URL(key.url) + let resWithBody = new Response(val.body, { headers, status: 200 }) + let resNoBody = new Response(null, { headers, status: 304 }) + let cacheKey: CacheKey = { + url: key.url, + headers: { + etag: `"${url.pathname.replace('/', '')}"`, + }, + } + cacheStore.set(JSON.stringify(cacheKey), resNoBody) + cacheKey.headers = {} + cacheStore.set(JSON.stringify(cacheKey), resWithBody) + return + }, + }, + } +} + +// mocks functionality used inside worker request +export function mockRequestScope() { + Object.assign(global, makeServiceWorkerEnv()) + Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() }) + Object.assign(global, { __STATIC_CONTENT: mockKV(store) }) + Object.assign(global, { caches: mockCaches() }) +} + +// mocks functionality used on global isolate scope. such as the KV namespace bind +export function mockGlobalScope() { + Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() }) + Object.assign(global, { __STATIC_CONTENT: mockKV(store) }) +} + +export const sleep = (milliseconds: number) => { + return new Promise((resolve) => setTimeout(resolve, milliseconds)) +} diff --git a/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV-optional.ts b/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV-optional.ts new file mode 100644 index 0000000..9740b7d --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV-optional.ts @@ -0,0 +1,24 @@ +import test from 'ava' +import { mockRequestScope, mockGlobalScope, getEvent, sleep, mockKV, mockManifest } from '../mocks' +mockGlobalScope() + +// manually reset manifest global, to test optional behaviour +Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined }) + +import { getAssetFromKV, mapRequestToAsset } from '../index' + +test('getAssetFromKV return correct val from KV without manifest', async (t) => { + mockRequestScope() + // manually reset manifest global, to test optional behaviour + Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined }) + + const event = getEvent(new Request('https://blah.com/key1.123HASHBROWN.txt')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'val1') + t.true(res.headers.get('content-type').includes('text')) + } else { + t.fail('Response was undefined') + } +}) diff --git a/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts b/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts new file mode 100644 index 0000000..425d622 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts @@ -0,0 +1,488 @@ +import test from 'ava' +import { mockRequestScope, mockGlobalScope, getEvent, sleep, mockKV, mockManifest } from '../mocks' +mockGlobalScope() + +import { getAssetFromKV, mapRequestToAsset } from '../index' +import { KVError } from '../types' + +test('getAssetFromKV return correct val from KV and default caching', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/key1.txt')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(res.headers.get('cache-control'), null) + t.is(res.headers.get('cf-cache-status'), 'MISS') + t.is(await res.text(), 'val1') + t.true(res.headers.get('content-type').includes('text')) + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV evaluated the file matching the extensionless path first /client/ -> client', async (t) => { + mockRequestScope() + const event = getEvent(new Request(`https://foo.com/client/`)) + const res = await getAssetFromKV(event) + t.is(await res.text(), 'important file') + t.true(res.headers.get('content-type').includes('text')) +}) +test('getAssetFromKV evaluated the file matching the extensionless path first /client -> client', async (t) => { + mockRequestScope() + const event = getEvent(new Request(`https://foo.com/client`)) + const res = await getAssetFromKV(event) + t.is(await res.text(), 'important file') + t.true(res.headers.get('content-type').includes('text')) +}) + +test('getAssetFromKV if not in asset manifest still returns nohash.txt', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/nohash.txt')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'no hash but still got some result') + t.true(res.headers.get('content-type').includes('text')) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV if no asset manifest /client -> client fails', async (t) => { + mockRequestScope() + const event = getEvent(new Request(`https://foo.com/client`)) + const error: KVError = await t.throwsAsync(getAssetFromKV(event, { ASSET_MANIFEST: {} })) + t.is(error.status, 404) +}) + +test('getAssetFromKV if sub/ -> sub/index.html served', async (t) => { + mockRequestScope() + const event = getEvent(new Request(`https://foo.com/sub`)) + const res = await getAssetFromKV(event) + if (res) { + t.is(await res.text(), 'picturedis') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV gets index.html by default for / requests', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'index.html') + t.true(res.headers.get('content-type').includes('html')) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV non ASCII path support', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/测试.html')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'My filename is non-ascii') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV supports browser percent encoded URLs', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://example.com/%not-really-percent-encoded.html')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'browser percent encoded') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV supports user percent encoded URLs', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/%2F.html')) + const res = await getAssetFromKV(event) + + if (res) { + t.is(await res.text(), 'user percent encoded') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV only decode URL when necessary', async (t) => { + mockRequestScope() + const event1 = getEvent(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD.html')) + const event2 = getEvent(new Request('https://blah.com/你好.html')) + const res1 = await getAssetFromKV(event1) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(await res1.text(), 'Im important') + t.is(await res2.text(), 'Im important') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV Support for user decode url path', async (t) => { + mockRequestScope() + const event1 = getEvent(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD/')) + const event2 = getEvent(new Request('https://blah.com/你好/')) + const res1 = await getAssetFromKV(event1) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(await res1.text(), 'My path is non-ascii') + t.is(await res2.text(), 'My path is non-ascii') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV custom key modifier', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/docs/sub/blah.png')) + + const customRequestMapper = (request: Request) => { + let defaultModifiedRequest = mapRequestToAsset(request) + + let url = new URL(defaultModifiedRequest.url) + url.pathname = url.pathname.replace('/docs', '') + return new Request(url.toString(), request) + } + + const res = await getAssetFromKV(event, { mapRequestToAsset: customRequestMapper }) + + if (res) { + t.is(await res.text(), 'picturedis') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV request override with existing manifest file', async (t) => { + // see https://github.com/cloudflare/kv-asset-handler/pull/159 for more info + mockRequestScope() + const event = getEvent(new Request('https://blah.com/image.png')) // real file in manifest + + const customRequestMapper = (request: Request) => { + let defaultModifiedRequest = mapRequestToAsset(request) + + let url = new URL(defaultModifiedRequest.url) + url.pathname = '/image.webp' // other different file in manifest + return new Request(url.toString(), request) + } + + const res = await getAssetFromKV(event, { mapRequestToAsset: customRequestMapper }) + + if (res) { + t.is(await res.text(), 'imagewebp') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV when setting browser caching', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/')) + + const res = await getAssetFromKV(event, { cacheControl: { browserTTL: 22 } }) + + if (res) { + t.is(res.headers.get('cache-control'), 'max-age=22') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV when setting custom cache setting', async (t) => { + mockRequestScope() + const event1 = getEvent(new Request('https://blah.com/')) + const event2 = getEvent(new Request('https://blah.com/key1.png?blah=34')) + const cacheOnlyPngs = (req: Request) => { + if (new URL(req.url).pathname.endsWith('.png')) + return { + browserTTL: 720, + edgeTTL: 720, + } + else + return { + bypassCache: true, + } + } + + const res1 = await getAssetFromKV(event1, { cacheControl: cacheOnlyPngs }) + const res2 = await getAssetFromKV(event2, { cacheControl: cacheOnlyPngs }) + + if (res1 && res2) { + t.is(res1.headers.get('cache-control'), null) + t.true(res2.headers.get('content-type').includes('png')) + t.is(res2.headers.get('cache-control'), 'max-age=720') + t.is(res2.headers.get('cf-cache-status'), 'MISS') + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV caches on two sequential requests', async (t) => { + mockRequestScope() + const resourceKey = 'cache.html' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const event2 = getEvent( + new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }), + ) + + const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720, browserTTL: 720 } }) + await sleep(1) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res1.headers.get('cache-control'), 'max-age=720') + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED') + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV does not store max-age on two sequential requests', async (t) => { + mockRequestScope() + const resourceKey = 'cache.html' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const event2 = getEvent( + new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }), + ) + + const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } }) + await sleep(100) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res1.headers.get('cache-control'), null) + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED') + t.is(res2.headers.get('cache-control'), null) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV does not cache on Cloudflare when bypass cache set', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/')) + + const res = await getAssetFromKV(event, { cacheControl: { bypassCache: true } }) + + if (res) { + t.is(res.headers.get('cache-control'), null) + t.is(res.headers.get('cf-cache-status'), null) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV with no trailing slash on root', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com')) + const res = await getAssetFromKV(event) + if (res) { + t.is(await res.text(), 'index.html') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV with no trailing slash on a subdirectory', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/sub/blah.png')) + const res = await getAssetFromKV(event) + if (res) { + t.is(await res.text(), 'picturedis') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV no result throws an error', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/random')) + const error: KVError = await t.throwsAsync(getAssetFromKV(event)) + t.is(error.status, 404) +}) +test('getAssetFromKV TTls set to null should not cache on browser or edge', async (t) => { + mockRequestScope() + const event = getEvent(new Request('https://blah.com/')) + + const res1 = await getAssetFromKV(event, { cacheControl: { browserTTL: null, edgeTTL: null } }) + await sleep(100) + const res2 = await getAssetFromKV(event, { cacheControl: { browserTTL: null, edgeTTL: null } }) + + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), null) + t.is(res1.headers.get('cache-control'), null) + t.is(res2.headers.get('cf-cache-status'), null) + t.is(res2.headers.get('cache-control'), null) + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV passing in a custom NAMESPACE serves correct asset', async (t) => { + mockRequestScope() + let CUSTOM_NAMESPACE = mockKV({ + 'key1.123HASHBROWN.txt': 'val1', + }) + Object.assign(global, { CUSTOM_NAMESPACE }) + const event = getEvent(new Request('https://blah.com/')) + const res = await getAssetFromKV(event) + if (res) { + t.is(await res.text(), 'index.html') + t.true(res.headers.get('content-type').includes('html')) + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV when custom namespace without the asset should fail', async (t) => { + mockRequestScope() + let CUSTOM_NAMESPACE = mockKV({ + 'key5.123HASHBROWN.txt': 'customvalu', + }) + + const event = getEvent(new Request('https://blah.com')) + const error: KVError = await t.throwsAsync( + getAssetFromKV(event, { ASSET_NAMESPACE: CUSTOM_NAMESPACE }), + ) + t.is(error.status, 404) +}) +test('getAssetFromKV when namespace not bound fails', async (t) => { + mockRequestScope() + var MY_CUSTOM_NAMESPACE = undefined + Object.assign(global, { MY_CUSTOM_NAMESPACE }) + + const event = getEvent(new Request('https://blah.com/')) + const error: KVError = await t.throwsAsync( + getAssetFromKV(event, { ASSET_NAMESPACE: MY_CUSTOM_NAMESPACE }), + ) + t.is(error.status, 500) +}) + +test('getAssetFromKV when if-none-match === active resource version, should revalidate', async (t) => { + mockRequestScope() + const resourceKey = 'key1.png' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const event2 = getEvent( + new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `W/"${resourceVersion}"`, + }, + }), + ) + + const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } }) + await sleep(100) + const res2 = await getAssetFromKV(event2) + + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV when if-none-match equals etag of stale resource then should bypass cache', async (t) => { + mockRequestScope() + const resourceKey = 'key1.png' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const req1 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }) + const req2 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}-another-version"`, + }, + }) + const event = getEvent(req1) + const event2 = getEvent(req2) + const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } }) + const res2 = await getAssetFromKV(event) + const res3 = await getAssetFromKV(event2) + if (res1 && res2 && res3) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`) + t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED') + t.not(res3.headers.get('etag'), req2.headers.get('if-none-match')) + t.is(res3.headers.get('cf-cache-status'), 'MISS') + } else { + t.fail('Response was undefined') + } +}) +test('getAssetFromKV when resource in cache, etag should be weakened before returned to eyeball', async (t) => { + mockRequestScope() + const resourceKey = 'key1.png' + const resourceVersion = JSON.parse(mockManifest())[resourceKey] + const req1 = new Request(`https://blah.com/${resourceKey}`, { + headers: { + 'if-none-match': `"${resourceVersion}"`, + }, + }) + const event = getEvent(req1) + const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } }) + const res2 = await getAssetFromKV(event) + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`) + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV if-none-match not sent but resource in cache, should return cache hit 200 OK', async (t) => { + const resourceKey = 'cache.html' + const event = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } }) + await sleep(1) + const res2 = await getAssetFromKV(event) + if (res1 && res2) { + t.is(res1.headers.get('cf-cache-status'), 'MISS') + t.is(res1.headers.get('cache-control'), null) + t.is(res2.status, 200) + t.is(res2.headers.get('cf-cache-status'), 'HIT') + } else { + t.fail('Response was undefined') + } +}) + +test('getAssetFromKV if range request submitted and resource in cache, request fulfilled', async (t) => { + const resourceKey = 'cache.html' + const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`)) + const event2 = getEvent( + new Request(`https://blah.com/${resourceKey}`, { headers: { range: 'bytes=0-10' } }), + ) + const res1 = getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } }) + await res1 + await sleep(2) + const res2 = await getAssetFromKV(event2) + if (res2.headers.has('content-range')) { + t.is(res2.status, 206) + } else { + t.fail('Response was undefined') + } +}) + +test.todo('getAssetFromKV when body not empty, should invoke .cancel()') diff --git a/node_modules/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts b/node_modules/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts new file mode 100644 index 0000000..422165e --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts @@ -0,0 +1,37 @@ +import test from 'ava' +import { mockRequestScope, mockGlobalScope } from '../mocks' +mockGlobalScope() + +import { mapRequestToAsset } from '../index' + +test('mapRequestToAsset() correctly changes /about -> /about/index.html', async (t) => { + mockRequestScope() + let path = '/about' + let request = new Request(`https://foo.com${path}`) + let newRequest = mapRequestToAsset(request) + t.is(newRequest.url, request.url + '/index.html') +}) + +test('mapRequestToAsset() correctly changes /about/ -> /about/index.html', async (t) => { + mockRequestScope() + let path = '/about/' + let request = new Request(`https://foo.com${path}`) + let newRequest = mapRequestToAsset(request) + t.is(newRequest.url, request.url + 'index.html') +}) + +test('mapRequestToAsset() correctly changes /about.me/ -> /about.me/index.html', async (t) => { + mockRequestScope() + let path = '/about.me/' + let request = new Request(`https://foo.com${path}`) + let newRequest = mapRequestToAsset(request) + t.is(newRequest.url, request.url + 'index.html') +}) + +test('mapRequestToAsset() correctly changes /about -> /about/default.html', async (t) => { + mockRequestScope() + let path = '/about' + let request = new Request(`https://foo.com${path}`) + let newRequest = mapRequestToAsset(request, { defaultDocument: 'default.html' }) + t.is(newRequest.url, request.url + '/default.html') +}) diff --git a/node_modules/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts b/node_modules/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts new file mode 100644 index 0000000..6c634c8 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts @@ -0,0 +1,44 @@ +import test from 'ava' +import { mockRequestScope, mockGlobalScope } from '../mocks' +mockGlobalScope() + +import { serveSinglePageApp } from '../index' + +function testRequest(path: string) { + mockRequestScope() + let url = new URL('https://example.com') + url.pathname = path + let request = new Request(url.toString()) + + return request +} + +test('serveSinglePageApp returns root asset path when request path ends in .html', async (t) => { + let path = '/foo/thing.html' + let request = testRequest(path) + + let expected_request = testRequest('/index.html') + let actual_request = serveSinglePageApp(request) + + t.deepEqual(expected_request, actual_request) +}) + +test('serveSinglePageApp returns root asset path when request path does not have extension', async (t) => { + let path = '/foo/thing' + let request = testRequest(path) + + let expected_request = testRequest('/index.html') + let actual_request = serveSinglePageApp(request) + + t.deepEqual(expected_request, actual_request) +}) + +test('serveSinglePageApp returns requested asset when request path has non-html extension', async (t) => { + let path = '/foo/thing.js' + let request = testRequest(path) + + let expected_request = request + let actual_request = serveSinglePageApp(request) + + t.deepEqual(expected_request, actual_request) +}) diff --git a/node_modules/@cloudflare/kv-asset-handler/src/types.ts b/node_modules/@cloudflare/kv-asset-handler/src/types.ts new file mode 100644 index 0000000..c806076 --- /dev/null +++ b/node_modules/@cloudflare/kv-asset-handler/src/types.ts @@ -0,0 +1,43 @@ +export type CacheControl = { + browserTTL: number + edgeTTL: number + bypassCache: boolean +} + +export type AssetManifestType = Record + +export type Options = { + cacheControl: ((req: Request) => Partial) | Partial + ASSET_NAMESPACE: any + ASSET_MANIFEST: AssetManifestType | string + mapRequestToAsset?: (req: Request, options?: Partial) => Request + defaultMimeType: string + defaultDocument: string + pathIsEncoded: boolean +} + +export class KVError extends Error { + constructor(message?: string, status: number = 500) { + super(message) + // see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html + Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain + this.name = KVError.name // stack traces display correctly now + this.status = status + } + status: number +} +export class MethodNotAllowedError extends KVError { + constructor(message: string = `Not a valid request method`, status: number = 405) { + super(message, status) + } +} +export class NotFoundError extends KVError { + constructor(message: string = `Not Found`, status: number = 404) { + super(message, status) + } +} +export class InternalError extends KVError { + constructor(message: string = `Internal Error in KV Asset Handler`, status: number = 500) { + super(message, status) + } +} diff --git a/node_modules/@cloudflare/workerd-windows-64/README.md b/node_modules/@cloudflare/workerd-windows-64/README.md new file mode 100644 index 0000000..ddb3c4e --- /dev/null +++ b/node_modules/@cloudflare/workerd-windows-64/README.md @@ -0,0 +1,6 @@ +# 👷 `workerd` for Windows 64-bit, Cloudflare's JavaScript/Wasm Runtime + +`workerd` is a JavaScript / Wasm server runtime based on the same code that powers +[Cloudflare Workers](https://workers.dev). + +See https://github.com/cloudflare/workerd for details. diff --git a/node_modules/@cloudflare/workerd-windows-64/bin/workerd.exe b/node_modules/@cloudflare/workerd-windows-64/bin/workerd.exe new file mode 100644 index 0000000..bb27e5f Binary files /dev/null and b/node_modules/@cloudflare/workerd-windows-64/bin/workerd.exe differ diff --git a/node_modules/@cloudflare/workerd-windows-64/package.json b/node_modules/@cloudflare/workerd-windows-64/package.json new file mode 100644 index 0000000..c2b5f68 --- /dev/null +++ b/node_modules/@cloudflare/workerd-windows-64/package.json @@ -0,0 +1,17 @@ +{ + "name": "@cloudflare/workerd-windows-64", + "description": "👷 workerd for Windows 64-bit, Cloudflare's JavaScript/Wasm Runtime", + "repository": "https://github.com/cloudflare/workerd", + "license": "Apache-2.0", + "preferUnplugged": false, + "engines": { + "node": ">=16" + }, + "os": [ + "win32" + ], + "cpu": [ + "x64" + ], + "version": "1.20230922.0" +} diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/Buffer.js b/node_modules/@esbuild-plugins/node-globals-polyfill/Buffer.js new file mode 100644 index 0000000..a857959 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/Buffer.js @@ -0,0 +1,2168 @@ +// taken from https://github.com/calvinmetcalf/buffer-es6 + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array +var inited = false +function init() { + inited = true + var code = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 +} + +function base64toByteArray(b64) { + if (!inited) { + init() + } + var i, j, l, tmp, placeHolders, arr + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr((len * 3) / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xff + arr[L++] = (tmp >> 8) & 0xff + arr[L++] = tmp & 0xff + } + + if (placeHolders === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xff + } else if (placeHolders === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xff + arr[L++] = tmp & 0xff + } + + return arr +} + +function tripletToBase64(num) { + return ( + lookup[(num >> 18) & 0x3f] + + lookup[(num >> 12) & 0x3f] + + lookup[(num >> 6) & 0x3f] + + lookup[num & 0x3f] + ) +} + +function encodeChunk(uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2] + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function base64fromByteArray(uint8) { + if (!inited) { + init() + } + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push( + encodeChunk( + uint8, + i, + i + maxChunkLength > len2 ? len2 : i + maxChunkLength, + ), + ) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3f] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3f] + output += lookup[(tmp << 2) & 0x3f] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +var INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = + global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : true + +function kMaxLength() { + return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff +} + +function createBuffer(that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +export function Buffer(arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string', + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function(arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from(that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function(value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +Buffer.kMaxLength = kMaxLength() + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if ( + typeof Symbol !== 'undefined' && + Symbol.species && + Buffer[Symbol.species] === Buffer + ) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + // Object.defineProperty(Buffer, Symbol.species, { + // value: null, + // configurable: true + // }) + } +} + +function assertSize(size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc(that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function(size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe(that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function(size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function(size) { + return allocUnsafe(null, size) +} + +function fromString(that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike(that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer(that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError("'offset' is out of bounds") + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError("'length' is out of bounds") + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ( + (typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || + 'length' in obj + ) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError( + 'First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.', + ) +} + +function checked(length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError( + 'Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + + kMaxLength().toString(16) + + ' bytes', + ) + } + return length | 0 +} + +export function SlowBuffer(length) { + if (+length != length) { + // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} +Buffer.isBuffer = isBuffer +function internalIsBuffer(b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare(a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat(list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength(string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if ( + typeof ArrayBuffer !== 'undefined' && + typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer) + ) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString(encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) + throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap(b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16() { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32() { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64() { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString() { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals(b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + + +Buffer.prototype.compare = function compare( + target, + start, + end, + thisStart, + thisEnd, +) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if ( + start < 0 || + end > target.length || + thisStart < 0 || + thisEnd > this.length + ) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1 + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xff // Search for a byte value [0-255] + if ( + Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function' + ) { + if (dir) { + return Uint8Array.prototype.indexOf.call( + buffer, + val, + byteOffset, + ) + } else { + return Uint8Array.prototype.lastIndexOf.call( + buffer, + val, + byteOffset, + ) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if ( + encoding === 'ucs2' || + encoding === 'ucs-2' || + encoding === 'utf16le' || + encoding === 'utf-16le' + ) { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read(buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if ( + read(arr, i) === + read(val, foundIndex === -1 ? 0 : i - foundIndex) + ) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) + return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) + byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write(buf, string, offset, length) { + return blitBuffer( + utf8ToBytes(string, buf.length - offset), + buf, + offset, + length, + ) +} + +function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write(buf, string, offset, length) { + return blitBuffer( + utf16leToBytes(string, buf.length - offset), + buf, + offset, + length, + ) +} + +Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported', + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ( + (string.length > 0 && (length < 0 || offset < 0)) || + offset > this.length + ) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) + throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON() { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0), + } +} + +function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64fromByteArray(buf) + } else { + return base64fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = + firstByte > 0xef + ? 4 + : firstByte > 0xdf + ? 3 + : firstByte > 0xbf + ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xc0) === 0x80) { + tempCodePoint = + ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f) + if (tempCodePoint > 0x7f) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ( + (secondByte & 0xc0) === 0x80 && + (thirdByte & 0xc0) === 0x80 + ) { + tempCodePoint = + ((firstByte & 0xf) << 0xc) | + ((secondByte & 0x3f) << 0x6) | + (thirdByte & 0x3f) + if ( + tempCodePoint > 0x7ff && + (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff) + ) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ( + (secondByte & 0xc0) === 0x80 && + (thirdByte & 0xc0) === 0x80 && + (fourthByte & 0xc0) === 0x80 + ) { + tempCodePoint = + ((firstByte & 0xf) << 0x12) | + ((secondByte & 0x3f) << 0xc) | + ((thirdByte & 0x3f) << 0x6) | + (fourthByte & 0x3f) + if ( + tempCodePoint > 0xffff && + tempCodePoint < 0x110000 + ) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xfffd + bytesPerSequence = 1 + } else if (codePoint > 0xffff) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(((codePoint >>> 10) & 0x3ff) | 0xd800) + codePoint = 0xdc00 | (codePoint & 0x3ff) + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray(codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH)), + ) + } + return res +} + +function asciiSlice(buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7f) + } + return ret +} + +function latin1Slice(buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice(buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice(start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) + throw new RangeError('offset is not uint') + if (offset + ext > length) + throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE( + offset, + byteLength, + noAssert, +) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE( + offset, + byteLength, + noAssert, +) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ( + (this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + + this[offset + 3] * 0x1000000 + ) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ( + this[offset] * 0x1000000 + + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) + ) +} + +Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return this[offset] + return (0xff - this[offset] + 1) * -1 +} + +Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return val & 0x8000 ? val | 0xffff0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return val & 0x8000 ? val | 0xffff0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ( + this[offset] | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + ) +} + +Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ( + (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3] + ) +} + +Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754read(this, offset, false, 52, 8) +} + +function checkInt(buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) + throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) + throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE( + value, + offset, + byteLength, + noAssert, +) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xff + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE( + value, + offset, + byteLength, + noAssert, +) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xff + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = value & 0xff + return offset + 1 +} + +function objectWriteUInt16(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = + (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + ((littleEndian ? i : 1 - i) * 8) + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE( + value, + offset, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff + this[offset + 1] = value >>> 8 + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE( + value, + offset, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8 + this[offset + 1] = value & 0xff + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> ((littleEndian ? i : 3 - i) * 8)) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE( + value, + offset, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = value >>> 24 + this[offset + 2] = value >>> 16 + this[offset + 1] = value >>> 8 + this[offset] = value & 0xff + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE( + value, + offset, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24 + this[offset + 1] = value >>> 16 + this[offset + 2] = value >>> 8 + this[offset + 3] = value & 0xff + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE( + value, + offset, + byteLength, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xff + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE( + value, + offset, + byteLength, + noAssert, +) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xff + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = value & 0xff + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff + this[offset + 1] = value >>> 8 + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8 + this[offset + 1] = value & 0xff + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff + this[offset + 1] = value >>> 8 + this[offset + 2] = value >>> 16 + this[offset + 3] = value >>> 24 + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24 + this[offset + 1] = value >>> 16 + this[offset + 2] = value >>> 8 + this[offset + 3] = value & 0xff + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754( + buf, + value, + offset, + 4, + 3.4028234663852886e38, + -3.4028234663852886e38, + ) + } + ieee754write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754( + buf, + value, + offset, + 8, + 1.7976931348623157e308, + -1.7976931348623157e308, + ) + } + ieee754write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE( + value, + offset, + noAssert, +) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE( + value, + offset, + noAssert, +) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) + throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart, + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean(str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim(str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex(n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes(string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xd7ff && codePoint < 0xe000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xdbff) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xdc00) { + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = + (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push((codePoint >> 0x6) | 0xc0, (codePoint & 0x3f) | 0x80) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + (codePoint >> 0xc) | 0xe0, + ((codePoint >> 0x6) & 0x3f) | 0x80, + (codePoint & 0x3f) | 0x80, + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + (codePoint >> 0x12) | 0xf0, + ((codePoint >> 0xc) & 0x3f) | 0x80, + ((codePoint >> 0x6) & 0x3f) | 0x80, + (codePoint & 0x3f) | 0x80, + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes(str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xff) + } + return byteArray +} + +function utf16leToBytes(str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes(str) { + return base64toByteArray(base64clean(str)) +} + +function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break + dst[i + offset] = src[i] + } + return i +} + +function isnan(val) { + return val !== val // eslint-disable-line no-self-compare +} + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer(obj) { + return ( + obj != null && + (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + ) +} + +function isFastBuffer(obj) { + return ( + !!obj.constructor && + typeof obj.constructor.isBuffer === 'function' && + obj.constructor.isBuffer(obj) + ) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer(obj) { + return ( + typeof obj.readFloatLE === 'function' && + typeof obj.slice === 'function' && + isFastBuffer(obj.slice(0, 0)) + ) +} + +function ieee754read(buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? nBytes - 1 : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << -nBits) - 1) + s >>= -nBits + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << -nBits) - 1) + e >>= -nBits + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function ieee754write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0 + var i = isLE ? 0 : nBytes - 1 + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for ( + ; + mLen >= 8; + buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8 + ) {} + + e = (e << mLen) | m + eLen += mLen + for ( + ; + eLen > 0; + buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8 + ) {} + + buffer[offset + i - d] |= s * 128 +} diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/_buffer.js b/node_modules/@esbuild-plugins/node-globals-polyfill/_buffer.js new file mode 100644 index 0000000..66103f8 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/_buffer.js @@ -0,0 +1 @@ +export { Buffer } from '_node-buffer-polyfill_.js' diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/_process.js b/node_modules/@esbuild-plugins/node-globals-polyfill/_process.js new file mode 100644 index 0000000..e9d08e8 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/_process.js @@ -0,0 +1 @@ +export { process } from '_node-process-polyfill_.js' diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts new file mode 100644 index 0000000..2f1104e --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts @@ -0,0 +1,7 @@ +import * as esbuild from 'esbuild'; +export declare function NodeGlobalsPolyfillPlugin({ buffer, process, }?: { + buffer?: boolean | undefined; + process?: boolean | undefined; +}): esbuild.Plugin; +export default NodeGlobalsPolyfillPlugin; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts.map b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts.map new file mode 100644 index 0000000..2d38864 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAElC,wBAAgB,yBAAyB,CAAC,EACtC,MAAc,EAEd,OAAc,GACjB;;;CAAK,GAAG,OAAO,CAAC,MAAM,CAyEtB;AAED,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js new file mode 100644 index 0000000..1bd8fb8 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js @@ -0,0 +1,80 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NodeGlobalsPolyfillPlugin = void 0; +const path_1 = __importDefault(require("path")); +function NodeGlobalsPolyfillPlugin({ buffer = false, +// define = {}, +process = true, } = {}) { + return { + name: 'node-globals-polyfill', + setup({ initialOptions, onResolve, onLoad }) { + onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => { + return { + path: path_1.default.resolve(__dirname, '../Buffer.js'), + }; + }); + onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => { + return { + path: path_1.default.resolve(__dirname, '../process.js'), + }; + }); + // TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 + // onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => { + // const data = fs + // .readFileSync(path.resolve(__dirname, '../process.js')) + // .toString() + // const keys = Object.keys(define) + // return { + // loader: 'js', + // contents: data.replace( + // `const defines = {}`, + // 'const defines = {\n' + + // keys + // .filter((x) => x.startsWith('process.')) + // .sort((a, b) => a.length - b.length) + // .map( + // (k) => + // ` ${JSON.stringify(k).replace( + // 'process.', + // '', + // )}: ${define[k]},`, + // ) + // .join('\n') + + // '\n}', + // ), + // } + // }) + onResolve({ filter: /_virtual-process-polyfill_\.js/ }, () => { + return { + path: path_1.default.resolve(__dirname, '../process.js'), + }; + }); + onResolve({ filter: /_virtual-buffer-polyfill_\.js/ }, () => { + return { + path: path_1.default.resolve(__dirname, '../_buffer.js'), + }; + }); + const polyfills = []; + if (process) { + polyfills.push(path_1.default.resolve(__dirname, '../_virtual-process-polyfill_.js')); + } + if (buffer) { + polyfills.push(path_1.default.resolve(__dirname, '../_virtual-buffer-polyfill_.js')); + } + if (initialOptions.inject) { + initialOptions.inject.push(...polyfills); + // handle duplicate plugin + initialOptions.inject = [...new Set(initialOptions.inject)]; + } + else { + initialOptions.inject = [...polyfills]; + } + }, + }; +} +exports.NodeGlobalsPolyfillPlugin = NodeGlobalsPolyfillPlugin; +exports.default = NodeGlobalsPolyfillPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js.map b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js.map new file mode 100644 index 0000000..8f8a451 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AAIvB,SAAgB,yBAAyB,CAAC,EACtC,MAAM,GAAG,KAAK;AACd,eAAe;AACf,OAAO,GAAG,IAAI,GACjB,GAAG,EAAE;IACF,OAAO;QACH,IAAI,EAAE,uBAAu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B,IAAI,OAAO,EAAE;gBACT,SAAS,CAAC,IAAI,CACV,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,kCAAkC,CAAC,CAC9D,CAAA;aACJ;YACD,IAAI,MAAM,EAAE;gBACR,SAAS,CAAC,IAAI,CACV,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,iCAAiC,CAAC,CAC7D,CAAA;aACJ;YACD,IAAI,cAAc,CAAC,MAAM,EAAE;gBACvB,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,CAAA;gBACxC,0BAA0B;gBAC1B,cAAc,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAA;aAC9D;iBAAM;gBACH,cAAc,CAAC,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC,CAAA;aACzC;QACL,CAAC;KACJ,CAAA;AACL,CAAC;AA7ED,8DA6EC;AAED,kBAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts new file mode 100644 index 0000000..121d59b --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.test.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts.map b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts.map new file mode 100644 index 0000000..b5774e1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js new file mode 100644 index 0000000..3f9f406 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js @@ -0,0 +1,139 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const esbuild_1 = require("esbuild"); +const test_support_1 = require("test-support"); +const _1 = require("."); +require('debug').enable(require('../package.json').name); +test('process works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `process.version`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('process is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `console.log('hei')`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }); + const output = res.outputFiles[0].text; + expect(output).not.toContain('process'); + unlink(); +})); +// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 +test('process env vars are replaced with ones from define', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `if (process.env.VAR !== 'hello') { throw new Error('process.env.VAR not right: ' + process.env.VAR) }`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + define: { + 'process.env.VAR': '"hello"', + }, + plugins: [_1.NodeGlobalsPolyfillPlugin({})], + }); + const output = res.outputFiles[0].text; + eval(output); + unlink(); +})); +test('Buffer works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `console.log(Buffer.from('xxx').toString())`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('Buffer is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `console.log('hei')`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }); + const output = res.outputFiles[0].text; + expect(output).not.toContain('Buffer'); + unlink(); +})); +test('Buffer works using plugin', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': ` + let buf = new Buffer(256); + let len = buf.write("Simply Easy Learning"); + console.log("Octets written : "+ len);`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.NodeGlobalsPolyfillPlugin({ buffer: true })], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('process works using plugin', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `console.log(process.cwd())`, + }); + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.NodeGlobalsPolyfillPlugin({ process: true })], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +//# sourceMappingURL=index.test.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js.map b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js.map new file mode 100644 index 0000000..cef0110 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/dist/index.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,qCAA+B;AAC/B,+CAAyC;AACzC,wBAA6C;AAE7C,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,CAAA;AAExD,IAAI,CAAC,eAAe,EAAE,GAAS,EAAE;IAC7B,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,yBAAU,CAAC;QACjB,UAAU,EAAE,iBAAiB;KAChC,CAAC,CAAA;IACF,MAAM,GAAG,GAAG,MAAM,eAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;KAC1C,CAAC,CAAA;IACF,MAAM,MAAM,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACtC,sBAAsB;IACtB,IAAI,CAAC,MAAM,CAAC,CAAA;IACZ,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA;AAEF,IAAI,CAAC,wBAAwB,EAAE,GAAS,EAAE;IACtC,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,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AC,CAAA,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts new file mode 100644 index 0000000..2f1104e --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts @@ -0,0 +1,7 @@ +import * as esbuild from 'esbuild'; +export declare function NodeGlobalsPolyfillPlugin({ buffer, process, }?: { + buffer?: boolean | undefined; + process?: boolean | undefined; +}): esbuild.Plugin; +export default NodeGlobalsPolyfillPlugin; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts.map b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts.map new file mode 100644 index 0000000..2d38864 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAElC,wBAAgB,yBAAyB,CAAC,EACtC,MAAc,EAEd,OAAc,GACjB;;;CAAK,GAAG,OAAO,CAAC,MAAM,CAyEtB;AAED,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js new file mode 100644 index 0000000..aa0bceb --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js @@ -0,0 +1,73 @@ +import path from 'path'; +export function NodeGlobalsPolyfillPlugin({ buffer = false, +// define = {}, +process = true, } = {}) { + return { + name: 'node-globals-polyfill', + setup({ initialOptions, onResolve, onLoad }) { + onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => { + return { + path: path.resolve(__dirname, '../Buffer.js'), + }; + }); + onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => { + return { + path: path.resolve(__dirname, '../process.js'), + }; + }); + // TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 + // onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => { + // const data = fs + // .readFileSync(path.resolve(__dirname, '../process.js')) + // .toString() + // const keys = Object.keys(define) + // return { + // loader: 'js', + // contents: data.replace( + // `const defines = {}`, + // 'const defines = {\n' + + // keys + // .filter((x) => x.startsWith('process.')) + // .sort((a, b) => a.length - b.length) + // .map( + // (k) => + // ` ${JSON.stringify(k).replace( + // 'process.', + // '', + // )}: ${define[k]},`, + // ) + // .join('\n') + + // '\n}', + // ), + // } + // }) + onResolve({ filter: /_virtual-process-polyfill_\.js/ }, () => { + return { + path: path.resolve(__dirname, '../process.js'), + }; + }); + onResolve({ filter: /_virtual-buffer-polyfill_\.js/ }, () => { + return { + path: path.resolve(__dirname, '../_buffer.js'), + }; + }); + const polyfills = []; + if (process) { + polyfills.push(path.resolve(__dirname, '../_virtual-process-polyfill_.js')); + } + if (buffer) { + polyfills.push(path.resolve(__dirname, '../_virtual-buffer-polyfill_.js')); + } + if (initialOptions.inject) { + initialOptions.inject.push(...polyfills); + // handle duplicate plugin + initialOptions.inject = [...new Set(initialOptions.inject)]; + } + else { + initialOptions.inject = [...polyfills]; + } + }, + }; +} +export default NodeGlobalsPolyfillPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js.map b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js.map new file mode 100644 index 0000000..0ebb938 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAA;AAIvB,MAAM,UAAU,yBAAyB,CAAC,EACtC,MAAM,GAAG,KAAK;AACd,eAAe;AACf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,CAAA;YACL,CAAC,CAAC,CAAA;YAEF,MAAM,SAAS,GAAa,EAAE,CAAA;YAC9B,IAAI,OAAO,EAAE;gBACT,SAAS,CAAC,IAAI,CACV,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,kCAAkC,CAAC,CAC9D,CAAA;aACJ;YACD,IAAI,MAAM,EAAE;gBACR,SAAS,CAAC,IAAI,CACV,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,iCAAiC,CAAC,CAC7D,CAAA;aACJ;YACD,IAAI,cAAc,CAAC,MAAM,EAAE;gBACvB,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,CAAA;gBACxC,0BAA0B;gBAC1B,cAAc,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAA;aAC9D;iBAAM;gBACH,cAAc,CAAC,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC,CAAA;aACzC;QACL,CAAC;KACJ,CAAA;AACL,CAAC;AAED,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts new file mode 100644 index 0000000..121d59b --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.test.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts.map b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts.map new file mode 100644 index 0000000..b5774e1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js new file mode 100644 index 0000000..c3177d5 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js @@ -0,0 +1,137 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { build } from 'esbuild'; +import { writeFiles } from 'test-support'; +import { NodeGlobalsPolyfillPlugin } from '.'; +require('debug').enable(require('../package.json').name); +test('process works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `process.version`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('process is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `console.log('hei')`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }); + const output = res.outputFiles[0].text; + expect(output).not.toContain('process'); + unlink(); +})); +// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 +test('process env vars are replaced with ones from define', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `if (process.env.VAR !== 'hello') { throw new Error('process.env.VAR not right: ' + process.env.VAR) }`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + define: { + 'process.env.VAR': '"hello"', + }, + plugins: [NodeGlobalsPolyfillPlugin({})], + }); + const output = res.outputFiles[0].text; + eval(output); + unlink(); +})); +test('Buffer works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `console.log(Buffer.from('xxx').toString())`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('Buffer is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `console.log('hei')`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }); + const output = res.outputFiles[0].text; + expect(output).not.toContain('Buffer'); + unlink(); +})); +test('Buffer works using plugin', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': ` + let buf = new Buffer(256); + let len = buf.write("Simply Easy Learning"); + console.log("Octets written : "+ len);`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeGlobalsPolyfillPlugin({ buffer: true })], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +test('process works using plugin', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `console.log(process.cwd())`, + }); + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeGlobalsPolyfillPlugin({ process: true })], + }); + const output = res.outputFiles[0].text; + // console.log(output) + eval(output); + unlink(); +})); +//# sourceMappingURL=index.test.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js.map b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js.map new file mode 100644 index 0000000..9e46b21 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/esm/index.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,yBAAyB,EAAE,MAAM,GAAG,CAAA;AAE7C,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,CAAA;AAExD,IAAI,CAAC,eAAe,EAAE,GAAS,EAAE;IAC7B,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,UAAU,CAAC;QACjB,UAAU,EAAE,iBAAiB;KAChC,CAAC,CAAA;IACF,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;KAC1C,CAAC,CAAA;IACF,MAAM,MAAM,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACtC,sBAAsB;IACtB,IAAI,CAAC,MAAM,CAAC,CAAA;IACZ,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA;AAEF,IAAI,CAAC,wBAAwB,EAAE,GAAS,EAAE;IACtC,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,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,CAAC,CAAA,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/package.json b/node_modules/@esbuild-plugins/node-globals-polyfill/package.json new file mode 100644 index 0000000..f62b1fc --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/package.json @@ -0,0 +1,34 @@ +{ + "name": "@esbuild-plugins/node-globals-polyfill", + "version": "0.2.3", + "description": "", + "preferUnplugged": true, + "sideEffects": false, + "main": "dist/index.js", + "module": "esm/index.js", + "types": "dist/index.d.ts", + "repository": "https://github.com/remorses/esbuild-plugins.git", + "scripts": { + "build": "tsc && tsc -m es6 --outDir esm", + "watch": "tsc -w" + }, + "files": [ + "dist", + "src", + "esm", + "Buffer.js", + "process.js", + "_buffer.js", + "_process.js" + ], + "keywords": [], + "author": "Tommaso De Rossi, morse ", + "license": "ISC", + "devDependencies": { + "test-support": "*" + }, + "dependencies": {}, + "peerDependencies": { + "esbuild": "*" + } +} diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/process.js b/node_modules/@esbuild-plugins/node-globals-polyfill/process.js new file mode 100644 index 0000000..cb43c28 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/process.js @@ -0,0 +1,245 @@ +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined') +} +function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined') +} +var cachedSetTimeout = defaultSetTimout +var cachedClearTimeout = defaultClearTimeout +if (typeof global.setTimeout === 'function') { + cachedSetTimeout = setTimeout +} +if (typeof global.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0) + } + // if setTimeout wasn't available but was latter defined + if ( + (cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && + setTimeout + ) { + cachedSetTimeout = setTimeout + return setTimeout(fun, 0) + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0) + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0) + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0) + } + } +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker) + } + // if clearTimeout wasn't available but was latter defined + if ( + (cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && + clearTimeout + ) { + cachedClearTimeout = clearTimeout + return clearTimeout(marker) + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker) + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker) + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker) + } + } +} +var queue = [] +var draining = false +var currentQueue +var queueIndex = -1 + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return + } + draining = false + if (currentQueue.length) { + queue = currentQueue.concat(queue) + } else { + queueIndex = -1 + } + if (queue.length) { + drainQueue() + } +} + +function drainQueue() { + if (draining) { + return + } + var timeout = runTimeout(cleanUpNextTick) + draining = true + + var len = queue.length + while (len) { + currentQueue = queue + queue = [] + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run() + } + } + queueIndex = -1 + len = queue.length + } + currentQueue = null + draining = false + runClearTimeout(timeout) +} +function nextTick(fun) { + var args = new Array(arguments.length - 1) + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i] + } + } + queue.push(new Item(fun, args)) + if (queue.length === 1 && !draining) { + runTimeout(drainQueue) + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun + this.array = array +} +Item.prototype.run = function() { + this.fun.apply(null, this.array) +} +var title = 'browser' +var platform = 'browser' +var browser = true +var env = {} +var argv = [] +var version = '' // empty string to avoid regexp issues +var versions = {} +var release = {} +var config = {} + +function noop() {} + +var on = noop +var addListener = noop +var once = noop +var off = noop +var removeListener = noop +var removeAllListeners = noop +var emit = noop + +function binding(name) { + throw new Error('process.binding is not supported') +} + +function cwd() { + return '/' +} +function chdir(dir) { + throw new Error('process.chdir is not supported') +} +function umask() { + return 0 +} + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global.performance || {} +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function() { + return new Date().getTime() + } + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp) { + var clocktime = performanceNow.call(performance) * 1e-3 + var seconds = Math.floor(clocktime) + var nanoseconds = Math.floor((clocktime % 1) * 1e9) + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0] + nanoseconds = nanoseconds - previousTimestamp[1] + if (nanoseconds < 0) { + seconds-- + nanoseconds += 1e9 + } + } + return [seconds, nanoseconds] +} + +var startTime = new Date() +function uptime() { + var currentTime = new Date() + var dif = currentTime - startTime + return dif / 1000 +} + +export var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime, +} + +// replace process.env.VAR with define + +const defines = {} +Object.keys(defines).forEach((key) => { + const segs = key.split('.') + let target = process + for (let i = 0; i < segs.length; i++) { + const seg = segs[i] + if (i === segs.length - 1) { + target[seg] = defines[key] + } else { + target = target[seg] || (target[seg] = {}) + } + } +}) diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.test.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.test.ts new file mode 100644 index 0000000..62e530e --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.test.ts @@ -0,0 +1,155 @@ +import { build } from 'esbuild' +import { writeFiles } from 'test-support' +import { NodeGlobalsPolyfillPlugin } from '.' + +require('debug').enable(require('../package.json').name) + +test('process works', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `process.version`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }) + const output = res.outputFiles[0].text + // console.log(output) + eval(output) + unlink() +}) + +test('process is tree shaken', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `console.log('hei')`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../process')], + }) + const output = res.outputFiles[0].text + expect(output).not.toContain('process') + unlink() +}) + +// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 +test('process env vars are replaced with ones from define', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `if (process.env.VAR !== 'hello') { throw new Error('process.env.VAR not right: ' + process.env.VAR) }`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + define: { + 'process.env.VAR': '"hello"', + }, + plugins: [NodeGlobalsPolyfillPlugin({})], + }) + const output = res.outputFiles[0].text + eval(output) + unlink() +}) + +test('Buffer works', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `console.log(Buffer.from('xxx').toString())`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }) + const output = res.outputFiles[0].text + // console.log(output) + eval(output) + unlink() +}) + +test('Buffer is tree shaken', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `console.log('hei')`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + inject: [require.resolve('../Buffer')], + }) + const output = res.outputFiles[0].text + expect(output).not.toContain('Buffer') + unlink() +}) + +test('Buffer works using plugin', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': ` + let buf = new Buffer(256); + let len = buf.write("Simply Easy Learning"); + console.log("Octets written : "+ len);`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeGlobalsPolyfillPlugin({ buffer: true })], + }) + const output = res.outputFiles[0].text + // console.log(output) + eval(output) + unlink() +}) +test('process works using plugin', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `console.log(process.cwd())`, + }) + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeGlobalsPolyfillPlugin({ process: true })], + }) + const output = res.outputFiles[0].text + // console.log(output) + eval(output) + unlink() +}) diff --git a/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.ts b/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.ts new file mode 100644 index 0000000..4b06c37 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-globals-polyfill/src/index.ts @@ -0,0 +1,84 @@ +import path from 'path' +import fs from 'fs' +import * as esbuild from 'esbuild' + +export function NodeGlobalsPolyfillPlugin({ + buffer = false, + // define = {}, + process = true, +} = {}): esbuild.Plugin { + return { + name: 'node-globals-polyfill', + setup({ initialOptions, onResolve, onLoad }) { + onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => { + return { + path: path.resolve(__dirname, '../Buffer.js'), + } + }) + onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => { + return { + path: path.resolve(__dirname, '../process.js'), + } + }) + + // TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762 + // onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => { + // const data = fs + // .readFileSync(path.resolve(__dirname, '../process.js')) + // .toString() + + // const keys = Object.keys(define) + // return { + // loader: 'js', + // contents: data.replace( + // `const defines = {}`, + // 'const defines = {\n' + + // keys + // .filter((x) => x.startsWith('process.')) + // .sort((a, b) => a.length - b.length) + // .map( + // (k) => + // ` ${JSON.stringify(k).replace( + // 'process.', + // '', + // )}: ${define[k]},`, + // ) + // .join('\n') + + // '\n}', + // ), + // } + // }) + onResolve({ filter: /_virtual-process-polyfill_\.js/ }, () => { + return { + path: path.resolve(__dirname, '../process.js'), + } + }) + onResolve({ filter: /_virtual-buffer-polyfill_\.js/ }, () => { + return { + path: path.resolve(__dirname, '../_buffer.js'), + } + }) + + const polyfills: string[] = [] + if (process) { + polyfills.push( + path.resolve(__dirname, '../_virtual-process-polyfill_.js'), + ) + } + if (buffer) { + polyfills.push( + path.resolve(__dirname, '../_virtual-buffer-polyfill_.js'), + ) + } + if (initialOptions.inject) { + initialOptions.inject.push(...polyfills) + // handle duplicate plugin + initialOptions.inject = [...new Set(initialOptions.inject)] + } else { + initialOptions.inject = [...polyfills] + } + }, + } +} + +export default NodeGlobalsPolyfillPlugin diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts new file mode 100644 index 0000000..65d4193 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts @@ -0,0 +1,8 @@ +import { Plugin } from 'esbuild'; +export interface NodePolyfillsOptions { + name?: string; + namespace?: string; +} +export declare function NodeModulesPolyfillPlugin(options?: NodePolyfillsOptions): Plugin; +export default NodeModulesPolyfillPlugin; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts.map new file mode 100644 index 0000000..c1151f9 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,MAAM,EAAE,MAAM,SAAS,CAAA;AAkB/C,MAAM,WAAW,oBAAoB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,wBAAgB,yBAAyB,CACrC,OAAO,GAAE,oBAAyB,GACnC,MAAM,CAwFR;AAmBD,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js new file mode 100644 index 0000000..51f4d1a --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js @@ -0,0 +1,127 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NodeModulesPolyfillPlugin = void 0; +const escape_string_regexp_1 = __importDefault(require("escape-string-regexp")); +const fs_1 = __importDefault(require("fs")); +const path_1 = __importDefault(require("path")); +const polyfills_1 = require("./polyfills"); +// import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve' +const NAME = 'node-modules-polyfills'; +const NAMESPACE = NAME; +function removeEndingSlash(importee) { + if (importee && importee.slice(-1) === '/') { + importee = importee.slice(0, -1); + } + return importee; +} +function NodeModulesPolyfillPlugin(options = {}) { + const { namespace = NAMESPACE, name = NAME } = options; + if (namespace.endsWith('commonjs')) { + throw new Error(`namespace ${namespace} must not end with commonjs`); + } + // this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default + const commonjsNamespace = namespace + '-commonjs'; + const polyfilledBuiltins = polyfills_1.builtinsPolyfills(); + const polyfilledBuiltinsNames = [...polyfilledBuiltins.keys()]; + return { + name, + setup: function setup({ onLoad, onResolve, initialOptions }) { + var _a; + // polyfills contain global keyword, it must be defined + if ((initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define) && !((_a = initialOptions.define) === null || _a === void 0 ? void 0 : _a.global)) { + initialOptions.define['global'] = 'globalThis'; + } + else if (!(initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define)) { + initialOptions.define = { global: 'globalThis' }; + } + // TODO these polyfill module cannot import anything, is that ok? + function loader(args) { + return __awaiter(this, void 0, void 0, function* () { + try { + const argsPath = args.path.replace(/^node:/, ''); + const isCommonjs = args.namespace.endsWith('commonjs'); + const resolved = polyfilledBuiltins.get(removeEndingSlash(argsPath)); + const contents = yield (yield fs_1.default.promises.readFile(resolved)).toString(); + let resolveDir = path_1.default.dirname(resolved); + if (isCommonjs) { + return { + loader: 'js', + contents: commonJsTemplate({ + importPath: argsPath, + }), + resolveDir, + }; + } + return { + loader: 'js', + contents, + resolveDir, + }; + } + catch (e) { + console.error('node-modules-polyfill', e); + return { + contents: `export {}`, + loader: 'js', + }; + } + }); + } + onLoad({ filter: /.*/, namespace }, loader); + onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader); + const filter = new RegExp([ + ...polyfilledBuiltinsNames, + ...polyfilledBuiltinsNames.map((n) => `node:${n}`), + ] + .map(escape_string_regexp_1.default) + .join('|')); + function resolver(args) { + return __awaiter(this, void 0, void 0, function* () { + const argsPath = args.path.replace(/^node:/, ''); + const ignoreRequire = args.namespace === commonjsNamespace; + if (!polyfilledBuiltins.has(argsPath)) { + return; + } + const isCommonjs = !ignoreRequire && args.kind === 'require-call'; + return { + namespace: isCommonjs ? commonjsNamespace : namespace, + path: argsPath, + }; + }); + } + onResolve({ filter }, resolver); + // onResolve({ filter: /.*/, namespace }, resolver) + }, + }; +} +exports.NodeModulesPolyfillPlugin = NodeModulesPolyfillPlugin; +function commonJsTemplate({ importPath }) { + return ` +const polyfill = require('${importPath}') + +if (polyfill && polyfill.default) { + module.exports = polyfill.default + for (let k in polyfill) { + module.exports[k] = polyfill[k] + } +} else if (polyfill) { + module.exports = polyfill +} + + +`; +} +exports.default = NodeModulesPolyfillPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js.map new file mode 100644 index 0000000..c4bf9e4 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,gFAAqD;AACrD,4CAAmB;AACnB,gDAAuB;AAEvB,2CAA+C;AAE/C,oEAAoE;AACpE,MAAM,IAAI,GAAG,wBAAwB,CAAA;AACrC,MAAM,SAAS,GAAG,IAAI,CAAA;AAEtB,SAAS,iBAAiB,CAAC,QAAQ;IAC/B,IAAI,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;QACxC,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;KACnC;IACD,OAAO,QAAQ,CAAA;AACnB,CAAC;AAOD,SAAgB,yBAAyB,CACrC,UAAgC,EAAE;IAElC,MAAM,EAAE,SAAS,GAAG,SAAS,EAAE,IAAI,GAAG,I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MAAM,UAAU,GACZ,CAAC,aAAa,IAAI,IAAI,CAAC,IAAI,KAAK,cAAc,CAAA;oBAElD,OAAO;wBACH,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,SAAS;wBACrD,IAAI,EAAE,QAAQ;qBACjB,CAAA;gBACL,CAAC;aAAA;YACD,SAAS,CAAC,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC/B,mDAAmD;QACvD,CAAC;KACJ,CAAA;AACL,CAAC;AA1FD,8DA0FC;AAED,SAAS,gBAAgB,CAAC,EAAE,UAAU,EAAE;IACpC,OAAO;4BACiB,UAAU;;;;;;;;;;;;CAYrC,CAAA;AACD,CAAC;AAED,kBAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts new file mode 100644 index 0000000..121d59b --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.test.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts.map new file mode 100644 index 0000000..b5774e1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js new file mode 100644 index 0000000..2923eec --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js @@ -0,0 +1,183 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const esbuild_1 = require("esbuild"); +const test_support_1 = require("test-support"); +const fs_1 = __importDefault(require("fs")); +const _1 = __importDefault(require(".")); +const node_globals_polyfill_1 = __importDefault(require("@esbuild-plugins/node-globals-polyfill")); +require('debug').enable(require('../package.json').name); +test('works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('works with SafeBuffer and other package consumers', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import {Buffer as SafeBuffer} from './safe-buffer'; console.log(SafeBuffer);`, + 'safe-buffer.ts': fs_1.default + .readFileSync(require.resolve('safe-buffer')) + .toString(), + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + // console.log( + // res.outputFiles[0].text + // .split('\n') + // .map((x, i) => i + ' ' + x) + // .join('\n'), + // ) + eval(res.outputFiles[0].text); + unlink(); +})); +test('events works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': ` + import EventEmitter from 'events'; + + class Test extends EventEmitter { + constructor() { }; + } + console.log(Test) + `, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text); + unlink(); +})); +test('require can use default export', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': ` + const assert = require('assert') + // console.log(assert) + assert('ok') + `, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text); + unlink(); +})); +test.skip('crypto', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import { randomBytes } from 'crypto'; console.log(randomBytes(20).toString('hex'))`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test.skip('fs', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import { readFile } from 'fs'; console.log(readFile(''))`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('does not include global keyword', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default()], + }); + const text = res.outputFiles[0].text; + eval(text); + expect(text).not.toContain(/\bglobal\b/); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('works with globals polyfills', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield esbuild_1.build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [_1.default(), node_globals_polyfill_1.default()], + }); + const text = res.outputFiles[0].text; + eval(text); + console.log(text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +//# sourceMappingURL=index.test.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js.map new file mode 100644 index 0000000..e8a76e6 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/index.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,qCAA+B;AAC/B,+CAAyC;AACzC,4CAAmB;AACnB,yCAA0C;AAC1C,mGAA+E;AAE/E,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,C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,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACpC,IAAI,CAAC,IAAI,CAAC,CAAA;IACV,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;IACjB,uCAAuC;IACvC,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts new file mode 100644 index 0000000..564adc1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts @@ -0,0 +1,2 @@ +export declare function builtinsPolyfills(): Map; +//# sourceMappingURL=polyfills.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts.map new file mode 100644 index 0000000..2f7b592 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":"AAQA,wBAAgB,iBAAiB,kBA8IhC"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js new file mode 100644 index 0000000..4f4f953 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js @@ -0,0 +1,61 @@ +"use strict"; +// Taken from https://github.com/ionic-team/rollup-plugin-node-polyfills/blob/master/src/modules.ts +Object.defineProperty(exports, "__esModule", { value: true }); +exports.builtinsPolyfills = void 0; +const EMPTY_PATH = require.resolve('rollup-plugin-node-polyfills/polyfills/empty.js'); +function builtinsPolyfills() { + const libs = new Map(); + libs.set('process', require.resolve('rollup-plugin-node-polyfills/polyfills/process-es6')); + libs.set('buffer', require.resolve('rollup-plugin-node-polyfills/polyfills/buffer-es6')); + libs.set('util', require.resolve('rollup-plugin-node-polyfills/polyfills/util')); + libs.set('sys', libs.get('util')); + libs.set('events', require.resolve('rollup-plugin-node-polyfills/polyfills/events')); + libs.set('stream', require.resolve('rollup-plugin-node-polyfills/polyfills/stream')); + libs.set('path', require.resolve('rollup-plugin-node-polyfills/polyfills/path')); + libs.set('querystring', require.resolve('rollup-plugin-node-polyfills/polyfills/qs')); + libs.set('punycode', require.resolve('rollup-plugin-node-polyfills/polyfills/punycode')); + libs.set('url', require.resolve('rollup-plugin-node-polyfills/polyfills/url')); + libs.set('string_decoder', require.resolve('rollup-plugin-node-polyfills/polyfills/string-decoder')); + libs.set('http', require.resolve('rollup-plugin-node-polyfills/polyfills/http')); + libs.set('https', require.resolve('rollup-plugin-node-polyfills/polyfills/http')); + libs.set('os', require.resolve('rollup-plugin-node-polyfills/polyfills/os')); + libs.set('assert', require.resolve('rollup-plugin-node-polyfills/polyfills/assert')); + libs.set('constants', require.resolve('rollup-plugin-node-polyfills/polyfills/constants')); + libs.set('_stream_duplex', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/duplex')); + libs.set('_stream_passthrough', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough')); + libs.set('_stream_readable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/readable')); + libs.set('_stream_writable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/writable')); + libs.set('_stream_transform', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/transform')); + libs.set('timers', require.resolve('rollup-plugin-node-polyfills/polyfills/timers')); + libs.set('console', require.resolve('rollup-plugin-node-polyfills/polyfills/console')); + libs.set('vm', require.resolve('rollup-plugin-node-polyfills/polyfills/vm')); + libs.set('zlib', require.resolve('rollup-plugin-node-polyfills/polyfills/zlib')); + libs.set('tty', require.resolve('rollup-plugin-node-polyfills/polyfills/tty')); + libs.set('domain', require.resolve('rollup-plugin-node-polyfills/polyfills/domain')); + // not shimmed + libs.set('dns', EMPTY_PATH); + libs.set('dgram', EMPTY_PATH); + libs.set('child_process', EMPTY_PATH); + libs.set('cluster', EMPTY_PATH); + libs.set('module', EMPTY_PATH); + libs.set('net', EMPTY_PATH); + libs.set('readline', EMPTY_PATH); + libs.set('repl', EMPTY_PATH); + libs.set('tls', EMPTY_PATH); + libs.set('fs', EMPTY_PATH); + libs.set('crypto', EMPTY_PATH); + // libs.set( + // 'fs', + // require.resolve('rollup-plugin-node-polyfills/polyfills/browserify-fs'), + // ) + // TODO enable crypto and fs https://github.com/ionic-team/rollup-plugin-node-polyfills/issues/20 + // libs.set( + // 'crypto', + // require.resolve( + // 'rollup-plugin-node-polyfills/polyfills/crypto-browserify', + // ), + // ) + return libs; +} +exports.builtinsPolyfills = builtinsPolyfills; +//# sourceMappingURL=polyfills.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js.map new file mode 100644 index 0000000..a7ef0e3 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/dist/polyfills.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":";AAAA,mGAAmG;;;AAInG,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAC9B,iDAAiD,CACpD,CAAA;AAED,SAAgB,iBAAiB;IAC7B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAE,CAAA;IAEtB,IAAI,CAAC,GAAG,CACJ,SAAS,EACT,OAAO,CAAC,OAAO,CAAC,oDAAoD,CAAC,CACxE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,QAAQ,EACR,OAAO,CAAC,OAAO,CAAC,mDAAmD,CAAC,CACvE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,MAAM,EACN,OAAO,CAAC,OAAO,CAAC,6CAA6C,CAAC,CACjE,CAAA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AAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAC9B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,UAAU,CAAC,CAAA;IAChC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;IAC5B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAA;IAC1B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAE9B,YAAY;IACZ,YAAY;IACZ,+EAA+E;IAC/E,IAAI;IAEJ,iGAAiG;IACjG,YAAY;IACZ,gBAAgB;IAChB,uBAAuB;IACvB,sEAAsE;IACtE,SAAS;IACT,IAAI;IAEJ,OAAO,IAAI,CAAA;AACf,CAAC;AA9ID,8CA8IC"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts new file mode 100644 index 0000000..65d4193 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts @@ -0,0 +1,8 @@ +import { Plugin } from 'esbuild'; +export interface NodePolyfillsOptions { + name?: string; + namespace?: string; +} +export declare function NodeModulesPolyfillPlugin(options?: NodePolyfillsOptions): Plugin; +export default NodeModulesPolyfillPlugin; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts.map new file mode 100644 index 0000000..c1151f9 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,MAAM,EAAE,MAAM,SAAS,CAAA;AAkB/C,MAAM,WAAW,oBAAoB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,wBAAgB,yBAAyB,CACrC,OAAO,GAAE,oBAAyB,GACnC,MAAM,CAwFR;AAmBD,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js new file mode 100644 index 0000000..69526b5 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js @@ -0,0 +1,120 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import escapeStringRegexp from 'escape-string-regexp'; +import fs from 'fs'; +import path from 'path'; +import { builtinsPolyfills } from './polyfills'; +// import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve' +const NAME = 'node-modules-polyfills'; +const NAMESPACE = NAME; +function removeEndingSlash(importee) { + if (importee && importee.slice(-1) === '/') { + importee = importee.slice(0, -1); + } + return importee; +} +export function NodeModulesPolyfillPlugin(options = {}) { + const { namespace = NAMESPACE, name = NAME } = options; + if (namespace.endsWith('commonjs')) { + throw new Error(`namespace ${namespace} must not end with commonjs`); + } + // this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default + const commonjsNamespace = namespace + '-commonjs'; + const polyfilledBuiltins = builtinsPolyfills(); + const polyfilledBuiltinsNames = [...polyfilledBuiltins.keys()]; + return { + name, + setup: function setup({ onLoad, onResolve, initialOptions }) { + var _a; + // polyfills contain global keyword, it must be defined + if ((initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define) && !((_a = initialOptions.define) === null || _a === void 0 ? void 0 : _a.global)) { + initialOptions.define['global'] = 'globalThis'; + } + else if (!(initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define)) { + initialOptions.define = { global: 'globalThis' }; + } + // TODO these polyfill module cannot import anything, is that ok? + function loader(args) { + return __awaiter(this, void 0, void 0, function* () { + try { + const argsPath = args.path.replace(/^node:/, ''); + const isCommonjs = args.namespace.endsWith('commonjs'); + const resolved = polyfilledBuiltins.get(removeEndingSlash(argsPath)); + const contents = yield (yield fs.promises.readFile(resolved)).toString(); + let resolveDir = path.dirname(resolved); + if (isCommonjs) { + return { + loader: 'js', + contents: commonJsTemplate({ + importPath: argsPath, + }), + resolveDir, + }; + } + return { + loader: 'js', + contents, + resolveDir, + }; + } + catch (e) { + console.error('node-modules-polyfill', e); + return { + contents: `export {}`, + loader: 'js', + }; + } + }); + } + onLoad({ filter: /.*/, namespace }, loader); + onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader); + const filter = new RegExp([ + ...polyfilledBuiltinsNames, + ...polyfilledBuiltinsNames.map((n) => `node:${n}`), + ] + .map(escapeStringRegexp) + .join('|')); + function resolver(args) { + return __awaiter(this, void 0, void 0, function* () { + const argsPath = args.path.replace(/^node:/, ''); + const ignoreRequire = args.namespace === commonjsNamespace; + if (!polyfilledBuiltins.has(argsPath)) { + return; + } + const isCommonjs = !ignoreRequire && args.kind === 'require-call'; + return { + namespace: isCommonjs ? commonjsNamespace : namespace, + path: argsPath, + }; + }); + } + onResolve({ filter }, resolver); + // onResolve({ filter: /.*/, namespace }, resolver) + }, + }; +} +function commonJsTemplate({ importPath }) { + return ` +const polyfill = require('${importPath}') + +if (polyfill && polyfill.default) { + module.exports = polyfill.default + for (let k in polyfill) { + module.exports[k] = polyfill[k] + } +} else if (polyfill) { + module.exports = polyfill +} + + +`; +} +export default NodeModulesPolyfillPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js.map new file mode 100644 index 0000000..c8544ab --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,kBAAkB,MAAM,sBAAsB,CAAA;AACrD,OAAO,EAAE,MAAM,IAAI,CAAA;AACnB,OAAO,IAAI,MAAM,MAAM,CAAA;AAEvB,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAE/C,oEAAoE;AACpE,MAAM,IAAI,GAAG,wBAAwB,CAAA;AACrC,MAAM,SAAS,GAAG,IAAI,CAAA;AAEtB,SAAS,iBAAiB,CAAC,QAAQ;IAC/B,IAAI,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;QACxC,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;KACnC;IACD,OAAO,QAAQ,CAAA;AACnB,CAAC;AAOD,MAAM,UAAU,yBAAyB,CACrC,UAAgC,EAAE;IAElC,MAAM,EAAE,SAAS,GAAG,SAAS,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,OAAO,CAAA;IACtD,IAAI,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;QAChC,MAAM,IAAI,KAAK,CAAC,aAAa,SAAS,6BAA6B,CAAC,CAAA;KACvE;IACD,+IAA+I;IAC/I,MAAM,iBAAiB,GAAG,SAAS,GAAG,WAAW,CAAA;IACjD,MAAM,kBAAkB,GAAG,iBAAiB,EAAE,CAAA;IAC9C,MAAM,uBAAuB,GAAG,CAAC,GAA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AC;KACJ,CAAA;AACL,CAAC;AAED,SAAS,gBAAgB,CAAC,EAAE,UAAU,EAAE;IACpC,OAAO;4BACiB,UAAU;;;;;;;;;;;;CAYrC,CAAA;AACD,CAAC;AAED,eAAe,yBAAyB,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts new file mode 100644 index 0000000..121d59b --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.test.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts.map new file mode 100644 index 0000000..b5774e1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js new file mode 100644 index 0000000..b4ff899 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js @@ -0,0 +1,178 @@ +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +import { build } from 'esbuild'; +import { writeFiles } from 'test-support'; +import fs from 'fs'; +import NodeModulesPolyfillsPlugin from '.'; +import NodeGlobalsPolyfillsPlugin from '@esbuild-plugins/node-globals-polyfill'; +require('debug').enable(require('../package.json').name); +test('works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('works with SafeBuffer and other package consumers', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import {Buffer as SafeBuffer} from './safe-buffer'; console.log(SafeBuffer);`, + 'safe-buffer.ts': fs + .readFileSync(require.resolve('safe-buffer')) + .toString(), + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + // console.log( + // res.outputFiles[0].text + // .split('\n') + // .map((x, i) => i + ' ' + x) + // .join('\n'), + // ) + eval(res.outputFiles[0].text); + unlink(); +})); +test('events works', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': ` + import EventEmitter from 'events'; + + class Test extends EventEmitter { + constructor() { }; + } + console.log(Test) + `, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text); + unlink(); +})); +test('require can use default export', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': ` + const assert = require('assert') + // console.log(assert) + assert('ok') + `, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text); + unlink(); +})); +test.skip('crypto', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import { randomBytes } from 'crypto'; console.log(randomBytes(20).toString('hex'))`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test.skip('fs', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import { readFile } from 'fs'; console.log(readFile(''))`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + eval(res.outputFiles[0].text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('does not include global keyword', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }); + const text = res.outputFiles[0].text; + eval(text); + expect(text).not.toContain(/\bglobal\b/); + // console.log(res.outputFiles[0].text) + unlink(); +})); +test('works with globals polyfills', () => __awaiter(void 0, void 0, void 0, function* () { + const { unlink, paths: [ENTRY], } = yield writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }); + // const outfile = randomOutputFile() + const res = yield build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin(), NodeGlobalsPolyfillsPlugin()], + }); + const text = res.outputFiles[0].text; + eval(text); + console.log(text); + // console.log(res.outputFiles[0].text) + unlink(); +})); +//# sourceMappingURL=index.test.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js.map new file mode 100644 index 0000000..9e80cfd --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/index.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,MAAM,IAAI,CAAA;AACnB,OAAO,0BAA0B,MAAM,GAAG,CAAA;AAC1C,OAAO,0BAA0B,MAAM,wCAAwC,CAAA;AAE/E,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,CAAA;AAExD,IAAI,CAAC,OAAO,EAAE,GAAS,EAAE;IACrB,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,UAAU,CAAC;QACjB,UAAU,EAAE,4CAA4C;QACxD,UAAU,EAAE,uHAAuH;KACtI,CAAC,CAAA;IACF,qCAAqC;IACrC,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAA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AK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,CAAC,0BAA0B,EAAE,CAAC;KAC1C,CAAC,CAAA;IACF,MAAM,IAAI,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACpC,IAAI,CAAC,IAAI,CAAC,CAAA;IACV,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,YAAY,CAAC,CAAA;IACxC,uCAAuC;IACvC,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA;AAEF,IAAI,CAAC,8BAA8B,EAAE,GAAS,EAAE;IAC5C,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,UAAU,CAAC;QACjB,UAAU,EAAE,4CAA4C;QACxD,UAAU,EAAE,uHAAuH;KACtI,CAAC,CAAA;IACF,qCAAqC;IACrC,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,CAAC,0BAA0B,EAAE,EAAE,0BAA0B,EAAE,CAAC;KACxE,CAAC,CAAA;IACF,MAAM,IAAI,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACpC,IAAI,CAAC,IAAI,CAAC,CAAA;IACV,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;IACjB,uCAAuC;IACvC,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts new file mode 100644 index 0000000..564adc1 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts @@ -0,0 +1,2 @@ +export declare function builtinsPolyfills(): Map; +//# sourceMappingURL=polyfills.d.ts.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts.map new file mode 100644 index 0000000..2f7b592 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":"AAQA,wBAAgB,iBAAiB,kBA8IhC"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js new file mode 100644 index 0000000..28b0ea7 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js @@ -0,0 +1,57 @@ +// Taken from https://github.com/ionic-team/rollup-plugin-node-polyfills/blob/master/src/modules.ts +const EMPTY_PATH = require.resolve('rollup-plugin-node-polyfills/polyfills/empty.js'); +export function builtinsPolyfills() { + const libs = new Map(); + libs.set('process', require.resolve('rollup-plugin-node-polyfills/polyfills/process-es6')); + libs.set('buffer', require.resolve('rollup-plugin-node-polyfills/polyfills/buffer-es6')); + libs.set('util', require.resolve('rollup-plugin-node-polyfills/polyfills/util')); + libs.set('sys', libs.get('util')); + libs.set('events', require.resolve('rollup-plugin-node-polyfills/polyfills/events')); + libs.set('stream', require.resolve('rollup-plugin-node-polyfills/polyfills/stream')); + libs.set('path', require.resolve('rollup-plugin-node-polyfills/polyfills/path')); + libs.set('querystring', require.resolve('rollup-plugin-node-polyfills/polyfills/qs')); + libs.set('punycode', require.resolve('rollup-plugin-node-polyfills/polyfills/punycode')); + libs.set('url', require.resolve('rollup-plugin-node-polyfills/polyfills/url')); + libs.set('string_decoder', require.resolve('rollup-plugin-node-polyfills/polyfills/string-decoder')); + libs.set('http', require.resolve('rollup-plugin-node-polyfills/polyfills/http')); + libs.set('https', require.resolve('rollup-plugin-node-polyfills/polyfills/http')); + libs.set('os', require.resolve('rollup-plugin-node-polyfills/polyfills/os')); + libs.set('assert', require.resolve('rollup-plugin-node-polyfills/polyfills/assert')); + libs.set('constants', require.resolve('rollup-plugin-node-polyfills/polyfills/constants')); + libs.set('_stream_duplex', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/duplex')); + libs.set('_stream_passthrough', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough')); + libs.set('_stream_readable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/readable')); + libs.set('_stream_writable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/writable')); + libs.set('_stream_transform', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/transform')); + libs.set('timers', require.resolve('rollup-plugin-node-polyfills/polyfills/timers')); + libs.set('console', require.resolve('rollup-plugin-node-polyfills/polyfills/console')); + libs.set('vm', require.resolve('rollup-plugin-node-polyfills/polyfills/vm')); + libs.set('zlib', require.resolve('rollup-plugin-node-polyfills/polyfills/zlib')); + libs.set('tty', require.resolve('rollup-plugin-node-polyfills/polyfills/tty')); + libs.set('domain', require.resolve('rollup-plugin-node-polyfills/polyfills/domain')); + // not shimmed + libs.set('dns', EMPTY_PATH); + libs.set('dgram', EMPTY_PATH); + libs.set('child_process', EMPTY_PATH); + libs.set('cluster', EMPTY_PATH); + libs.set('module', EMPTY_PATH); + libs.set('net', EMPTY_PATH); + libs.set('readline', EMPTY_PATH); + libs.set('repl', EMPTY_PATH); + libs.set('tls', EMPTY_PATH); + libs.set('fs', EMPTY_PATH); + libs.set('crypto', EMPTY_PATH); + // libs.set( + // 'fs', + // require.resolve('rollup-plugin-node-polyfills/polyfills/browserify-fs'), + // ) + // TODO enable crypto and fs https://github.com/ionic-team/rollup-plugin-node-polyfills/issues/20 + // libs.set( + // 'crypto', + // require.resolve( + // 'rollup-plugin-node-polyfills/polyfills/crypto-browserify', + // ), + // ) + return libs; +} +//# sourceMappingURL=polyfills.js.map \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js.map b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js.map new file mode 100644 index 0000000..3c35ae4 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/esm/polyfills.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":"AAAA,mGAAmG;AAInG,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAC9B,iDAAiD,CACpD,CAAA;AAED,MAAM,UAAU,iBAAiB;IAC7B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAE,CAAA;IAEtB,IAAI,CAAC,GAAG,CACJ,SAAS,EACT,OAAO,CAAC,OAAO,CAAC,oDAAoD,CAAC,CACxE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,QAAQ,EACR,OAAO,CAAC,OAAO,CAAC,mDAAmD,CAAC,CACvE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,MAAM,EACN,OAAO,CAAC,OAAO,CAAC,6CAA6C,CAAC,CACjE,CAAA;IACD,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAA;IACjC,IAAI,CAAC,GAAG,CACJ,QAAQ,EACR,OAAO,CAAC,OAAO,CAAC,+CAA+C,CAAC,CACnE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,QAAQ,EACR,OAAO,CAAC,OAAO,CAAC,+CAA+C,CAAC,CACnE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,MAAM,EACN,OAAO,CAAC,OAAO,CAAC,6CAA6C,CAAC,CACjE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ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EAAE,UAAU,CAAC,CAAA;IAE9B,YAAY;IACZ,YAAY;IACZ,+EAA+E;IAC/E,IAAI;IAEJ,iGAAiG;IACjG,YAAY;IACZ,gBAAgB;IAChB,uBAAuB;IACvB,sEAAsE;IACtE,SAAS;IACT,IAAI;IAEJ,OAAO,IAAI,CAAA;AACf,CAAC"} \ No newline at end of file diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/package.json b/node_modules/@esbuild-plugins/node-modules-polyfill/package.json new file mode 100644 index 0000000..d9a6e41 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/package.json @@ -0,0 +1,33 @@ +{ + "name": "@esbuild-plugins/node-modules-polyfill", + "version": "0.2.2", + "description": "", + "main": "dist/index.js", + "module": "esm/index.js", + "types": "dist/index.d.ts", + "repository": "https://github.com/remorses/esbuild-plugins.git", + "scripts": { + "build": "tsc && tsc -m es6 --outDir esm", + "watch": "tsc -w" + }, + "files": [ + "dist", + "src", + "esm" + ], + "keywords": [], + "author": "Tommaso De Rossi, morse ", + "license": "ISC", + "devDependencies": { + "safe-buffer": "^5.2.1", + "test-support": "*", + "@esbuild-plugins/node-globals-polyfill": "*" + }, + "dependencies": { + "escape-string-regexp": "^4.0.0", + "rollup-plugin-node-polyfills": "^0.2.1" + }, + "peerDependencies": { + "esbuild": "*" + } +} diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.test.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.test.ts new file mode 100644 index 0000000..92792e6 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.test.ts @@ -0,0 +1,200 @@ +import { build } from 'esbuild' +import { writeFiles } from 'test-support' +import fs from 'fs' +import NodeModulesPolyfillsPlugin from '.' +import NodeGlobalsPolyfillsPlugin from '@esbuild-plugins/node-globals-polyfill' + +require('debug').enable(require('../package.json').name) + +test('works', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + eval(res.outputFiles[0].text) + // console.log(res.outputFiles[0].text) + unlink() +}) + +test('works with SafeBuffer and other package consumers', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import {Buffer as SafeBuffer} from './safe-buffer'; console.log(SafeBuffer);`, + 'safe-buffer.ts': fs + .readFileSync(require.resolve('safe-buffer')) + .toString(), + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + // console.log( + // res.outputFiles[0].text + // .split('\n') + // .map((x, i) => i + ' ' + x) + // .join('\n'), + // ) + eval(res.outputFiles[0].text) + unlink() +}) + +test('events works', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': ` + import EventEmitter from 'events'; + + class Test extends EventEmitter { + constructor() { }; + } + console.log(Test) + `, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text) + unlink() +}) + +test('require can use default export', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': ` + const assert = require('assert') + // console.log(assert) + assert('ok') + `, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + // console.log(res.outputFiles[0].text) + eval(res.outputFiles[0].text) + unlink() +}) + +test.skip('crypto', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import { randomBytes } from 'crypto'; console.log(randomBytes(20).toString('hex'))`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + eval(res.outputFiles[0].text) + // console.log(res.outputFiles[0].text) + unlink() +}) +test.skip('fs', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import { readFile } from 'fs'; console.log(readFile(''))`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + eval(res.outputFiles[0].text) + // console.log(res.outputFiles[0].text) + unlink() +}) + +test('does not include global keyword', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin()], + }) + const text = res.outputFiles[0].text + eval(text) + expect(text).not.toContain(/\bglobal\b/) + // console.log(res.outputFiles[0].text) + unlink() +}) + +test('works with globals polyfills', async () => { + const { + unlink, + paths: [ENTRY], + } = await writeFiles({ + 'entry.ts': `import {x} from './utils'; console.log(x);`, + 'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`, + }) + // const outfile = randomOutputFile() + const res = await build({ + entryPoints: [ENTRY], + write: false, + format: 'esm', + target: 'es2017', + bundle: true, + plugins: [NodeModulesPolyfillsPlugin(), NodeGlobalsPolyfillsPlugin()], + }) + const text = res.outputFiles[0].text + eval(text) + console.log(text) + // console.log(res.outputFiles[0].text) + unlink() +}) diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.ts new file mode 100644 index 0000000..f7397e4 --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/src/index.ts @@ -0,0 +1,133 @@ +import { OnResolveArgs, Plugin } from 'esbuild' +import escapeStringRegexp from 'escape-string-regexp' +import fs from 'fs' +import path from 'path' +import esbuild from 'esbuild' +import { builtinsPolyfills } from './polyfills' + +// import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve' +const NAME = 'node-modules-polyfills' +const NAMESPACE = NAME + +function removeEndingSlash(importee) { + if (importee && importee.slice(-1) === '/') { + importee = importee.slice(0, -1) + } + return importee +} + +export interface NodePolyfillsOptions { + name?: string + namespace?: string +} + +export function NodeModulesPolyfillPlugin( + options: NodePolyfillsOptions = {}, +): Plugin { + const { namespace = NAMESPACE, name = NAME } = options + if (namespace.endsWith('commonjs')) { + throw new Error(`namespace ${namespace} must not end with commonjs`) + } + // this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default + const commonjsNamespace = namespace + '-commonjs' + const polyfilledBuiltins = builtinsPolyfills() + const polyfilledBuiltinsNames = [...polyfilledBuiltins.keys()] + + return { + name, + setup: function setup({ onLoad, onResolve, initialOptions }) { + // polyfills contain global keyword, it must be defined + if (initialOptions?.define && !initialOptions.define?.global) { + initialOptions.define['global'] = 'globalThis' + } else if (!initialOptions?.define) { + initialOptions.define = { global: 'globalThis' } + } + + // TODO these polyfill module cannot import anything, is that ok? + async function loader( + args: esbuild.OnLoadArgs, + ): Promise { + try { + const argsPath = args.path.replace(/^node:/, '') + const isCommonjs = args.namespace.endsWith('commonjs') + + const resolved = polyfilledBuiltins.get( + removeEndingSlash(argsPath), + ) + const contents = await ( + await fs.promises.readFile(resolved) + ).toString() + let resolveDir = path.dirname(resolved) + + if (isCommonjs) { + return { + loader: 'js', + contents: commonJsTemplate({ + importPath: argsPath, + }), + resolveDir, + } + } + return { + loader: 'js', + contents, + resolveDir, + } + } catch (e) { + console.error('node-modules-polyfill', e) + return { + contents: `export {}`, + loader: 'js', + } + } + } + onLoad({ filter: /.*/, namespace }, loader) + onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader) + const filter = new RegExp( + [ + ...polyfilledBuiltinsNames, + ...polyfilledBuiltinsNames.map((n) => `node:${n}`), + ] + .map(escapeStringRegexp) + .join('|'), // TODO builtins could end with slash, keep in mind in regex + ) + async function resolver(args: OnResolveArgs) { + const argsPath = args.path.replace(/^node:/, '') + const ignoreRequire = args.namespace === commonjsNamespace + + if (!polyfilledBuiltins.has(argsPath)) { + return + } + + const isCommonjs = + !ignoreRequire && args.kind === 'require-call' + + return { + namespace: isCommonjs ? commonjsNamespace : namespace, + path: argsPath, + } + } + onResolve({ filter }, resolver) + // onResolve({ filter: /.*/, namespace }, resolver) + }, + } +} + +function commonJsTemplate({ importPath }) { + return ` +const polyfill = require('${importPath}') + +if (polyfill && polyfill.default) { + module.exports = polyfill.default + for (let k in polyfill) { + module.exports[k] = polyfill[k] + } +} else if (polyfill) { + module.exports = polyfill +} + + +` +} + +export default NodeModulesPolyfillPlugin diff --git a/node_modules/@esbuild-plugins/node-modules-polyfill/src/polyfills.ts b/node_modules/@esbuild-plugins/node-modules-polyfill/src/polyfills.ts new file mode 100644 index 0000000..cea5f8d --- /dev/null +++ b/node_modules/@esbuild-plugins/node-modules-polyfill/src/polyfills.ts @@ -0,0 +1,151 @@ +// Taken from https://github.com/ionic-team/rollup-plugin-node-polyfills/blob/master/src/modules.ts + +import { NodePolyfillsOptions } from '.' + +const EMPTY_PATH = require.resolve( + 'rollup-plugin-node-polyfills/polyfills/empty.js', +) + +export function builtinsPolyfills() { + const libs = new Map() + + libs.set( + 'process', + require.resolve('rollup-plugin-node-polyfills/polyfills/process-es6'), + ) + libs.set( + 'buffer', + require.resolve('rollup-plugin-node-polyfills/polyfills/buffer-es6'), + ) + libs.set( + 'util', + require.resolve('rollup-plugin-node-polyfills/polyfills/util'), + ) + libs.set('sys', libs.get('util')) + libs.set( + 'events', + require.resolve('rollup-plugin-node-polyfills/polyfills/events'), + ) + libs.set( + 'stream', + require.resolve('rollup-plugin-node-polyfills/polyfills/stream'), + ) + libs.set( + 'path', + require.resolve('rollup-plugin-node-polyfills/polyfills/path'), + ) + libs.set( + 'querystring', + require.resolve('rollup-plugin-node-polyfills/polyfills/qs'), + ) + libs.set( + 'punycode', + require.resolve('rollup-plugin-node-polyfills/polyfills/punycode'), + ) + libs.set( + 'url', + require.resolve('rollup-plugin-node-polyfills/polyfills/url'), + ) + libs.set( + 'string_decoder', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/string-decoder', + ), + ) + libs.set( + 'http', + require.resolve('rollup-plugin-node-polyfills/polyfills/http'), + ) + libs.set( + 'https', + require.resolve('rollup-plugin-node-polyfills/polyfills/http'), + ) + libs.set('os', require.resolve('rollup-plugin-node-polyfills/polyfills/os')) + libs.set( + 'assert', + require.resolve('rollup-plugin-node-polyfills/polyfills/assert'), + ) + libs.set( + 'constants', + require.resolve('rollup-plugin-node-polyfills/polyfills/constants'), + ) + libs.set( + '_stream_duplex', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex', + ), + ) + libs.set( + '_stream_passthrough', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough', + ), + ) + libs.set( + '_stream_readable', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/readable', + ), + ) + libs.set( + '_stream_writable', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/writable', + ), + ) + libs.set( + '_stream_transform', + require.resolve( + 'rollup-plugin-node-polyfills/polyfills/readable-stream/transform', + ), + ) + libs.set( + 'timers', + require.resolve('rollup-plugin-node-polyfills/polyfills/timers'), + ) + libs.set( + 'console', + require.resolve('rollup-plugin-node-polyfills/polyfills/console'), + ) + libs.set('vm', require.resolve('rollup-plugin-node-polyfills/polyfills/vm')) + libs.set( + 'zlib', + require.resolve('rollup-plugin-node-polyfills/polyfills/zlib'), + ) + libs.set( + 'tty', + require.resolve('rollup-plugin-node-polyfills/polyfills/tty'), + ) + libs.set( + 'domain', + require.resolve('rollup-plugin-node-polyfills/polyfills/domain'), + ) + + // not shimmed + libs.set('dns', EMPTY_PATH) + libs.set('dgram', EMPTY_PATH) + libs.set('child_process', EMPTY_PATH) + libs.set('cluster', EMPTY_PATH) + libs.set('module', EMPTY_PATH) + libs.set('net', EMPTY_PATH) + libs.set('readline', EMPTY_PATH) + libs.set('repl', EMPTY_PATH) + libs.set('tls', EMPTY_PATH) + libs.set('fs', EMPTY_PATH) + libs.set('crypto', EMPTY_PATH) + + // libs.set( + // 'fs', + // require.resolve('rollup-plugin-node-polyfills/polyfills/browserify-fs'), + // ) + + // TODO enable crypto and fs https://github.com/ionic-team/rollup-plugin-node-polyfills/issues/20 + // libs.set( + // 'crypto', + // require.resolve( + // 'rollup-plugin-node-polyfills/polyfills/crypto-browserify', + // ), + // ) + + return libs +} diff --git a/node_modules/@esbuild/win32-x64/README.md b/node_modules/@esbuild/win32-x64/README.md new file mode 100644 index 0000000..a99ee7c --- /dev/null +++ b/node_modules/@esbuild/win32-x64/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is the Windows 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details. diff --git a/node_modules/@esbuild/win32-x64/esbuild.exe b/node_modules/@esbuild/win32-x64/esbuild.exe new file mode 100644 index 0000000..771afc9 Binary files /dev/null and b/node_modules/@esbuild/win32-x64/esbuild.exe differ diff --git a/node_modules/@esbuild/win32-x64/package.json b/node_modules/@esbuild/win32-x64/package.json new file mode 100644 index 0000000..3d313c2 --- /dev/null +++ b/node_modules/@esbuild/win32-x64/package.json @@ -0,0 +1,17 @@ +{ + "name": "@esbuild/win32-x64", + "version": "0.17.19", + "description": "The Windows 64-bit binary for esbuild, a JavaScript bundler.", + "repository": "https://github.com/evanw/esbuild", + "license": "MIT", + "preferUnplugged": true, + "engines": { + "node": ">=12" + }, + "os": [ + "win32" + ], + "cpu": [ + "x64" + ] +} diff --git a/node_modules/acorn-walk/CHANGELOG.md b/node_modules/acorn-walk/CHANGELOG.md new file mode 100644 index 0000000..30ec5a5 --- /dev/null +++ b/node_modules/acorn-walk/CHANGELOG.md @@ -0,0 +1,167 @@ +## 8.2.0 (2021-09-06) + +### New features + +Add support for walking ES2022 class static blocks. + +## 8.1.1 (2021-06-29) + +### Bug fixes + +Include `base` in the type declarations. + +## 8.1.0 (2021-04-24) + +### New features + +Support node types for class fields and private methods. + +## 8.0.2 (2021-01-25) + +### Bug fixes + +Adjust package.json to work with Node 12.16.0 and 13.0-13.6. + +## 8.0.0 (2021-01-05) + +### Bug fixes + +Fix a bug where `full` and `fullAncestor` would skip nodes with overridden types. + +## 8.0.0 (2020-08-12) + +### New features + +The package can now be loaded directly as an ECMAScript module in node 13+. + +## 7.2.0 (2020-06-17) + +### New features + +Support optional chaining and nullish coalescing. + +Support `import.meta`. + +Add support for `export * as ns from "source"`. + +## 7.1.1 (2020-02-13) + +### Bug fixes + +Clean up the type definitions to actually work well with the main parser. + +## 7.1.0 (2020-02-11) + +### New features + +Add a TypeScript definition file for the library. + +## 7.0.0 (2017-08-12) + +### New features + +Support walking `ImportExpression` nodes. + +## 6.2.0 (2017-07-04) + +### New features + +Add support for `Import` nodes. + +## 6.1.0 (2018-09-28) + +### New features + +The walker now walks `TemplateElement` nodes. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix bad "main" field in package.json. + +## 6.0.0 (2018-09-14) + +### Breaking changes + +This is now a separate package, `acorn-walk`, rather than part of the main `acorn` package. + +The `ScopeBody` and `ScopeExpression` meta-node-types are no longer supported. + +## 5.7.1 (2018-06-15) + +### Bug fixes + +Make sure the walker and bin files are rebuilt on release (the previous release didn't get the up-to-date versions). + +## 5.7.0 (2018-06-15) + +### Bug fixes + +Fix crash in walker when walking a binding-less catch node. + +## 5.6.2 (2018-06-05) + +### Bug fixes + +In the walker, go back to allowing the `baseVisitor` argument to be null to default to the default base everywhere. + +## 5.6.1 (2018-06-01) + +### Bug fixes + +Fix regression when passing `null` as fourth argument to `walk.recursive`. + +## 5.6.0 (2018-05-31) + +### Bug fixes + +Fix a bug in the walker that caused a crash when walking an object pattern spread. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix regression in walker causing property values in object patterns to be walked as expressions. + +## 5.5.0 (2018-02-27) + +### Bug fixes + +Support object spread in the AST walker. + +## 5.4.1 (2018-02-02) + +### Bug fixes + +5.4.0 somehow accidentally included an old version of walk.js. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +The `full` and `fullAncestor` walkers no longer visit nodes multiple times. + +## 5.1.0 (2017-07-05) + +### New features + +New walker functions `full` and `fullAncestor`. + +## 3.2.0 (2016-06-07) + +### New features + +Make it possible to use `visit.ancestor` with a walk state. + +## 3.1.0 (2016-04-18) + +### New features + +The walker now allows defining handlers for `CatchClause` nodes. + +## 2.5.2 (2015-10-27) + +### Fixes + +Fix bug where the walker walked an exported `let` statement as an expression. diff --git a/node_modules/acorn-walk/LICENSE b/node_modules/acorn-walk/LICENSE new file mode 100644 index 0000000..d6be6db --- /dev/null +++ b/node_modules/acorn-walk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2012-2020 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/acorn-walk/README.md b/node_modules/acorn-walk/README.md new file mode 100644 index 0000000..e192bac --- /dev/null +++ b/node_modules/acorn-walk/README.md @@ -0,0 +1,126 @@ +# Acorn AST walker + +An abstract syntax tree walker for the +[ESTree](https://github.com/estree/estree) format. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/acorn-walk/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). For questions +and discussion, please use the +[Tern discussion forum](https://discuss.ternjs.net). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn-walk +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` + +## Interface + +An algorithm for recursing through a syntax tree is stored as an +object, with a property for each tree node type holding a function +that will recurse through such a node. There are several ways to run +such a walker. + +**simple**`(node, visitors, base, state)` does a 'simple' walk over a +tree. `node` should be the AST node to walk, and `visitors` an object +with properties whose names correspond to node types in the [ESTree +spec](https://github.com/estree/estree). The properties should contain +functions that will be called with the node object and, if applicable +the state at that point. The last two arguments are optional. `base` +is a walker algorithm, and `state` is a start state. The default +walker will simply visit all statements and expressions and not +produce a meaningful state. (An example of a use of state is to track +scope at each point in the tree.) + +```js +const acorn = require("acorn") +const walk = require("acorn-walk") + +walk.simple(acorn.parse("let x = 10"), { + Literal(node) { + console.log(`Found a literal: ${node.value}`) + } +}) +``` + +**ancestor**`(node, visitors, base, state)` does a 'simple' walk over +a tree, building up an array of ancestor nodes (including the current node) +and passing the array to the callbacks as a third parameter. + +```js +const acorn = require("acorn") +const walk = require("acorn-walk") + +walk.ancestor(acorn.parse("foo('hi')"), { + Literal(_, ancestors) { + console.log("This literal's ancestors are:", ancestors.map(n => n.type)) + } +}) +``` + +**recursive**`(node, state, functions, base)` does a 'recursive' +walk, where the walker functions are responsible for continuing the +walk on the child nodes of their target node. `state` is the start +state, and `functions` should contain an object that maps node types +to walker functions. Such functions are called with `(node, state, c)` +arguments, and can cause the walk to continue on a sub-node by calling +the `c` argument on it with `(node, state)` arguments. The optional +`base` argument provides the fallback walker functions for node types +that aren't handled in the `functions` object. If not given, the +default walkers will be used. + +**make**`(functions, base)` builds a new walker object by using the +walker functions in `functions` and filling in the missing ones by +taking defaults from `base`. + +**full**`(node, callback, base, state)` does a 'full' walk over a +tree, calling the callback with the arguments (node, state, type) for +each node + +**fullAncestor**`(node, callback, base, state)` does a 'full' walk +over a tree, building up an array of ancestor nodes (including the +current node) and passing the array to the callbacks as a third +parameter. + +```js +const acorn = require("acorn") +const walk = require("acorn-walk") + +walk.full(acorn.parse("1 + 1"), node => { + console.log(`There's a ${node.type} node at ${node.ch}`) +}) +``` + +**findNodeAt**`(node, start, end, test, base, state)` tries to locate +a node in a tree at the given start and/or end offsets, which +satisfies the predicate `test`. `start` and `end` can be either `null` +(as wildcard) or a number. `test` may be a string (indicating a node +type) or a function that takes `(nodeType, node)` arguments and +returns a boolean indicating whether this node is interesting. `base` +and `state` are optional, and can be used to specify a custom walker. +Nodes are tested from inner to outer, so if two nodes match the +boundaries, the inner one will be preferred. + +**findNodeAround**`(node, pos, test, base, state)` is a lot like +`findNodeAt`, but will match any node that exists 'around' (spanning) +the given position. + +**findNodeAfter**`(node, pos, test, base, state)` is similar to +`findNodeAround`, but will match all nodes *after* the given position +(testing outer nodes before inner nodes). diff --git a/node_modules/acorn-walk/dist/walk.d.ts b/node_modules/acorn-walk/dist/walk.d.ts new file mode 100644 index 0000000..2d81f01 --- /dev/null +++ b/node_modules/acorn-walk/dist/walk.d.ts @@ -0,0 +1,114 @@ +import {Node} from 'acorn'; + +declare module "acorn-walk" { + type FullWalkerCallback = ( + node: Node, + state: TState, + type: string + ) => void; + + type FullAncestorWalkerCallback = ( + node: Node, + state: TState | Node[], + ancestors: Node[], + type: string + ) => void; + type WalkerCallback = (node: Node, state: TState) => void; + + type SimpleWalkerFn = ( + node: Node, + state: TState + ) => void; + + type AncestorWalkerFn = ( + node: Node, + state: TState| Node[], + ancestors: Node[] + ) => void; + + type RecursiveWalkerFn = ( + node: Node, + state: TState, + callback: WalkerCallback + ) => void; + + type SimpleVisitors = { + [type: string]: SimpleWalkerFn + }; + + type AncestorVisitors = { + [type: string]: AncestorWalkerFn + }; + + type RecursiveVisitors = { + [type: string]: RecursiveWalkerFn + }; + + type FindPredicate = (type: string, node: Node) => boolean; + + interface Found { + node: Node, + state: TState + } + + export function simple( + node: Node, + visitors: SimpleVisitors, + base?: RecursiveVisitors, + state?: TState + ): void; + + export function ancestor( + node: Node, + visitors: AncestorVisitors, + base?: RecursiveVisitors, + state?: TState + ): void; + + export function recursive( + node: Node, + state: TState, + functions: RecursiveVisitors, + base?: RecursiveVisitors + ): void; + + export function full( + node: Node, + callback: FullWalkerCallback, + base?: RecursiveVisitors, + state?: TState + ): void; + + export function fullAncestor( + node: Node, + callback: FullAncestorWalkerCallback, + base?: RecursiveVisitors, + state?: TState + ): void; + + export function make( + functions: RecursiveVisitors, + base?: RecursiveVisitors + ): RecursiveVisitors; + + export function findNodeAt( + node: Node, + start: number | undefined, + end?: number | undefined, + type?: FindPredicate | string, + base?: RecursiveVisitors, + state?: TState + ): Found | undefined; + + export function findNodeAround( + node: Node, + start: number | undefined, + type?: FindPredicate | string, + base?: RecursiveVisitors, + state?: TState + ): Found | undefined; + + export const findNodeAfter: typeof findNodeAround; + + export const base: RecursiveVisitors; +} diff --git a/node_modules/acorn-walk/dist/walk.js b/node_modules/acorn-walk/dist/walk.js new file mode 100644 index 0000000..a7f81b0 --- /dev/null +++ b/node_modules/acorn-walk/dist/walk.js @@ -0,0 +1,463 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory((global.acorn = global.acorn || {}, global.acorn.walk = {}))); +}(this, (function (exports) { 'use strict'; + + // AST walker module for Mozilla Parser API compatible trees + + // A simple walk is one where you simply specify callbacks to be + // called on specific nodes. The last two arguments are optional. A + // simple use would be + // + // walk.simple(myTree, { + // Expression: function(node) { ... } + // }); + // + // to do something with all expressions. All Parser API node types + // can be used to identify node types, as well as Expression and + // Statement, which denote categories of nodes. + // + // The base argument can be used to pass a custom (recursive) + // walker, and state can be used to give this walked an initial + // state. + + function simple(node, visitors, baseVisitor, state, override) { + if (!baseVisitor) { baseVisitor = base + ; }(function c(node, st, override) { + var type = override || node.type, found = visitors[type]; + baseVisitor[type](node, st, c); + if (found) { found(node, st); } + })(node, state, override); + } + + // An ancestor walk keeps an array of ancestor nodes (including the + // current node) and passes them to the callback as third parameter + // (and also as state parameter when no other state is present). + function ancestor(node, visitors, baseVisitor, state, override) { + var ancestors = []; + if (!baseVisitor) { baseVisitor = base + ; }(function c(node, st, override) { + var type = override || node.type, found = visitors[type]; + var isNew = node !== ancestors[ancestors.length - 1]; + if (isNew) { ancestors.push(node); } + baseVisitor[type](node, st, c); + if (found) { found(node, st || ancestors, ancestors); } + if (isNew) { ancestors.pop(); } + })(node, state, override); + } + + // A recursive walk is one where your functions override the default + // walkers. They can modify and replace the state parameter that's + // threaded through the walk, and can opt how and whether to walk + // their child nodes (by calling their third argument on these + // nodes). + function recursive(node, state, funcs, baseVisitor, override) { + var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor + ;(function c(node, st, override) { + visitor[override || node.type](node, st, c); + })(node, state, override); + } + + function makeTest(test) { + if (typeof test === "string") + { return function (type) { return type === test; } } + else if (!test) + { return function () { return true; } } + else + { return test } + } + + var Found = function Found(node, state) { this.node = node; this.state = state; }; + + // A full walk triggers the callback on each node + function full(node, callback, baseVisitor, state, override) { + if (!baseVisitor) { baseVisitor = base; } + var last + ;(function c(node, st, override) { + var type = override || node.type; + baseVisitor[type](node, st, c); + if (last !== node) { + callback(node, st, type); + last = node; + } + })(node, state, override); + } + + // An fullAncestor walk is like an ancestor walk, but triggers + // the callback on each node + function fullAncestor(node, callback, baseVisitor, state) { + if (!baseVisitor) { baseVisitor = base; } + var ancestors = [], last + ;(function c(node, st, override) { + var type = override || node.type; + var isNew = node !== ancestors[ancestors.length - 1]; + if (isNew) { ancestors.push(node); } + baseVisitor[type](node, st, c); + if (last !== node) { + callback(node, st || ancestors, ancestors, type); + last = node; + } + if (isNew) { ancestors.pop(); } + })(node, state); + } + + // Find a node with a given start, end, and type (all are optional, + // null can be used as wildcard). Returns a {node, state} object, or + // undefined when it doesn't find a matching node. + function findNodeAt(node, start, end, test, baseVisitor, state) { + if (!baseVisitor) { baseVisitor = base; } + test = makeTest(test); + try { + (function c(node, st, override) { + var type = override || node.type; + if ((start == null || node.start <= start) && + (end == null || node.end >= end)) + { baseVisitor[type](node, st, c); } + if ((start == null || node.start === start) && + (end == null || node.end === end) && + test(type, node)) + { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } + } + + // Find the innermost node of a given type that contains the given + // position. Interface similar to findNodeAt. + function findNodeAround(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + var type = override || node.type; + if (node.start > pos || node.end < pos) { return } + baseVisitor[type](node, st, c); + if (test(type, node)) { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } + } + + // Find the outermost matching node after a given position. + function findNodeAfter(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + if (node.end < pos) { return } + var type = override || node.type; + if (node.start >= pos && test(type, node)) { throw new Found(node, st) } + baseVisitor[type](node, st, c); + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } + } + + // Find the outermost matching node before a given position. + function findNodeBefore(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + var max + ;(function c(node, st, override) { + if (node.start > pos) { return } + var type = override || node.type; + if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) + { max = new Found(node, st); } + baseVisitor[type](node, st, c); + })(node, state); + return max + } + + // Used to create a custom walker. Will fill in all missing node + // type properties with the defaults. + function make(funcs, baseVisitor) { + var visitor = Object.create(baseVisitor || base); + for (var type in funcs) { visitor[type] = funcs[type]; } + return visitor + } + + function skipThrough(node, st, c) { c(node, st); } + function ignore(_node, _st, _c) {} + + // Node walkers. + + var base = {}; + + base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var stmt = list[i]; + + c(stmt, st, "Statement"); + } + }; + base.Statement = skipThrough; + base.EmptyStatement = ignore; + base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = + function (node, st, c) { return c(node.expression, st, "Expression"); }; + base.IfStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Statement"); + if (node.alternate) { c(node.alternate, st, "Statement"); } + }; + base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; + base.BreakStatement = base.ContinueStatement = ignore; + base.WithStatement = function (node, st, c) { + c(node.object, st, "Expression"); + c(node.body, st, "Statement"); + }; + base.SwitchStatement = function (node, st, c) { + c(node.discriminant, st, "Expression"); + for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { + var cs = list$1[i$1]; + + if (cs.test) { c(cs.test, st, "Expression"); } + for (var i = 0, list = cs.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } + } + }; + base.SwitchCase = function (node, st, c) { + if (node.test) { c(node.test, st, "Expression"); } + for (var i = 0, list = node.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } + }; + base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { + if (node.argument) { c(node.argument, st, "Expression"); } + }; + base.ThrowStatement = base.SpreadElement = + function (node, st, c) { return c(node.argument, st, "Expression"); }; + base.TryStatement = function (node, st, c) { + c(node.block, st, "Statement"); + if (node.handler) { c(node.handler, st); } + if (node.finalizer) { c(node.finalizer, st, "Statement"); } + }; + base.CatchClause = function (node, st, c) { + if (node.param) { c(node.param, st, "Pattern"); } + c(node.body, st, "Statement"); + }; + base.WhileStatement = base.DoWhileStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.body, st, "Statement"); + }; + base.ForStatement = function (node, st, c) { + if (node.init) { c(node.init, st, "ForInit"); } + if (node.test) { c(node.test, st, "Expression"); } + if (node.update) { c(node.update, st, "Expression"); } + c(node.body, st, "Statement"); + }; + base.ForInStatement = base.ForOfStatement = function (node, st, c) { + c(node.left, st, "ForInit"); + c(node.right, st, "Expression"); + c(node.body, st, "Statement"); + }; + base.ForInit = function (node, st, c) { + if (node.type === "VariableDeclaration") { c(node, st); } + else { c(node, st, "Expression"); } + }; + base.DebuggerStatement = ignore; + + base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; + base.VariableDeclaration = function (node, st, c) { + for (var i = 0, list = node.declarations; i < list.length; i += 1) + { + var decl = list[i]; + + c(decl, st); + } + }; + base.VariableDeclarator = function (node, st, c) { + c(node.id, st, "Pattern"); + if (node.init) { c(node.init, st, "Expression"); } + }; + + base.Function = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + c(param, st, "Pattern"); + } + c(node.body, st, node.expression ? "Expression" : "Statement"); + }; + + base.Pattern = function (node, st, c) { + if (node.type === "Identifier") + { c(node, st, "VariablePattern"); } + else if (node.type === "MemberExpression") + { c(node, st, "MemberPattern"); } + else + { c(node, st); } + }; + base.VariablePattern = ignore; + base.MemberPattern = skipThrough; + base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; + base.ArrayPattern = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Pattern"); } + } + }; + base.ObjectPattern = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + if (prop.type === "Property") { + if (prop.computed) { c(prop.key, st, "Expression"); } + c(prop.value, st, "Pattern"); + } else if (prop.type === "RestElement") { + c(prop.argument, st, "Pattern"); + } + } + }; + + base.Expression = skipThrough; + base.ThisExpression = base.Super = base.MetaProperty = ignore; + base.ArrayExpression = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Expression"); } + } + }; + base.ObjectExpression = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) + { + var prop = list[i]; + + c(prop, st); + } + }; + base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; + base.SequenceExpression = function (node, st, c) { + for (var i = 0, list = node.expressions; i < list.length; i += 1) + { + var expr = list[i]; + + c(expr, st, "Expression"); + } + }; + base.TemplateLiteral = function (node, st, c) { + for (var i = 0, list = node.quasis; i < list.length; i += 1) + { + var quasi = list[i]; + + c(quasi, st); + } + + for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) + { + var expr = list$1[i$1]; + + c(expr, st, "Expression"); + } + }; + base.TemplateElement = ignore; + base.UnaryExpression = base.UpdateExpression = function (node, st, c) { + c(node.argument, st, "Expression"); + }; + base.BinaryExpression = base.LogicalExpression = function (node, st, c) { + c(node.left, st, "Expression"); + c(node.right, st, "Expression"); + }; + base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { + c(node.left, st, "Pattern"); + c(node.right, st, "Expression"); + }; + base.ConditionalExpression = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Expression"); + c(node.alternate, st, "Expression"); + }; + base.NewExpression = base.CallExpression = function (node, st, c) { + c(node.callee, st, "Expression"); + if (node.arguments) + { for (var i = 0, list = node.arguments; i < list.length; i += 1) + { + var arg = list[i]; + + c(arg, st, "Expression"); + } } + }; + base.MemberExpression = function (node, st, c) { + c(node.object, st, "Expression"); + if (node.computed) { c(node.property, st, "Expression"); } + }; + base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { + if (node.declaration) + { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } + if (node.source) { c(node.source, st, "Expression"); } + }; + base.ExportAllDeclaration = function (node, st, c) { + if (node.exported) + { c(node.exported, st); } + c(node.source, st, "Expression"); + }; + base.ImportDeclaration = function (node, st, c) { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) + { + var spec = list[i]; + + c(spec, st); + } + c(node.source, st, "Expression"); + }; + base.ImportExpression = function (node, st, c) { + c(node.source, st, "Expression"); + }; + base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; + + base.TaggedTemplateExpression = function (node, st, c) { + c(node.tag, st, "Expression"); + c(node.quasi, st, "Expression"); + }; + base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; + base.Class = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + if (node.superClass) { c(node.superClass, st, "Expression"); } + c(node.body, st); + }; + base.ClassBody = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var elt = list[i]; + + c(elt, st); + } + }; + base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) { + if (node.computed) { c(node.key, st, "Expression"); } + if (node.value) { c(node.value, st, "Expression"); } + }; + + exports.ancestor = ancestor; + exports.base = base; + exports.findNodeAfter = findNodeAfter; + exports.findNodeAround = findNodeAround; + exports.findNodeAt = findNodeAt; + exports.findNodeBefore = findNodeBefore; + exports.full = full; + exports.fullAncestor = fullAncestor; + exports.make = make; + exports.recursive = recursive; + exports.simple = simple; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/node_modules/acorn-walk/dist/walk.mjs b/node_modules/acorn-walk/dist/walk.mjs new file mode 100644 index 0000000..89dd1f1 --- /dev/null +++ b/node_modules/acorn-walk/dist/walk.mjs @@ -0,0 +1,443 @@ +// AST walker module for Mozilla Parser API compatible trees + +// A simple walk is one where you simply specify callbacks to be +// called on specific nodes. The last two arguments are optional. A +// simple use would be +// +// walk.simple(myTree, { +// Expression: function(node) { ... } +// }); +// +// to do something with all expressions. All Parser API node types +// can be used to identify node types, as well as Expression and +// Statement, which denote categories of nodes. +// +// The base argument can be used to pass a custom (recursive) +// walker, and state can be used to give this walked an initial +// state. + +function simple(node, visitors, baseVisitor, state, override) { + if (!baseVisitor) { baseVisitor = base + ; }(function c(node, st, override) { + var type = override || node.type, found = visitors[type]; + baseVisitor[type](node, st, c); + if (found) { found(node, st); } + })(node, state, override); +} + +// An ancestor walk keeps an array of ancestor nodes (including the +// current node) and passes them to the callback as third parameter +// (and also as state parameter when no other state is present). +function ancestor(node, visitors, baseVisitor, state, override) { + var ancestors = []; + if (!baseVisitor) { baseVisitor = base + ; }(function c(node, st, override) { + var type = override || node.type, found = visitors[type]; + var isNew = node !== ancestors[ancestors.length - 1]; + if (isNew) { ancestors.push(node); } + baseVisitor[type](node, st, c); + if (found) { found(node, st || ancestors, ancestors); } + if (isNew) { ancestors.pop(); } + })(node, state, override); +} + +// A recursive walk is one where your functions override the default +// walkers. They can modify and replace the state parameter that's +// threaded through the walk, and can opt how and whether to walk +// their child nodes (by calling their third argument on these +// nodes). +function recursive(node, state, funcs, baseVisitor, override) { + var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor + ;(function c(node, st, override) { + visitor[override || node.type](node, st, c); + })(node, state, override); +} + +function makeTest(test) { + if (typeof test === "string") + { return function (type) { return type === test; } } + else if (!test) + { return function () { return true; } } + else + { return test } +} + +var Found = function Found(node, state) { this.node = node; this.state = state; }; + +// A full walk triggers the callback on each node +function full(node, callback, baseVisitor, state, override) { + if (!baseVisitor) { baseVisitor = base; } + var last + ;(function c(node, st, override) { + var type = override || node.type; + baseVisitor[type](node, st, c); + if (last !== node) { + callback(node, st, type); + last = node; + } + })(node, state, override); +} + +// An fullAncestor walk is like an ancestor walk, but triggers +// the callback on each node +function fullAncestor(node, callback, baseVisitor, state) { + if (!baseVisitor) { baseVisitor = base; } + var ancestors = [], last + ;(function c(node, st, override) { + var type = override || node.type; + var isNew = node !== ancestors[ancestors.length - 1]; + if (isNew) { ancestors.push(node); } + baseVisitor[type](node, st, c); + if (last !== node) { + callback(node, st || ancestors, ancestors, type); + last = node; + } + if (isNew) { ancestors.pop(); } + })(node, state); +} + +// Find a node with a given start, end, and type (all are optional, +// null can be used as wildcard). Returns a {node, state} object, or +// undefined when it doesn't find a matching node. +function findNodeAt(node, start, end, test, baseVisitor, state) { + if (!baseVisitor) { baseVisitor = base; } + test = makeTest(test); + try { + (function c(node, st, override) { + var type = override || node.type; + if ((start == null || node.start <= start) && + (end == null || node.end >= end)) + { baseVisitor[type](node, st, c); } + if ((start == null || node.start === start) && + (end == null || node.end === end) && + test(type, node)) + { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } +} + +// Find the innermost node of a given type that contains the given +// position. Interface similar to findNodeAt. +function findNodeAround(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + var type = override || node.type; + if (node.start > pos || node.end < pos) { return } + baseVisitor[type](node, st, c); + if (test(type, node)) { throw new Found(node, st) } + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } +} + +// Find the outermost matching node after a given position. +function findNodeAfter(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + try { + (function c(node, st, override) { + if (node.end < pos) { return } + var type = override || node.type; + if (node.start >= pos && test(type, node)) { throw new Found(node, st) } + baseVisitor[type](node, st, c); + })(node, state); + } catch (e) { + if (e instanceof Found) { return e } + throw e + } +} + +// Find the outermost matching node before a given position. +function findNodeBefore(node, pos, test, baseVisitor, state) { + test = makeTest(test); + if (!baseVisitor) { baseVisitor = base; } + var max + ;(function c(node, st, override) { + if (node.start > pos) { return } + var type = override || node.type; + if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) + { max = new Found(node, st); } + baseVisitor[type](node, st, c); + })(node, state); + return max +} + +// Used to create a custom walker. Will fill in all missing node +// type properties with the defaults. +function make(funcs, baseVisitor) { + var visitor = Object.create(baseVisitor || base); + for (var type in funcs) { visitor[type] = funcs[type]; } + return visitor +} + +function skipThrough(node, st, c) { c(node, st); } +function ignore(_node, _st, _c) {} + +// Node walkers. + +var base = {}; + +base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var stmt = list[i]; + + c(stmt, st, "Statement"); + } +}; +base.Statement = skipThrough; +base.EmptyStatement = ignore; +base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = + function (node, st, c) { return c(node.expression, st, "Expression"); }; +base.IfStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Statement"); + if (node.alternate) { c(node.alternate, st, "Statement"); } +}; +base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; +base.BreakStatement = base.ContinueStatement = ignore; +base.WithStatement = function (node, st, c) { + c(node.object, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.SwitchStatement = function (node, st, c) { + c(node.discriminant, st, "Expression"); + for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { + var cs = list$1[i$1]; + + if (cs.test) { c(cs.test, st, "Expression"); } + for (var i = 0, list = cs.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } + } +}; +base.SwitchCase = function (node, st, c) { + if (node.test) { c(node.test, st, "Expression"); } + for (var i = 0, list = node.consequent; i < list.length; i += 1) + { + var cons = list[i]; + + c(cons, st, "Statement"); + } +}; +base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { + if (node.argument) { c(node.argument, st, "Expression"); } +}; +base.ThrowStatement = base.SpreadElement = + function (node, st, c) { return c(node.argument, st, "Expression"); }; +base.TryStatement = function (node, st, c) { + c(node.block, st, "Statement"); + if (node.handler) { c(node.handler, st); } + if (node.finalizer) { c(node.finalizer, st, "Statement"); } +}; +base.CatchClause = function (node, st, c) { + if (node.param) { c(node.param, st, "Pattern"); } + c(node.body, st, "Statement"); +}; +base.WhileStatement = base.DoWhileStatement = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.ForStatement = function (node, st, c) { + if (node.init) { c(node.init, st, "ForInit"); } + if (node.test) { c(node.test, st, "Expression"); } + if (node.update) { c(node.update, st, "Expression"); } + c(node.body, st, "Statement"); +}; +base.ForInStatement = base.ForOfStatement = function (node, st, c) { + c(node.left, st, "ForInit"); + c(node.right, st, "Expression"); + c(node.body, st, "Statement"); +}; +base.ForInit = function (node, st, c) { + if (node.type === "VariableDeclaration") { c(node, st); } + else { c(node, st, "Expression"); } +}; +base.DebuggerStatement = ignore; + +base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; +base.VariableDeclaration = function (node, st, c) { + for (var i = 0, list = node.declarations; i < list.length; i += 1) + { + var decl = list[i]; + + c(decl, st); + } +}; +base.VariableDeclarator = function (node, st, c) { + c(node.id, st, "Pattern"); + if (node.init) { c(node.init, st, "Expression"); } +}; + +base.Function = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + c(param, st, "Pattern"); + } + c(node.body, st, node.expression ? "Expression" : "Statement"); +}; + +base.Pattern = function (node, st, c) { + if (node.type === "Identifier") + { c(node, st, "VariablePattern"); } + else if (node.type === "MemberExpression") + { c(node, st, "MemberPattern"); } + else + { c(node, st); } +}; +base.VariablePattern = ignore; +base.MemberPattern = skipThrough; +base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; +base.ArrayPattern = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Pattern"); } + } +}; +base.ObjectPattern = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + if (prop.type === "Property") { + if (prop.computed) { c(prop.key, st, "Expression"); } + c(prop.value, st, "Pattern"); + } else if (prop.type === "RestElement") { + c(prop.argument, st, "Pattern"); + } + } +}; + +base.Expression = skipThrough; +base.ThisExpression = base.Super = base.MetaProperty = ignore; +base.ArrayExpression = function (node, st, c) { + for (var i = 0, list = node.elements; i < list.length; i += 1) { + var elt = list[i]; + + if (elt) { c(elt, st, "Expression"); } + } +}; +base.ObjectExpression = function (node, st, c) { + for (var i = 0, list = node.properties; i < list.length; i += 1) + { + var prop = list[i]; + + c(prop, st); + } +}; +base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; +base.SequenceExpression = function (node, st, c) { + for (var i = 0, list = node.expressions; i < list.length; i += 1) + { + var expr = list[i]; + + c(expr, st, "Expression"); + } +}; +base.TemplateLiteral = function (node, st, c) { + for (var i = 0, list = node.quasis; i < list.length; i += 1) + { + var quasi = list[i]; + + c(quasi, st); + } + + for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) + { + var expr = list$1[i$1]; + + c(expr, st, "Expression"); + } +}; +base.TemplateElement = ignore; +base.UnaryExpression = base.UpdateExpression = function (node, st, c) { + c(node.argument, st, "Expression"); +}; +base.BinaryExpression = base.LogicalExpression = function (node, st, c) { + c(node.left, st, "Expression"); + c(node.right, st, "Expression"); +}; +base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { + c(node.left, st, "Pattern"); + c(node.right, st, "Expression"); +}; +base.ConditionalExpression = function (node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Expression"); + c(node.alternate, st, "Expression"); +}; +base.NewExpression = base.CallExpression = function (node, st, c) { + c(node.callee, st, "Expression"); + if (node.arguments) + { for (var i = 0, list = node.arguments; i < list.length; i += 1) + { + var arg = list[i]; + + c(arg, st, "Expression"); + } } +}; +base.MemberExpression = function (node, st, c) { + c(node.object, st, "Expression"); + if (node.computed) { c(node.property, st, "Expression"); } +}; +base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { + if (node.declaration) + { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } + if (node.source) { c(node.source, st, "Expression"); } +}; +base.ExportAllDeclaration = function (node, st, c) { + if (node.exported) + { c(node.exported, st); } + c(node.source, st, "Expression"); +}; +base.ImportDeclaration = function (node, st, c) { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) + { + var spec = list[i]; + + c(spec, st); + } + c(node.source, st, "Expression"); +}; +base.ImportExpression = function (node, st, c) { + c(node.source, st, "Expression"); +}; +base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; + +base.TaggedTemplateExpression = function (node, st, c) { + c(node.tag, st, "Expression"); + c(node.quasi, st, "Expression"); +}; +base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; +base.Class = function (node, st, c) { + if (node.id) { c(node.id, st, "Pattern"); } + if (node.superClass) { c(node.superClass, st, "Expression"); } + c(node.body, st); +}; +base.ClassBody = function (node, st, c) { + for (var i = 0, list = node.body; i < list.length; i += 1) + { + var elt = list[i]; + + c(elt, st); + } +}; +base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) { + if (node.computed) { c(node.key, st, "Expression"); } + if (node.value) { c(node.value, st, "Expression"); } +}; + +export { ancestor, base, findNodeAfter, findNodeAround, findNodeAt, findNodeBefore, full, fullAncestor, make, recursive, simple }; diff --git a/node_modules/acorn-walk/package.json b/node_modules/acorn-walk/package.json new file mode 100644 index 0000000..8d75b97 --- /dev/null +++ b/node_modules/acorn-walk/package.json @@ -0,0 +1,45 @@ +{ + "name": "acorn-walk", + "description": "ECMAScript (ESTree) AST walker", + "homepage": "https://github.com/acornjs/acorn", + "main": "dist/walk.js", + "types": "dist/walk.d.ts", + "module": "dist/walk.mjs", + "exports": { + ".": [ + { + "import": "./dist/walk.mjs", + "require": "./dist/walk.js", + "default": "./dist/walk.js" + }, + "./dist/walk.js" + ], + "./package.json": "./package.json" + }, + "version": "8.2.0", + "engines": {"node": ">=0.4.0"}, + "maintainers": [ + { + "name": "Marijn Haverbeke", + "email": "marijnh@gmail.com", + "web": "https://marijnhaverbeke.nl" + }, + { + "name": "Ingvar Stepanyan", + "email": "me@rreverser.com", + "web": "https://rreverser.com/" + }, + { + "name": "Adrian Heine", + "web": "http://adrianheine.de" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/acornjs/acorn.git" + }, + "scripts": { + "prepare": "cd ..; npm run build:walk" + }, + "license": "MIT" +} diff --git a/node_modules/acorn/CHANGELOG.md b/node_modules/acorn/CHANGELOG.md new file mode 100644 index 0000000..12464cf --- /dev/null +++ b/node_modules/acorn/CHANGELOG.md @@ -0,0 +1,844 @@ +## 8.10.0 (2023-07-05) + +### New features + +Add a `checkPrivateFields` option that disables strict checking of private property use. + +## 8.9.0 (2023-06-16) + +### Bug fixes + +Forbid dynamic import after `new`, even when part of a member expression. + +### New features + +Add Unicode properties for ES2023. + +Add support for the `v` flag to regular expressions. + +## 8.8.2 (2023-01-23) + +### Bug fixes + +Fix a bug that caused `allowHashBang` to be set to false when not provided, even with `ecmaVersion >= 14`. + +Fix an exception when passing no option object to `parse` or `new Parser`. + +Fix incorrect parse error on `if (0) let\n[astral identifier char]`. + +## 8.8.1 (2022-10-24) + +### Bug fixes + +Make type for `Comment` compatible with estree types. + +## 8.8.0 (2022-07-21) + +### Bug fixes + +Allow parentheses around spread args in destructuring object assignment. + +Fix an issue where the tree contained `directive` properties in when parsing with a language version that doesn't support them. + +### New features + +Support hashbang comments by default in ECMAScript 2023 and later. + +## 8.7.1 (2021-04-26) + +### Bug fixes + +Stop handling `"use strict"` directives in ECMAScript versions before 5. + +Fix an issue where duplicate quoted export names in `export *` syntax were incorrectly checked. + +Add missing type for `tokTypes`. + +## 8.7.0 (2021-12-27) + +### New features + +Support quoted export names. + +Upgrade to Unicode 14. + +Add support for Unicode 13 properties in regular expressions. + +### Bug fixes + +Use a loop to find line breaks, because the existing regexp search would overrun the end of the searched range and waste a lot of time in minified code. + +## 8.6.0 (2021-11-18) + +### Bug fixes + +Fix a bug where an object literal with multiple `__proto__` properties would incorrectly be accepted if a later property value held an assigment. + +### New features + +Support class private fields with the `in` operator. + +## 8.5.0 (2021-09-06) + +### Bug fixes + +Improve context-dependent tokenization in a number of corner cases. + +Fix location tracking after a 0x2028 or 0x2029 character in a string literal (which before did not increase the line number). + +Fix an issue where arrow function bodies in for loop context would inappropriately consume `in` operators. + +Fix wrong end locations stored on SequenceExpression nodes. + +Implement restriction that `for`/`of` loop LHS can't start with `let`. + +### New features + +Add support for ES2022 class static blocks. + +Allow multiple input files to be passed to the CLI tool. + +## 8.4.1 (2021-06-24) + +### Bug fixes + +Fix a bug where `allowAwaitOutsideFunction` would allow `await` in class field initializers, and setting `ecmaVersion` to 13 or higher would allow top-level await in non-module sources. + +## 8.4.0 (2021-06-11) + +### New features + +A new option, `allowSuperOutsideMethod`, can be used to suppress the error when `super` is used in the wrong context. + +## 8.3.0 (2021-05-31) + +### New features + +Default `allowAwaitOutsideFunction` to true for ECMAScript 2022 an higher. + +Add support for the `d` ([indices](https://github.com/tc39/proposal-regexp-match-indices)) regexp flag. + +## 8.2.4 (2021-05-04) + +### Bug fixes + +Fix spec conformity in corner case 'for await (async of ...)'. + +## 8.2.3 (2021-05-04) + +### Bug fixes + +Fix an issue where the library couldn't parse 'for (async of ...)'. + +Fix a bug in UTF-16 decoding that would read characters incorrectly in some circumstances. + +## 8.2.2 (2021-04-29) + +### Bug fixes + +Fix a bug where a class field initialized to an async arrow function wouldn't allow await inside it. Same issue existed for generator arrow functions with yield. + +## 8.2.1 (2021-04-24) + +### Bug fixes + +Fix a regression introduced in 8.2.0 where static or async class methods with keyword names fail to parse. + +## 8.2.0 (2021-04-24) + +### New features + +Add support for ES2022 class fields and private methods. + +## 8.1.1 (2021-04-12) + +### Various + +Stop shipping source maps in the NPM package. + +## 8.1.0 (2021-03-09) + +### Bug fixes + +Fix a spurious error in nested destructuring arrays. + +### New features + +Expose `allowAwaitOutsideFunction` in CLI interface. + +Make `allowImportExportAnywhere` also apply to `import.meta`. + +## 8.0.5 (2021-01-25) + +### Bug fixes + +Adjust package.json to work with Node 12.16.0 and 13.0-13.6. + +## 8.0.4 (2020-10-05) + +### Bug fixes + +Make `await x ** y` an error, following the spec. + +Fix potentially exponential regular expression. + +## 8.0.3 (2020-10-02) + +### Bug fixes + +Fix a wasteful loop during `Parser` creation when setting `ecmaVersion` to `"latest"`. + +## 8.0.2 (2020-09-30) + +### Bug fixes + +Make the TypeScript types reflect the current allowed values for `ecmaVersion`. + +Fix another regexp/division tokenizer issue. + +## 8.0.1 (2020-08-12) + +### Bug fixes + +Provide the correct value in the `version` export. + +## 8.0.0 (2020-08-12) + +### Bug fixes + +Disallow expressions like `(a = b) = c`. + +Make non-octal escape sequences a syntax error in strict mode. + +### New features + +The package can now be loaded directly as an ECMAScript module in node 13+. + +Update to the set of Unicode properties from ES2021. + +### Breaking changes + +The `ecmaVersion` option is now required. For the moment, omitting it will still work with a warning, but that will change in a future release. + +Some changes to method signatures that may be used by plugins. + +## 7.4.0 (2020-08-03) + +### New features + +Add support for logical assignment operators. + +Add support for numeric separators. + +## 7.3.1 (2020-06-11) + +### Bug fixes + +Make the string in the `version` export match the actual library version. + +## 7.3.0 (2020-06-11) + +### Bug fixes + +Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail. + +### New features + +Add support for optional chaining (`?.`). + +## 7.2.0 (2020-05-09) + +### Bug fixes + +Fix precedence issue in parsing of async arrow functions. + +### New features + +Add support for nullish coalescing. + +Add support for `import.meta`. + +Support `export * as ...` syntax. + +Upgrade to Unicode 13. + +## 6.4.1 (2020-03-09) + +### Bug fixes + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.1 (2020-03-01) + +### Bug fixes + +Treat `\8` and `\9` as invalid escapes in template strings. + +Allow unicode escapes in property names that are keywords. + +Don't error on an exponential operator expression as argument to `await`. + +More carefully check for valid UTF16 surrogate pairs in regexp validator. + +## 7.1.0 (2019-09-24) + +### Bug fixes + +Disallow trailing object literal commas when ecmaVersion is less than 5. + +### New features + +Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on. + +## 7.0.0 (2019-08-13) + +### Breaking changes + +Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression). + +Makes 10 (ES2019) the default value for the `ecmaVersion` option. + +## 6.3.0 (2019-08-12) + +### New features + +`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard. + +## 6.2.1 (2019-07-21) + +### Bug fixes + +Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such. + +Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances. + +## 6.2.0 (2019-07-04) + +### Bug fixes + +Improve valid assignment checking in `for`/`in` and `for`/`of` loops. + +Disallow binding `let` in patterns. + +### New features + +Support bigint syntax with `ecmaVersion` >= 11. + +Support dynamic `import` syntax with `ecmaVersion` >= 11. + +Upgrade to Unicode version 12. + +## 6.1.1 (2019-02-27) + +### Bug fixes + +Fix bug that caused parsing default exports of with names to fail. + +## 6.1.0 (2019-02-08) + +### Bug fixes + +Fix scope checking when redefining a `var` as a lexical binding. + +### New features + +Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins. + +## 6.0.7 (2019-02-04) + +### Bug fixes + +Check that exported bindings are defined. + +Don't treat `\u180e` as a whitespace character. + +Check for duplicate parameter names in methods. + +Don't allow shorthand properties when they are generators or async methods. + +Forbid binding `await` in async arrow function's parameter list. + +## 6.0.6 (2019-01-30) + +### Bug fixes + +The content of class declarations and expressions is now always parsed in strict mode. + +Don't allow `let` or `const` to bind the variable name `let`. + +Treat class declarations as lexical. + +Don't allow a generator function declaration as the sole body of an `if` or `else`. + +Ignore `"use strict"` when after an empty statement. + +Allow string line continuations with special line terminator characters. + +Treat `for` bodies as part of the `for` scope when checking for conflicting bindings. + +Fix bug with parsing `yield` in a `for` loop initializer. + +Implement special cases around scope checking for functions. + +## 6.0.5 (2019-01-02) + +### Bug fixes + +Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type. + +Don't treat `let` as a keyword when the next token is `{` on the next line. + +Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on. + +## 6.0.4 (2018-11-05) + +### Bug fixes + +Further improvements to tokenizing regular expressions in corner cases. + +## 6.0.3 (2018-11-04) + +### Bug fixes + +Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression. + +Remove stray symlink in the package tarball. + +## 6.0.2 (2018-09-26) + +### Bug fixes + +Fix bug where default expressions could fail to parse inside an object destructuring assignment expression. + +## 6.0.1 (2018-09-14) + +### Bug fixes + +Fix wrong value in `version` export. + +## 6.0.0 (2018-09-14) + +### Bug fixes + +Better handle variable-redefinition checks for catch bindings and functions directly under if statements. + +Forbid `new.target` in top-level arrow functions. + +Fix issue with parsing a regexp after `yield` in some contexts. + +### New features + +The package now comes with TypeScript definitions. + +### Breaking changes + +The default value of the `ecmaVersion` option is now 9 (2018). + +Plugins work differently, and will have to be rewritten to work with this version. + +The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`). + +## 5.7.3 (2018-09-10) + +### Bug fixes + +Fix failure to tokenize regexps after expressions like `x.of`. + +Better error message for unterminated template literals. + +## 5.7.2 (2018-08-24) + +### Bug fixes + +Properly handle `allowAwaitOutsideFunction` in for statements. + +Treat function declarations at the top level of modules like let bindings. + +Don't allow async function declarations as the only statement under a label. + +## 5.7.0 (2018-06-15) + +### New features + +Upgraded to Unicode 11. + +## 5.6.0 (2018-05-31) + +### New features + +Allow U+2028 and U+2029 in string when ECMAVersion >= 10. + +Allow binding-less catch statements when ECMAVersion >= 10. + +Add `allowAwaitOutsideFunction` option for parsing top-level `await`. + +## 5.5.3 (2018-03-08) + +### Bug fixes + +A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps. + +## 5.5.2 (2018-03-08) + +### Bug fixes + +A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0. + +## 5.5.1 (2018-03-06) + +### Bug fixes + +Fix misleading error message for octal escapes in template strings. + +## 5.5.0 (2018-02-27) + +### New features + +The identifier character categorization is now based on Unicode version 10. + +Acorn will now validate the content of regular expressions, including new ES9 features. + +## 5.4.0 (2018-02-01) + +### Bug fixes + +Disallow duplicate or escaped flags on regular expressions. + +Disallow octal escapes in strings in strict mode. + +### New features + +Add support for async iteration. + +Add support for object spread and rest. + +## 5.3.0 (2017-12-28) + +### Bug fixes + +Fix parsing of floating point literals with leading zeroes in loose mode. + +Allow duplicate property names in object patterns. + +Don't allow static class methods named `prototype`. + +Disallow async functions directly under `if` or `else`. + +Parse right-hand-side of `for`/`of` as an assignment expression. + +Stricter parsing of `for`/`in`. + +Don't allow unicode escapes in contextual keywords. + +### New features + +Parsing class members was factored into smaller methods to allow plugins to hook into it. + +## 5.2.1 (2017-10-30) + +### Bug fixes + +Fix a token context corruption bug. + +## 5.2.0 (2017-10-30) + +### Bug fixes + +Fix token context tracking for `class` and `function` in property-name position. + +Make sure `%*` isn't parsed as a valid operator. + +Allow shorthand properties `get` and `set` to be followed by default values. + +Disallow `super` when not in callee or object position. + +### New features + +Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements. + +## 5.1.2 (2017-09-04) + +### Bug fixes + +Disable parsing of legacy HTML-style comments in modules. + +Fix parsing of async methods whose names are keywords. + +## 5.1.1 (2017-07-06) + +### Bug fixes + +Fix problem with disambiguating regexp and division after a class. + +## 5.1.0 (2017-07-05) + +### Bug fixes + +Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`. + +Parse zero-prefixed numbers with non-octal digits as decimal. + +Allow object/array patterns in rest parameters. + +Don't error when `yield` is used as a property name. + +Allow `async` as a shorthand object property. + +### New features + +Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9. + +## 5.0.3 (2017-04-01) + +### Bug fixes + +Fix spurious duplicate variable definition errors for named functions. + +## 5.0.2 (2017-03-30) + +### Bug fixes + +A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error. + +## 5.0.0 (2017-03-28) + +### Bug fixes + +Raise an error for duplicated lexical bindings. + +Fix spurious error when an assignement expression occurred after a spread expression. + +Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions. + +Allow labels in front or `var` declarations, even in strict mode. + +### Breaking changes + +Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`. + +## 4.0.11 (2017-02-07) + +### Bug fixes + +Allow all forms of member expressions to be parenthesized as lvalue. + +## 4.0.10 (2017-02-07) + +### Bug fixes + +Don't expect semicolons after default-exported functions or classes, even when they are expressions. + +Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode. + +## 4.0.9 (2017-02-06) + +### Bug fixes + +Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again. + +## 4.0.8 (2017-02-03) + +### Bug fixes + +Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet. + +## 4.0.7 (2017-02-02) + +### Bug fixes + +Accept invalidly rejected code like `(x).y = 2` again. + +Don't raise an error when a function _inside_ strict code has a non-simple parameter list. + +## 4.0.6 (2017-02-02) + +### Bug fixes + +Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check. + +## 4.0.5 (2017-02-02) + +### Bug fixes + +Disallow parenthesized pattern expressions. + +Allow keywords as export names. + +Don't allow the `async` keyword to be parenthesized. + +Properly raise an error when a keyword contains a character escape. + +Allow `"use strict"` to appear after other string literal expressions. + +Disallow labeled declarations. + +## 4.0.4 (2016-12-19) + +### Bug fixes + +Fix crash when `export` was followed by a keyword that can't be +exported. + +## 4.0.3 (2016-08-16) + +### Bug fixes + +Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode. + +Properly parse properties named `async` in ES2017 mode. + +Fix bug where reserved words were broken in ES2017 mode. + +## 4.0.2 (2016-08-11) + +### Bug fixes + +Don't ignore period or 'e' characters after octal numbers. + +Fix broken parsing for call expressions in default parameter values of arrow functions. + +## 4.0.1 (2016-08-08) + +### Bug fixes + +Fix false positives in duplicated export name errors. + +## 4.0.0 (2016-08-07) + +### Breaking changes + +The default `ecmaVersion` option value is now 7. + +A number of internal method signatures changed, so plugins might need to be updated. + +### Bug fixes + +The parser now raises errors on duplicated export names. + +`arguments` and `eval` can now be used in shorthand properties. + +Duplicate parameter names in non-simple argument lists now always produce an error. + +### New features + +The `ecmaVersion` option now also accepts year-style version numbers +(2015, etc). + +Support for `async`/`await` syntax when `ecmaVersion` is >= 8. + +Support for trailing commas in call expressions when `ecmaVersion` is >= 8. + +## 3.3.0 (2016-07-25) + +### Bug fixes + +Fix bug in tokenizing of regexp operator after a function declaration. + +Fix parser crash when parsing an array pattern with a hole. + +### New features + +Implement check against complex argument lists in functions that enable strict mode in ES7. + +## 3.2.0 (2016-06-07) + +### Bug fixes + +Improve handling of lack of unicode regexp support in host +environment. + +Properly reject shorthand properties whose name is a keyword. + +### New features + +Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object. + +## 3.1.0 (2016-04-18) + +### Bug fixes + +Properly tokenize the division operator directly after a function expression. + +Allow trailing comma in destructuring arrays. + +## 3.0.4 (2016-02-25) + +### Fixes + +Allow update expressions as left-hand-side of the ES7 exponential operator. + +## 3.0.2 (2016-02-10) + +### Fixes + +Fix bug that accidentally made `undefined` a reserved word when parsing ES7. + +## 3.0.0 (2016-02-10) + +### Breaking changes + +The default value of the `ecmaVersion` option is now 6 (used to be 5). + +Support for comprehension syntax (which was dropped from the draft spec) has been removed. + +### Fixes + +`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code. + +A parenthesized class or function expression after `export default` is now parsed correctly. + +### New features + +When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`). + +The identifier character ranges are now based on Unicode 8.0.0. + +Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled. + +## 2.7.0 (2016-01-04) + +### Fixes + +Stop allowing rest parameters in setters. + +Disallow `y` rexexp flag in ES5. + +Disallow `\00` and `\000` escapes in strict mode. + +Raise an error when an import name is a reserved word. + +## 2.6.2 (2015-11-10) + +### Fixes + +Don't crash when no options object is passed. + +## 2.6.0 (2015-11-09) + +### Fixes + +Add `await` as a reserved word in module sources. + +Disallow `yield` in a parameter default value for a generator. + +Forbid using a comma after a rest pattern in an array destructuring. + +### New features + +Support parsing stdin in command-line tool. + +## 2.5.0 (2015-10-27) + +### Fixes + +Fix tokenizer support in the command-line tool. + +Stop allowing `new.target` outside of functions. + +Remove legacy `guard` and `guardedHandler` properties from try nodes. + +Stop allowing multiple `__proto__` properties on an object literal in strict mode. + +Don't allow rest parameters to be non-identifier patterns. + +Check for duplicate paramter names in arrow functions. diff --git a/node_modules/acorn/LICENSE b/node_modules/acorn/LICENSE new file mode 100644 index 0000000..9d71cc6 --- /dev/null +++ b/node_modules/acorn/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2012-2022 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/acorn/README.md b/node_modules/acorn/README.md new file mode 100644 index 0000000..b62d02b --- /dev/null +++ b/node_modules/acorn/README.md @@ -0,0 +1,278 @@ +# Acorn + +A tiny, fast JavaScript parser written in JavaScript. + +## Community + +Acorn is open source software released under an +[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). + +You are welcome to +[report bugs](https://github.com/acornjs/acorn/issues) or create pull +requests on [github](https://github.com/acornjs/acorn). For questions +and discussion, please use the +[Tern discussion forum](https://discuss.ternjs.net). + +## Installation + +The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): + +```sh +npm install acorn +``` + +Alternately, you can download the source and build acorn yourself: + +```sh +git clone https://github.com/acornjs/acorn.git +cd acorn +npm install +``` + +## Interface + +**parse**`(input, options)` is the main interface to the library. The +`input` parameter is a string, `options` must be an object setting +some of the options listed below. The return value will be an abstract +syntax tree object as specified by the [ESTree +spec](https://github.com/estree/estree). + +```javascript +let acorn = require("acorn"); +console.log(acorn.parse("1 + 1", {ecmaVersion: 2020})); +``` + +When encountering a syntax error, the parser will raise a +`SyntaxError` object with a meaningful message. The error object will +have a `pos` property that indicates the string offset at which the +error occurred, and a `loc` object that contains a `{line, column}` +object referring to that same position. + +Options are provided by in a second argument, which should be an +object containing any of these fields (only `ecmaVersion` is +required): + +- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be + either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019), + 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` (the + latest the library supports). This influences support for strict + mode, the set of reserved words, and support for new syntax + features. + + **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being + implemented by Acorn. Other proposed new features must be + implemented through plugins. + +- **sourceType**: Indicate the mode the code should be parsed in. Can be + either `"script"` or `"module"`. This influences global strict mode + and parsing of `import` and `export` declarations. + + **NOTE**: If set to `"module"`, then static `import` / `export` syntax + will be valid, even if `ecmaVersion` is less than 6. + +- **onInsertedSemicolon**: If given a callback, that callback will be + called whenever a missing semicolon is inserted by the parser. The + callback will be given the character offset of the point where the + semicolon is inserted as argument, and if `locations` is on, also a + `{line, column}` object representing this position. + +- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing + commas. + +- **allowReserved**: If `false`, using a reserved word will generate + an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher + versions. When given the value `"never"`, reserved words and + keywords can also not be used as property names (as in Internet + Explorer's old parser). + +- **allowReturnOutsideFunction**: By default, a return statement at + the top level raises an error. Set this to `true` to accept such + code. + +- **allowImportExportEverywhere**: By default, `import` and `export` + declarations can only appear at a program's top level. Setting this + option to `true` allows them anywhere where a statement is allowed, + and also allows `import.meta` expressions to appear in scripts + (when `sourceType` is not `"module"`). + +- **allowAwaitOutsideFunction**: If `false`, `await` expressions can + only appear inside `async` functions. Defaults to `true` in modules + for `ecmaVersion` 2022 and later, `false` for lower versions. + Setting this option to `true` allows to have top-level `await` + expressions. They are still not allowed in non-`async` functions, + though. + +- **allowSuperOutsideMethod**: By default, `super` outside a method + raises an error. Set this to `true` to accept such code. + +- **allowHashBang**: When this is enabled, if the code starts with the + characters `#!` (as in a shellscript), the first line will be + treated as a comment. Defaults to true when `ecmaVersion` >= 2023. + +- **checkPrivateFields**: By default, the parser will verify that + private properties are only used in places where they are valid and + have been declared. Set this to false to turn such checks off. + +- **locations**: When `true`, each node has a `loc` object attached + with `start` and `end` subobjects, each of which contains the + one-based line and zero-based column numbers in `{line, column}` + form. Default is `false`. + +- **onToken**: If a function is passed for this option, each found + token will be passed in same format as tokens returned from + `tokenizer().getToken()`. + + If array is passed, each found token is pushed to it. + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **onComment**: If a function is passed for this option, whenever a + comment is encountered the function will be called with the + following parameters: + + - `block`: `true` if the comment is a block comment, false if it + is a line comment. + - `text`: The content of the comment. + - `start`: Character offset of the start of the comment. + - `end`: Character offset of the end of the comment. + + When the `locations` options is on, the `{line, column}` locations + of the comment’s start and end are passed as two additional + parameters. + + If array is passed for this option, each found comment is pushed + to it as object in Esprima format: + + ```javascript + { + "type": "Line" | "Block", + "value": "comment text", + "start": Number, + "end": Number, + // If `locations` option is on: + "loc": { + "start": {line: Number, column: Number} + "end": {line: Number, column: Number} + }, + // If `ranges` option is on: + "range": [Number, Number] + } + ``` + + Note that you are not allowed to call the parser from the + callback—that will corrupt its internal state. + +- **ranges**: Nodes have their start and end characters offsets + recorded in `start` and `end` properties (directly on the node, + rather than the `loc` object, which holds line/column data. To also + add a + [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) + `range` property holding a `[start, end]` array with the same + numbers, set the `ranges` option to `true`. + +- **program**: It is possible to parse multiple files into a single + AST by passing the tree produced by parsing the first file as the + `program` option in subsequent parses. This will add the toplevel + forms of the parsed file to the "Program" (top) node of an existing + parse tree. + +- **sourceFile**: When the `locations` option is `true`, you can pass + this option to add a `source` attribute in every node’s `loc` + object. Note that the contents of this option are not examined or + processed in any way; you are free to use whatever format you + choose. + +- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property + will be added (regardless of the `location` option) directly to the + nodes, rather than the `loc` object. + +- **preserveParens**: If this option is `true`, parenthesized expressions + are represented by (non-standard) `ParenthesizedExpression` nodes + that have a single `expression` property containing the expression + inside parentheses. + +**parseExpressionAt**`(input, offset, options)` will parse a single +expression in a string, and return its AST. It will not complain if +there is more of the string left after the expression. + +**tokenizer**`(input, options)` returns an object with a `getToken` +method that can be called repeatedly to get the next token, a `{start, +end, type, value}` object (with added `loc` property when the +`locations` option is enabled and `range` property when the `ranges` +option is enabled). When the token's type is `tokTypes.eof`, you +should stop calling the method, since it will keep returning that same +token forever. + +In ES6 environment, returned result can be used as any other +protocol-compliant iterable: + +```javascript +for (let token of acorn.tokenizer(str)) { + // iterate over the tokens +} + +// transform code to array of tokens: +var tokens = [...acorn.tokenizer(str)]; +``` + +**tokTypes** holds an object mapping names to the token type objects +that end up in the `type` properties of tokens. + +**getLineInfo**`(input, offset)` can be used to get a `{line, +column}` object for a given program string and offset. + +### The `Parser` class + +Instances of the **`Parser`** class contain all the state and logic +that drives a parse. It has static methods `parse`, +`parseExpressionAt`, and `tokenizer` that match the top-level +functions by the same name. + +When extending the parser with plugins, you need to call these methods +on the extended version of the class. To extend a parser with plugins, +you can use its static `extend` method. + +```javascript +var acorn = require("acorn"); +var jsx = require("acorn-jsx"); +var JSXParser = acorn.Parser.extend(jsx()); +JSXParser.parse("foo()", {ecmaVersion: 2020}); +``` + +The `extend` method takes any number of plugin values, and returns a +new `Parser` class that includes the extra parser logic provided by +the plugins. + +## Command line interface + +The `bin/acorn` utility can be used to parse a file from the command +line. It accepts as arguments its input file and the following +options: + +- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version + to parse. Default is version 9. + +- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. + +- `--locations`: Attaches a "loc" object to each node with "start" and + "end" subobjects, each of which contains the one-based line and + zero-based column numbers in `{line, column}` form. + +- `--allow-hash-bang`: If the code starts with the characters #! (as + in a shellscript), the first line will be treated as a comment. + +- `--allow-await-outside-function`: Allows top-level `await` expressions. + See the `allowAwaitOutsideFunction` option for more information. + +- `--compact`: No whitespace is used in the AST output. + +- `--silent`: Do not output the AST, just return the exit status. + +- `--help`: Print the usage information and quit. + +The utility spits out the syntax tree as JSON data. + +## Existing plugins + + - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) diff --git a/node_modules/acorn/bin/acorn b/node_modules/acorn/bin/acorn new file mode 100644 index 0000000..3ef3c12 --- /dev/null +++ b/node_modules/acorn/bin/acorn @@ -0,0 +1,4 @@ +#!/usr/bin/env node +"use strict" + +require("../dist/bin.js") diff --git a/node_modules/acorn/dist/acorn.d.mts b/node_modules/acorn/dist/acorn.d.mts new file mode 100644 index 0000000..49ae59f --- /dev/null +++ b/node_modules/acorn/dist/acorn.d.mts @@ -0,0 +1,26 @@ +export { + Node, + Parser, + Position, + SourceLocation, + TokContext, + Token, + TokenType, + defaultOptions, + getLineInfo, + isIdentifierChar, + isIdentifierStart, + isNewLine, + lineBreak, + lineBreakG, + parse, + parseExpressionAt, + tokContexts, + tokTypes, + tokenizer, + version, + AbstractToken, + Comment, + Options, + ecmaVersion, +} from "./acorn.js"; diff --git a/node_modules/acorn/dist/acorn.d.ts b/node_modules/acorn/dist/acorn.d.ts new file mode 100644 index 0000000..5b26741 --- /dev/null +++ b/node_modules/acorn/dist/acorn.d.ts @@ -0,0 +1,292 @@ +export as namespace acorn +export = acorn + +declare namespace acorn { + function parse(input: string, options: Options): Node + + function parseExpressionAt(input: string, pos: number, options: Options): Node + + function tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + + type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 'latest' + + interface Options { + ecmaVersion: ecmaVersion + sourceType?: 'script' | 'module' + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + allowReserved?: boolean | 'never' + allowReturnOutsideFunction?: boolean + allowImportExportEverywhere?: boolean + allowAwaitOutsideFunction?: boolean + allowSuperOutsideMethod?: boolean + allowHashBang?: boolean + locations?: boolean + onToken?: ((token: Token) => any) | Token[] + onComment?: (( + isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, + endLoc?: Position + ) => void) | Comment[] + ranges?: boolean + program?: Node + sourceFile?: string + directSourceFile?: string + preserveParens?: boolean + } + + class Parser { + // state.js + lineStart: number; + options: Options; + curLine: number; + start: number; + end: number; + input: string; + type: TokenType; + + // state.js + constructor(options: Options, input: string, startPos?: number) + parse(this: Parser): Node + + // tokenize.js + next(): void; + nextToken(): void; + + // statement.js + parseTopLevel(node: Node): Node; + + // node.js + finishNode(node: Node, type: string): Node; + finishNodeAt(node: Node, type: string, pos: number, loc: Position): Node; + + // location.js + raise(pos: number, message: string) : void; + raiseRecoverable?(pos: number, message: string) : void; + + // parseutils.js + unexpected(pos: number) : void; + + // index.js + static acorn: typeof acorn; + + // state.js + static parse(this: typeof Parser, input: string, options: Options): Node + static parseExpressionAt(this: typeof Parser, input: string, pos: number, options: Options): Node + static tokenizer(this: typeof Parser, input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + static extend(this: typeof Parser, ...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser + } + + interface Position { line: number; column: number; offset: number } + + const defaultOptions: Options + + function getLineInfo(input: string, offset: number): Position + + class SourceLocation { + start: Position + end: Position + source?: string | null + constructor(p: Parser, start: Position, end: Position) + } + + class Node { + type: string + start: number + end: number + loc?: SourceLocation + sourceFile?: string + range?: [number, number] + constructor(parser: Parser, pos: number, loc?: SourceLocation) + } + + class TokenType { + label: string + keyword: string + beforeExpr: boolean + startsExpr: boolean + isLoop: boolean + isAssign: boolean + prefix: boolean + postfix: boolean + binop: number + updateContext?: (prevType: TokenType) => void + constructor(label: string, conf?: any) + } + + const tokTypes: { + num: TokenType + regexp: TokenType + string: TokenType + name: TokenType + privateId: TokenType + eof: TokenType + bracketL: TokenType + bracketR: TokenType + braceL: TokenType + braceR: TokenType + parenL: TokenType + parenR: TokenType + comma: TokenType + semi: TokenType + colon: TokenType + dot: TokenType + question: TokenType + questionDot: TokenType + arrow: TokenType + template: TokenType + invalidTemplate: TokenType + ellipsis: TokenType + backQuote: TokenType + dollarBraceL: TokenType + eq: TokenType + assign: TokenType + incDec: TokenType + prefix: TokenType + logicalOR: TokenType + logicalAND: TokenType + bitwiseOR: TokenType + bitwiseXOR: TokenType + bitwiseAND: TokenType + equality: TokenType + relational: TokenType + bitShift: TokenType + plusMin: TokenType + modulo: TokenType + star: TokenType + slash: TokenType + starstar: TokenType + coalesce: TokenType + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType + } + + class TokContext { + constructor(token: string, isExpr: boolean, preserveSpace: boolean, override?: (p: Parser) => void) + } + + const tokContexts: { + b_stat: TokContext + b_expr: TokContext + b_tmpl: TokContext + p_stat: TokContext + p_expr: TokContext + q_tmpl: TokContext + f_expr: TokContext + f_stat: TokContext + f_expr_gen: TokContext + f_gen: TokContext + } + + function isIdentifierStart(code: number, astral?: boolean): boolean + + function isIdentifierChar(code: number, astral?: boolean): boolean + + interface AbstractToken { + } + + interface Comment extends AbstractToken { + type: 'Line' | 'Block' + value: string + start: number + end: number + loc?: SourceLocation + range?: [number, number] + } + + class Token { + type: TokenType + value: any + start: number + end: number + loc?: SourceLocation + range?: [number, number] + constructor(p: Parser) + } + + function isNewLine(code: number): boolean + + const lineBreak: RegExp + + const lineBreakG: RegExp + + const version: string + + const nonASCIIwhitespace: RegExp + + const keywordTypes: { + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType + } +} diff --git a/node_modules/acorn/dist/acorn.js b/node_modules/acorn/dist/acorn.js new file mode 100644 index 0000000..62e1aa6 --- /dev/null +++ b/node_modules/acorn/dist/acorn.js @@ -0,0 +1,5990 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.acorn = {})); +})(this, (function (exports) { 'use strict'; + + // This file was generated. Do not modify manually! + var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + + // This file was generated. Do not modify manually! + var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191]; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + + // These are a run-length and offset encoded representation of the + // >0xffff code points that are a valid part of identifiers. The + // offset starts at 0x10000, and each pair of numbers represents an + // offset to the next range, and then a size of the range. + + // Reserved word lists for various dialects of the language + + var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" + }; + + // And the keywords + + var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + + var keywords$1 = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" + }; + + var keywordRelationalOperator = /^in(stanceof)?$/; + + // ## Character categories + + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + + // This has a complexity linear to the value of the code. The + // assumption is that looking up astral identifier characters is + // rare. + function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } + } + return false + } + + // Test whether a given character code starts an identifier. + + function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) + } + + // Test whether a given character is part of an identifier. + + function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) + } + + // ## Token types + + // The assignment of fine-grained, information-carrying type objects + // allows the tokenizer to store the information it has about a + // token in a way that is very cheap for the parser to look up. + + // All token type variables start with an underscore, to make them + // easy to recognize. + + // The `beforeExpr` property is used to disambiguate between regular + // expressions and divisions. It is set on all token types that can + // be followed by an expression (thus, a slash after them would be a + // regular expression). + // + // The `startsExpr` property is used to check if the token ends a + // `yield` expression. It is set on all token types that either can + // directly start an expression (like a quotation mark) or can + // continue an expression (like the body of a string). + // + // `isLoop` marks a keyword as starting a loop, which is important + // to know when parsing a label, in order to allow or disallow + // continue jumps to that label. + + var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; + }; + + function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) + } + var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; + + // Map keyword names to token types. + + var keywords = {}; + + // Succinct definitions of keyword token types + function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name; + return keywords[name] = new TokenType(name, options) + } + + var types$1 = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + coalesce: binop("??", 1), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) + }; + + // Matches a whole line break (where CRLF is considered a single + // line break). Used to count lines. + + var lineBreak = /\r\n?|\n|\u2028|\u2029/; + var lineBreakG = new RegExp(lineBreak.source, "g"); + + function isNewLine(code) { + return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 + } + + function nextLineBreak(code, from, end) { + if ( end === void 0 ) end = code.length; + + for (var i = from; i < end; i++) { + var next = code.charCodeAt(i); + if (isNewLine(next)) + { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } + } + return -1 + } + + var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + + var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + + var ref = Object.prototype; + var hasOwnProperty = ref.hasOwnProperty; + var toString = ref.toString; + + var hasOwn = Object.hasOwn || (function (obj, propName) { return ( + hasOwnProperty.call(obj, propName) + ); }); + + var isArray = Array.isArray || (function (obj) { return ( + toString.call(obj) === "[object Array]" + ); }); + + function wordsRegexp(words) { + return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") + } + + function codePointToString(code) { + // UTF-16 Decoding + if (code <= 0xFFFF) { return String.fromCharCode(code) } + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) + } + + var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; + + // These are used when `options.locations` is on, for the + // `startLoc` and `endLoc` properties. + + var Position = function Position(line, col) { + this.line = line; + this.column = col; + }; + + Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) + }; + + var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } + }; + + // The `getLineInfo` function is mostly useful when the + // `locations` option is off (for performance reasons) and you + // want to find the line/column position for a given character + // offset. `input` should be the code string that the offset refers + // into. + + function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + var nextBreak = nextLineBreak(input, cur, offset); + if (nextBreak < 0) { return new Position(line, offset - cur) } + ++line; + cur = nextBreak; + } + } + + // A second argument must be given to configure the parser process. + // These options are recognized (only `ecmaVersion` is required): + + var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + // (the latest version the library supports). This influences + // support for strict mode, the set of reserved words, and support + // for new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called + // when a semicolon is automatically inserted. It will be passed + // the position of the comma as an offset, and if `locations` is + // enabled, it is given the location as a `{line, column}` object + // as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file is + // allowed and treated as a line comment. Enabled by default when + // `ecmaVersion` >= 2023. + allowHashBang: false, + // By default, the parser will verify that private properties are + // only used in places where they are valid and have been declared. + // Set this to false to turn such checks off. + checkPrivateFields: true, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false + }; + + // Interpret and default an options object + + var warnedAboutEcmaVersion = false; + + function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } + + if (!opts || opts.allowHashBang == null) + { options.allowHashBang = options.ecmaVersion >= 14; } + + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } + + return options + } + + function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); + } + } + + // Each scope gets a bitset that may contain these flags + var + SCOPE_TOP = 1, + SCOPE_FUNCTION = 2, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128, + SCOPE_CLASS_STATIC_BLOCK = 256, + SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; + + function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + } + + // Used in checkLVal* and declareName to determine the type of a binding + var + BIND_NONE = 0, // Not a binding + BIND_VAR = 1, // Var-style binding + BIND_LEXICAL = 2, // Let- or const-style binding + BIND_FUNCTION = 3, // Function declaration + BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding + BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + + var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + + // Properties of the current token: + // Its type + this.type = types$1.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + // Labels in scope. + this.labels = []; + // Thus-far undefined exports. + this.undefinedExports = Object.create(null); + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } + + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + + // For RegExp validation + this.regexpState = null; + + // The stack of private names. + // Each element has two properties: 'declared' and 'used'. + // When it exited from the outermost class definition, all used private names must be declared. + this.privateNameStack = []; + }; + + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; + + Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) + }; + + prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; + + prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; + + prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; + + prototypeAccessors.canAwait.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var scope = this.scopeStack[i]; + if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } + if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } + } + return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction + }; + + prototypeAccessors.allowSuper.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod + }; + + prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + + prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + + prototypeAccessors.allowNewDotTarget.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit + }; + + prototypeAccessors.inClassStaticBlock.get = function () { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 + }; + + Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; + + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls + }; + + Parser.parse = function parse (input, options) { + return new this(options, input).parse() + }; + + Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() + }; + + Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) + }; + + Object.defineProperties( Parser.prototype, prototypeAccessors ); + + var pp$9 = Parser.prototype; + + // ## Parser utilities + + var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; + pp$9.strictDirective = function(start) { + if (this.options.ecmaVersion < 5) { return false } + for (;;) { + // Try to find string literal. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || + (lineBreak.test(spaceAfter[0]) && + !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) + } + start += match[0].length; + + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } + } + }; + + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. + + pp$9.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } + }; + + // Tests whether parsed token is a contextual keyword. + + pp$9.isContextual = function(name) { + return this.type === types$1.name && this.value === name && !this.containsEsc + }; + + // Consumes contextual keyword if possible. + + pp$9.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true + }; + + // Asserts that following token is given contextual keyword. + + pp$9.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } + }; + + // Test whether a semicolon can be inserted at the current position. + + pp$9.canInsertSemicolon = function() { + return this.type === types$1.eof || + this.type === types$1.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + pp$9.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } + }; + + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. + + pp$9.semicolon = function() { + if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } + }; + + pp$9.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true + } + }; + + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. + + pp$9.expect = function(type) { + this.eat(type) || this.unexpected(); + }; + + // Raise an unexpected token error. + + pp$9.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); + }; + + var DestructuringErrors = function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; + }; + + pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } + }; + + pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } + }; + + pp$9.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } + }; + + pp$9.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" + }; + + var pp$8 = Parser.prototype; + + // ### Statement parsing + + // Parse a program. Initializes the parser, reads any number of + // statements, and wraps them in a Program node. Optionally takes a + // `program` argument. If present, the statements will be appended + // to its body instead of creating a new node. + + pp$8.parseTopLevel = function(node) { + var exports = Object.create(null); + if (!node.body) { node.body = []; } + while (this.type !== types$1.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); + } + if (this.inModule) + { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) + { + var name = list[i]; + + this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); + } } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program") + }; + + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + + pp$8.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + // For ambiguous cases, determine if a LexicalDeclaration (or only a + // Statement) is allowed here. If context is not empty then only a Statement + // is allowed. However, `let [` is an explicit negative lookahead for + // ExpressionStatement, so special-case it first. + if (nextCh === 91 || nextCh === 92) { return true } // '[', '/' + if (context) { return false } + + if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } + if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } + } + return false + }; + + // check 'async [no LineTerminator here] function' + // - 'async /*foo*/ function' is OK. + // - 'async /*\n*/ function' is invalid. + pp$8.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || + !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) + }; + + // Parse a single statement. + // + // If expecting a statement and finding a slash operator, parse a + // regular expression literal. This is to handle cases like + // `if (foo) /blah/.exec(foo)`, where looking at the previous token + // does not help. + + pp$8.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types$1._debugger: return this.parseDebuggerStatement(node) + case types$1._do: return this.parseDoStatement(node) + case types$1._for: return this.parseForStatement(node) + case types$1._function: + // Function as sole body of either an if statement or a labeled statement + // works, but not when it is part of a labeled statement that is the sole + // body of an if statement. + if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types$1._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types$1._if: return this.parseIfStatement(node) + case types$1._return: return this.parseReturnStatement(node) + case types$1._switch: return this.parseSwitchStatement(node) + case types$1._throw: return this.parseThrowStatement(node) + case types$1._try: return this.parseTryStatement(node) + case types$1._const: case types$1._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types$1._while: return this.parseWhileStatement(node) + case types$1._with: return this.parseWithStatement(node) + case types$1.braceL: return this.parseBlock(true, node) + case types$1.semi: return this.parseEmptyStatement(node) + case types$1._export: + case types$1._import: + if (this.options.ecmaVersion > 10 && starttype === types$1._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) // '(' or '.' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } + + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } + } + }; + + pp$8.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types$1.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } + } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") + }; + + pp$8.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") + }; + + pp$8.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types$1._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types$1.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") + }; + + // Disambiguating between a `for` and a `for`/`in` or `for`/`of` + // loop is non-trivial. Basically, we have to parse the init `var` + // statement or expression, disallowing the `in` operator (see + // the second parameter to `parseExpression`), and then check + // whether the next token is `in` or `of`. When there is no init + // part (semicolon immediately after the opening parenthesis), it + // is a regular `for` loop. + + pp$8.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types$1.parenL); + if (this.type === types$1.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types$1._var || this.type === types$1._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init$1) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init$1) + } + var startsWithLet = this.isContextual("let"), isForOf = false; + var refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); + if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) + }; + + pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) + }; + + pp$8.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") + }; + + pp$8.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") + }; + + pp$8.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types$1.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types$1.braceR;) { + if (this.type === types$1._case || this.type === types$1._default) { + var isCase = this.type === types$1._case; + if (cur) { this.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this.expect(types$1.colon); + } else { + if (!cur) { this.unexpected(); } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") + }; + + pp$8.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") + }; + + // Reused empty array added for node fields that are always empty. + + var empty$1 = []; + + pp$8.parseCatchClauseParam = function() { + var param = this.parseBindingAtom(); + var simple = param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types$1.parenR); + + return param + }; + + pp$8.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types$1._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types$1.parenL)) { + clause.param = this.parseCatchClauseParam(); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") + }; + + pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") + }; + + pp$8.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") + }; + + pp$8.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") + }; + + pp$8.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") + }; + + pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") + }; + + pp$8.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") + }; + + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). + + pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); + + node.body = []; + this.expect(types$1.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + if (exitStrict) { this.strict = false; } + this.next(); + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") + }; + + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. + + pp$8.parseFor = function(node, init) { + node.init = init; + this.expect(types$1.semi); + node.test = this.type === types$1.semi ? null : this.parseExpression(); + this.expect(types$1.semi); + node.update = this.type === types$1.parenR ? null : this.parseExpression(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement") + }; + + // Parse a `for`/`in` and `for`/`of` loop, which are almost + // same from parser's perspective. + + pp$8.parseForIn = function(node, init) { + var isForIn = this.type === types$1._in; + this.next(); + + if ( + init.type === "VariableDeclaration" && + init.declarations[0].init != null && + ( + !isForIn || + this.options.ecmaVersion < 8 || + this.strict || + init.kind !== "var" || + init.declarations[0].id.type !== "Identifier" + ) + ) { + this.raise( + init.start, + ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") + ); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") + }; + + // Parse a list of variable declarations. + + pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) { + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types$1.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { + this.unexpected(); + } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) { break } + } + return node + }; + + pp$8.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); + }; + + var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + + // Parse a function declaration or literal (depending on the + // `statement & FUNC_STATEMENT`). + + // Remove `allowExpressionBody` for 7.0.0, as it is only called with false + pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) + { this.unexpected(); } + node.generator = this.eat(types$1.star); + } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + // If it is a regular function declaration in sloppy mode, then it is + // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding + // mode depends on properties of the current scope (see + // treatFunctionsAsVar). + { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } + + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types$1.name ? this.parseIdent() : null; } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") + }; + + pp$8.parseFunctionParams = function(node) { + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + }; + + // Parse a class declaration or literal (depending on the + // `isStatement` parameter). + + pp$8.parseClass = function(node, isStatement) { + this.next(); + + // ecma-262 14.6 Class Definitions + // A class definition is always strict mode code. + var oldStrict = this.strict; + this.strict = true; + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types$1.braceL); + while (this.type !== types$1.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; + + pp$8.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types$1.semi)) { return null } + + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + + if (this.eatContextual("static")) { + // Parse static init block + if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { + this.parseClassStaticBlock(node); + return node + } + if (this.isClassElementNameStart() || this.type === types$1.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node.static = isStatic; + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + + // Parse element name + if (keyName) { + // 'async', 'get', 'set', or 'static' were not a keyword contextually. + // The last token is any of those. Make it the element name. + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + + // Parse element value + if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. + if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + + return node + }; + + pp$8.isClassElementNameStart = function() { + return ( + this.type === types$1.name || + this.type === types$1.privateId || + this.type === types$1.num || + this.type === types$1.string || + this.type === types$1.bracketL || + this.type.keyword + ) + }; + + pp$8.parseClassElementName = function(element) { + if (this.type === types$1.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } + }; + + pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + // Check key and flags + var key = method.key; + if (method.kind === "constructor") { + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + + // Parse value + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + + // Check value + if (method.kind === "get" && value.params.length !== 0) + { this.raiseRecoverable(value.start, "getter should have no params"); } + if (method.kind === "set" && value.params.length !== 1) + { this.raiseRecoverable(value.start, "setter should have exactly one param"); } + if (method.kind === "set" && value.params[0].type === "RestElement") + { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } + + return this.finishNode(method, "MethodDefinition") + }; + + pp$8.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + + if (this.eat(types$1.eq)) { + // To raise SyntaxError if 'arguments' exists in the initializer. + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; + } + this.semicolon(); + + return this.finishNode(field, "PropertyDefinition") + }; + + pp$8.parseClassStaticBlock = function(node) { + node.body = []; + + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + this.next(); + this.exitScope(); + this.labels = oldLabels; + + return this.finishNode(node, "StaticBlock") + }; + + pp$8.parseClassId = function(node, isStatement) { + if (this.type === types$1.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLValSimple(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; + } + }; + + pp$8.parseClassSuper = function(node) { + node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; + }; + + pp$8.enterClassBody = function() { + var element = {declared: Object.create(null), used: []}; + this.privateNameStack.push(element); + return element.declared + }; + + pp$8.exitClassBody = function() { + var ref = this.privateNameStack.pop(); + var declared = ref.declared; + var used = ref.used; + if (!this.options.checkPrivateFields) { return } + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!hasOwn(declared, id.name)) { + if (parent) { + parent.used.push(id); + } else { + this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); + } + } + } + }; + + function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + + // `class { get #a(){}; static set #a(_){} }` is also conflict. + if ( + curr === "iget" && next === "iset" || + curr === "iset" && next === "iget" || + curr === "sget" && next === "sset" || + curr === "sset" && next === "sget" + ) { + privateNameMap[name] = "true"; + return false + } else if (!curr) { + privateNameMap[name] = next; + return false + } else { + return true + } + } + + function checkKeyName(node, name) { + var computed = node.computed; + var key = node.key; + return !computed && ( + key.type === "Identifier" && key.name === name || + key.type === "Literal" && key.value === name + ) + } + + // Parses module export declaration. + + pp$8.parseExportAllDeclaration = function(node, exports) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + this.checkExport(exports, node.exported, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") + }; + + pp$8.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types$1.star)) { + return this.parseExportAllDeclaration(node, exports) + } + if (this.eat(types$1._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + node.declaration = this.parseExportDefaultDeclaration(); + return this.finishNode(node, "ExportDefaultDeclaration") + } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseExportDeclaration(node); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); + } + } + + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration") + }; + + pp$8.parseExportDeclaration = function(node) { + return this.parseStatement(null) + }; + + pp$8.parseExportDefaultDeclaration = function() { + var isAsync; + if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync) + } else if (this.type === types$1._class) { + var cNode = this.startNode(); + return this.parseClass(cNode, "nullableID") + } else { + var declaration = this.parseMaybeAssign(); + this.semicolon(); + return declaration + } + }; + + pp$8.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (typeof name !== "string") + { name = name.type === "Identifier" ? name.name : name.value; } + if (hasOwn(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; + }; + + pp$8.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } + else if (type === "ParenthesizedExpression") + { this.checkPatternExport(exports, pat.expression); } + }; + + pp$8.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this.checkPatternExport(exports, decl.id); + } + }; + + pp$8.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() + }; + + // Parses a comma-separated list of module exports. + + pp$8.parseExportSpecifier = function(exports) { + var node = this.startNode(); + node.local = this.parseModuleExportName(); + + node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; + this.checkExport( + exports, + node.exported, + node.exported.start + ); + + return this.finishNode(node, "ExportSpecifier") + }; + + pp$8.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseExportSpecifier(exports)); + } + return nodes + }; + + // Parses import declaration. + + pp$8.parseImport = function(node) { + this.next(); + + // import '...' + if (this.type === types$1.string) { + node.specifiers = empty$1; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") + }; + + // Parses a comma-separated list of module imports. + + pp$8.parseImportSpecifier = function() { + var node = this.startNode(); + node.imported = this.parseModuleExportName(); + + if (this.eatContextual("as")) { + node.local = this.parseIdent(); + } else { + this.checkUnreserved(node.imported); + node.local = node.imported; + } + this.checkLValSimple(node.local, BIND_LEXICAL); + + return this.finishNode(node, "ImportSpecifier") + }; + + pp$8.parseImportDefaultSpecifier = function() { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportDefaultSpecifier") + }; + + pp$8.parseImportNamespaceSpecifier = function() { + var node = this.startNode(); + this.next(); + this.expectContextual("as"); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportNamespaceSpecifier") + }; + + pp$8.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types$1.name) { + nodes.push(this.parseImportDefaultSpecifier()); + if (!this.eat(types$1.comma)) { return nodes } + } + if (this.type === types$1.star) { + nodes.push(this.parseImportNamespaceSpecifier()); + return nodes + } + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseImportSpecifier()); + } + return nodes + }; + + pp$8.parseModuleExportName = function() { + if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { + var stringLiteral = this.parseLiteral(this.value); + if (loneSurrogate.test(stringLiteral.value)) { + this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); + } + return stringLiteral + } + return this.parseIdent(true) + }; + + // Set `ExpressionStatement#directive` property for directive prologues. + pp$8.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } + }; + pp$8.isDirectiveCandidate = function(statement) { + return ( + this.options.ecmaVersion >= 5 && + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) + }; + + var pp$7 = Parser.prototype; + + // Convert existing expression atom to assignable pattern + // if possible. + + pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (!isBinding) { break } + + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node + }; + + // Convert list of expression atoms to binding list. + + pp$7.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList + }; + + // Parses spread element. + + pp$7.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") + }; + + pp$7.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types$1.name) + { this.unexpected(); } + + node.argument = this.parseBindingAtom(); + + return this.finishNode(node, "RestElement") + }; + + // Parses lvalue (assignable) atom. + + pp$7.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types$1.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types$1.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") + + case types$1.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() + }; + + pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this.expect(types$1.comma); } + if (allowEmpty && this.type === types$1.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break + } else if (this.type === types$1.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } + this.expect(close); + break + } else { + elts.push(this.parseAssignableListItem(allowModifiers)); + } + } + return elts + }; + + pp$7.parseAssignableListItem = function(allowModifiers) { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + return elem + }; + + pp$7.parseBindingListItem = function(param) { + return param + }; + + // Parses assignment pattern around given atom if possible. + + pp$7.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") + }; + + // The following three functions all verify that a node is an lvalue — + // something that can be bound, or assigned to. In order to do so, they perform + // a variety of checks: + // + // - Check that none of the bound/assigned-to identifiers are reserved words. + // - Record name declarations for bindings in the appropriate scope. + // - Check duplicate argument names, if checkClashes is set. + // + // If a complex binding pattern is encountered (e.g., object and array + // destructuring), the entire pattern is recursively checked. + // + // There are three versions of checkLVal*() appropriate for different + // circumstances: + // + // - checkLValSimple() shall be used if the syntactic construct supports + // nothing other than identifiers and member expressions. Parenthesized + // expressions are also correctly handled. This is generally appropriate for + // constructs for which the spec says + // + // > It is a Syntax Error if AssignmentTargetType of [the production] is not + // > simple. + // + // It is also appropriate for checking if an identifier is valid and not + // defined elsewhere, like import declarations or function/class identifiers. + // + // Examples where this is used include: + // a += …; + // import a from '…'; + // where a is the node to be checked. + // + // - checkLValPattern() shall be used if the syntactic construct supports + // anything checkLValSimple() supports, as well as object and array + // destructuring patterns. This is generally appropriate for constructs for + // which the spec says + // + // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor + // > an ArrayLiteral and AssignmentTargetType of [the production] is not + // > simple. + // + // Examples where this is used include: + // (a = …); + // const a = …; + // try { … } catch (a) { … } + // where a is the node to be checked. + // + // - checkLValInnerPattern() shall be used if the syntactic construct supports + // anything checkLValPattern() supports, as well as default assignment + // patterns, rest elements, and other constructs that may appear within an + // object or array destructuring pattern. + // + // As a special case, function parameters also use checkLValInnerPattern(), + // as they also support defaults and rest constructs. + // + // These functions deliberately support both assignment and binding constructs, + // as the logic for both is exceedingly similar. If the node is the target of + // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it + // should be set to the appropriate BIND_* constant, like BIND_VAR or + // BIND_LEXICAL. + // + // If the function is called with a non-BIND_NONE bindingType, then + // additionally a checkClashes object may be specified to allow checking for + // duplicate argument names. checkClashes is ignored if the provided construct + // is an assignment (i.e., bindingType is BIND_NONE). + + pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + var isBind = bindingType !== BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (checkClashes) { + if (hasOwn(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + } + break + + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ParenthesizedExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } + return this.checkLValSimple(expr.expression, bindingType, checkClashes) + + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } + }; + + pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break + + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } + } + break + + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } + }; + + pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Property": + // AssignmentProperty has type === "Property" + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break + + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break + + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } + }; + + // The algorithm used to determine whether a regexp can appear at a + // given point in the program is loosely based on sweet.js' approach. + // See https://github.com/mozilla/sweet.js/wiki/design + + + var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; + }; + + var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) + }; + + var pp$6 = Parser.prototype; + + pp$6.initialContext = function() { + return [types.b_stat] + }; + + pp$6.curContext = function() { + return this.context[this.context.length - 1] + }; + + pp$6.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types.f_expr || parent === types.f_stat) + { return true } + if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) + { return true } + if (prevType === types$1.braceL) + { return parent === types.b_stat } + if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) + { return false } + return !this.exprAllowed + }; + + pp$6.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") + { return context.generator } + } + return false + }; + + pp$6.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types$1.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } + }; + + // Used to handle egde cases when token context could not be inferred correctly during tokenization phase + + pp$6.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } + }; + + // Token-specific context update code + + types$1.parenR.updateContext = types$1.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; + }; + + types$1.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); + this.exprAllowed = true; + }; + + types$1.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl); + this.exprAllowed = true; + }; + + types$1.parenL.updateContext = function(prevType) { + var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; + this.context.push(statementParens ? types.p_stat : types.p_expr); + this.exprAllowed = true; + }; + + types$1.incDec.updateContext = function() { + // tokExprAllowed stays unchanged + }; + + types$1._function.updateContext = types$1._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types$1._else && + !(prevType === types$1.semi && this.curContext() !== types.p_stat) && + !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) + { this.context.push(types.f_expr); } + else + { this.context.push(types.f_stat); } + this.exprAllowed = false; + }; + + types$1.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types.q_tmpl); } + this.exprAllowed = false; + }; + + types$1.star.updateContext = function(prevType) { + if (prevType === types$1._function) { + var index = this.context.length - 1; + if (this.context[index] === types.f_expr) + { this.context[index] = types.f_expr_gen; } + else + { this.context[index] = types.f_gen; } + } + this.exprAllowed = true; + }; + + types$1.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } + } + this.exprAllowed = allowed; + }; + + // A recursive descent parser operates by defining functions for all + // syntactic elements, and recursively calling those, each function + // advancing the input stream and returning an AST node. Precedence + // of constructs (for example, the fact that `!x[1]` means `!(x[1])` + // instead of `(!x)[1]` is handled by the fact that the parser + // function that parses unary prefix operators is called first, and + // in turn calls the function that parses `[]` subscripts — that + // way, it'll receive the node for `x[1]` already parsed, and wraps + // *that* in the unary operator node. + // + // Acorn uses an [operator precedence parser][opp] to handle binary + // operator precedence, because it is much more compact than using + // the technique outlined above, which uses different, nesting + // functions to specify precedence, for all of the ten binary + // precedence levels that JavaScript defines. + // + // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + + + var pp$5 = Parser.prototype; + + // Check if property name clashes with already added. + // Object/class getters and setters are not allowed to clash — + // either with each other or with an init property — and in + // strict mode, init properties are also not allowed to be repeated. + + pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) { + refDestructuringErrors.doubleProto = key.start; + } + } else { + this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); + } + } + propHash.proto = true; + } + return + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; + }; + + // ### Expression parsing + + // These nest, from the most general expression type at the top to + // 'atomic', nondivisible expression types at the bottom. Most of + // the functions will simply let the function(s) below them parse, + // and, *if* the syntactic construct they handle is present, wrap + // the AST node that the inner parser gave them in another node. + + // Parse a full expression. The optional arguments are used to + // forbid the `in` operator (in for loops initalization expressions) + // and provide reference for storing '=' operator inside shorthand + // property assignment in contexts where both object expression + // and object pattern might appear (so it's possible to raise + // delayed syntax error at correct position). + + pp$5.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types$1.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr + }; + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(forInit) } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } + } + + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } + + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types$1.parenL || this.type === types$1.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types$1.eq) + { left = this.toAssignable(left, false, refDestructuringErrors); } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly + if (this.type === types$1.eq) + { this.checkLValPattern(left); } + else + { this.checkLValSimple(left); } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + return left + }; + + // Parse a ternary conditional (`?:`) operator. + + pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types$1.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types$1.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression") + } + return expr + }; + + // Start the precedence parser. + + pp$5.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) + }; + + // Parse binary operators with the operator precedence parsing + // algorithm. `left` is the left-hand side of the operator. + // `minPrec` provides context that allows the function to stop and + // defer further parser to one of its callers when it encounters an + // operator that has a lower precedence than the set it is parsing. + + pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types$1._in)) { + if (prec > minPrec) { + var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; + var coalesce = this.type === types$1.coalesce; + if (coalesce) { + // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. + // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. + prec = types$1.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) + } + } + return left + }; + + pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { + if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") + }; + + // Parse unary operators, both prefix and postfix. + + pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types$1.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLValSimple(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) + { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else if (!sawUnary && this.type === types$1.privateId) { + if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); } + expr = this.parsePrivateIdent(); + // only could be private fields in 'in', such as #x in obj + if (this.type !== types$1._in) { this.unexpected(); } + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + + if (!incDec && this.eat(types$1.starstar)) { + if (sawUnary) + { this.unexpected(this.lastTokStart); } + else + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } + } else { + return expr + } + }; + + function isPrivateFieldAccess(node) { + return ( + node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || + node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) + ) + } + + // Parse call, dot, and `[]`-subscript expressions. + + pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } + } + return result + }; + + pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && + this.potentialArrowAt === base.start; + var optionalChained = false; + + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + + if (element.optional) { optionalChained = true; } + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element + } + + base = element; + } + }; + + pp$5.shouldParseAsyncArrow = function() { + return !this.canInsertSemicolon() && this.eat(types$1.arrow) + }; + + pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) + }; + + pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types$1.questionDot); + if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + + var computed = this.eat(types$1.bracketL); + if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types$1.bracketR); + } else if (this.type === types$1.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types$1.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types$1.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({isTagged: true}); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base + }; + + // Parse an atomic expression — either a single token that is an + // expression, an expression started by a keyword like `function` or + // `new`, or an expression wrapped in punctuation like `()`, `[]`, + // or `{}`. + + pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types$1.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types$1._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types$1.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super ( Arguments ) + if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types$1._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types$1.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { + this.overrideContext(types.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types$1.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && + (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) + } + } + return id + + case types$1.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node + + case types$1.num: case types$1.string: + return this.parseLiteral(this.value) + + case types$1._null: case types$1._true: case types$1._false: + node = this.startNode(); + node.value = this.type === types$1._null ? null : this.type === types$1._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types$1.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr + + case types$1.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") + + case types$1.braceL: + this.overrideContext(types.b_expr); + return this.parseObj(false, refDestructuringErrors) + + case types$1._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) + + case types$1._class: + return this.parseClass(this.startNode(), false) + + case types$1._new: + return this.parseNew() + + case types$1.backQuote: + return this.parseTemplate() + + case types$1._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport(forNew) + } else { + return this.unexpected() + } + + default: + return this.parseExprAtomDefault() + } + }; + + pp$5.parseExprAtomDefault = function() { + this.unexpected(); + }; + + pp$5.parseExprImport = function(forNew) { + var node = this.startNode(); + + // Consume `import` as an identifier for `import.meta`. + // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } + var meta = this.parseIdent(true); + + if (this.type === types$1.parenL && !forNew) { + return this.parseDynamicImport(node) + } else if (this.type === types$1.dot) { + node.meta = meta; + return this.parseImportMeta(node) + } else { + this.unexpected(); + } + }; + + pp$5.parseDynamicImport = function(node) { + this.next(); // skip `(` + + // Parse node.source. + node.source = this.parseMaybeAssign(); + + // Verify ending. + if (!this.eat(types$1.parenR)) { + var errorPos = this.start; + if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + + return this.finishNode(node, "ImportExpression") + }; + + pp$5.parseImportMeta = function(node) { + this.next(); // skip `.` + + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + + if (node.property.name !== "meta") + { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) + { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + + return this.finishNode(node, "MetaProperty") + }; + + pp$5.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } + this.next(); + return this.finishNode(node, "Literal") + }; + + pp$5.parseParenExpression = function() { + this.expect(types$1.parenL); + var val = this.parseExpression(); + this.expect(types$1.parenR); + return val + }; + + pp$5.shouldParseArrow = function(exprList) { + return !this.canInsertSemicolon() + }; + + pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + // Do not save awaitIdentPos to allow checking awaits nested in parameters + while (this.type !== types$1.parenR) { + first ? first = false : this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { + lastIsComma = true; + break + } else if (this.type === types$1.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types$1.comma) { + this.raiseRecoverable( + this.start, + "Comma is not permitted after the rest element" + ); + } + break + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types$1.parenR); + + if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit) + } + + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val + } + }; + + pp$5.parseParenItem = function(item) { + return item + }; + + pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) + }; + + // New's precedence is slightly tricky. It must allow its argument to + // be a `[]` or dot subscript expression, but not a call — at least, + // not without wrapping it in parentheses. Thus, it uses the noCalls + // argument to parseSubscripts to prevent it from consuming the + // argument list. + + var empty = []; + + pp$5.parseNew = function() { + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } + var node = this.startNode(); + var meta = this.parseIdent(true); + if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) { + node.meta = meta; + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } + if (!this.allowNewDotTarget) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc; + node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); + if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty; } + return this.finishNode(node, "NewExpression") + }; + + // Parse template expression. + + pp$5.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types$1.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types$1.backQuote; + return this.finishNode(elem, "TemplateElement") + }; + + pp$5.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } + this.expect(types$1.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types$1.braceR); + node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); + } + this.next(); + return this.finishNode(node, "TemplateLiteral") + }; + + pp$5.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + // Parse an object literal or binding pattern. + + pp$5.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") + }; + + pp$5.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types$1.star); } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); + this.parsePropertyName(prop); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") + }; + + pp$5.parseGetterSetter = function(prop) { + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } + }; + + pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types$1.colon) + { this.unexpected(); } + + if (this.eat(types$1.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { + if (isPattern) { this.unexpected(); } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { + if (isGenerator || isAsync) { this.unexpected(); } + this.parseGetterSetter(prop); + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { this.unexpected(); } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = startPos; } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types$1.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { this.unexpected(); } + }; + + pp$5.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types$1.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types$1.bracketR); + return prop.key + } else { + prop.computed = false; + } + } + return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") + }; + + // Initialize empty function node. + + pp$5.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } + }; + + // Parse object or class method. + + pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; + + // Parse arrow function expression with given parameters. + + pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; + + // Parse function body and check parameters. + + pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types$1.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(forInit); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } + node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); + }; + + pp$5.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true + }; + + // Checks function params for various disallowed patterns such as using "eval" + // or "arguments" and duplicate parameters. + + pp$5.checkParams = function(node, allowDuplicates) { + var nameHash = Object.create(null); + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } + }; + + // Parses a comma-separated list of expressions, and returns them as + // an array. `close` is the token type that ends the list, and + // `allowEmpty` can be turned on to allow subsequent commas with + // nothing in between them to be parsed as `null` (which is needed + // for array literals). + + pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this.type === types$1.comma) + { elt = null; } + else if (this.type === types$1.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this.start; } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts + }; + + pp$5.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } + if (this.currentThisScope().inClassFieldInit && name === "arguments") + { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) + { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); + } + }; + + // Parse the next token as an identifier. If `liberal` is true (used + // when parsing properties), it will also convert keywords into + // identifiers. + + pp$5.parseIdent = function(liberal) { + var node = this.parseIdentNode(); + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node + }; + + pp$5.parseIdentNode = function() { + var node = this.startNode(); + if (this.type === types$1.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + } else { + this.unexpected(); + } + return node + }; + + pp$5.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types$1.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + + // For validating existence + if (this.options.checkPrivateFields) { + if (this.privateNameStack.length === 0) { + this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + } + + return node + }; + + // Parses yield expression inside generator. + + pp$5.parseYield = function(forInit) { + if (!this.yieldPos) { this.yieldPos = this.start; } + + var node = this.startNode(); + this.next(); + if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types$1.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression") + }; + + pp$5.parseAwait = function(forInit) { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node, "AwaitExpression") + }; + + var pp$4 = Parser.prototype; + + // This function is used to raise exceptions on parse errors. It + // takes an offset integer (into the current `input`) to indicate + // the location of the error, attaches the position to the end + // of the error message, and then raises a `SyntaxError` with that + // message. + + pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err + }; + + pp$4.raiseRecoverable = pp$4.raise; + + pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } + }; + + var pp$3 = Parser.prototype; + + var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; + // A list of lexically-declared FunctionDeclaration names in the current lexical scope + this.functions = []; + // A switch to disallow the identifier reference 'arguments' + this.inClassFieldInit = false; + }; + + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + + pp$3.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; + + pp$3.exitScope = function() { + this.scopeStack.pop(); + }; + + // The spec says: + // > At the top level of a function, or script, function declarations are + // > treated like var declarations rather than like lexical declarations. + pp$3.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) + }; + + pp$3.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && (scope.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) + { redeclared = scope$2.lexical.indexOf(name) > -1; } + else + { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || + !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break + } + scope$3.var.push(name); + if (this.inModule && (scope$3.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + if (scope$3.flags & SCOPE_VAR) { break } + } + } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } + }; + + pp$3.checkLocalExport = function(id) { + // scope.functions must be empty as Module code is always strict. + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && + this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; + } + }; + + pp$3.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; + + pp$3.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } + } + }; + + // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. + pp$3.currentThisScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } + } + }; + + var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } + }; + + // Start an AST node, attaching a start offset. + + var pp$2 = Parser.prototype; + + pp$2.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; + + pp$2.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) + }; + + // Finish an AST node, adding `type` and `end` properties. + + function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node + } + + pp$2.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; + + // Finish node at given position + + pp$2.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; + + pp$2.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode + }; + + // This file contains Unicode properties extracted from the ECMAScript specification. + // The lists are extracted like so: + // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) + + // #table-binary-unicode-properties + var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; + var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; + var ecma11BinaryProperties = ecma10BinaryProperties; + var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; + var ecma13BinaryProperties = ecma12BinaryProperties; + var ecma14BinaryProperties = ecma13BinaryProperties; + + var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties, + 13: ecma13BinaryProperties, + 14: ecma14BinaryProperties + }; + + // #table-binary-unicode-properties-of-strings + var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; + + var unicodeBinaryPropertiesOfStrings = { + 9: "", + 10: "", + 11: "", + 12: "", + 13: "", + 14: ecma14BinaryPropertiesOfStrings + }; + + // #table-unicode-general-category-values + var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; + + // #table-unicode-script-values + var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; + var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; + var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; + var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; + var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; + var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz"; + + var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues, + 13: ecma13ScriptValues, + 14: ecma14ScriptValues + }; + + var data = {}; + function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; + } + + for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) { + var ecmaVersion = list[i]; + + buildUnicodeData(ecmaVersion); + } + + var pp$1 = Parser.prototype; + + var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchV = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; + }; + + RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicodeSets = flags.indexOf("v") !== -1; + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + if (unicodeSets && this.parser.options.ecmaVersion >= 15) { + this.switchU = true; + this.switchV = true; + this.switchN = true; + } else { + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchV = false; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + } + }; + + RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); + }; + + // If u flag is given, this returns the code point at the index (it combines a surrogate pair). + // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). + RegExpValidationState.prototype.at = function at (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c + } + var next = s.charCodeAt(i + 1); + return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c + }; + + RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 + } + return i + 2 + }; + + RegExpValidationState.prototype.current = function current (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.pos, forceU) + }; + + RegExpValidationState.prototype.lookahead = function lookahead (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.nextIndex(this.pos, forceU), forceU) + }; + + RegExpValidationState.prototype.advance = function advance (forceU) { + if ( forceU === void 0 ) forceU = false; + + this.pos = this.nextIndex(this.pos, forceU); + }; + + RegExpValidationState.prototype.eat = function eat (ch, forceU) { + if ( forceU === void 0 ) forceU = false; + + if (this.current(forceU) === ch) { + this.advance(forceU); + return true + } + return false + }; + + RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) { + if ( forceU === void 0 ) forceU = false; + + var pos = this.pos; + for (var i = 0, list = chs; i < list.length; i += 1) { + var ch = list[i]; + + var current = this.at(pos, forceU); + if (current === -1 || current !== ch) { + return false + } + pos = this.nextIndex(pos, forceU); + } + this.pos = pos; + return true + }; + + /** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + + var u = false; + var v = false; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + if (flag === "u") { u = true; } + if (flag === "v") { v = true; } + } + if (this.options.ecmaVersion >= 15 && u && v) { + this.raise(state.start, "Invalid regular expression flag"); + } + }; + + /** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern + pp$1.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction + pp$1.regexp_disjunction = function(state) { + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + this.regexp_alternative(state); + } + + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative + pp$1.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) + { } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term + pp$1.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } + + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion + pp$1.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } + + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } + + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } + + state.pos = start; + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier + pp$1.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; + + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix + pp$1.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) + }; + pp$1.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom + pp$1.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) + }; + pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true + } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom + pp$1.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier + pp$1.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter + pp$1.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter + // But eat eager. + pp$1.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter + pp$1.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false + }; + + // GroupSpecifier :: + // [empty] + // `?` GroupName + pp$1.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); + } + state.groupNames.push(state.lastStringValue); + return + } + state.raise("Invalid group"); + } + }; + + // GroupName :: + // `<` RegExpIdentifierName `>` + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); + } + return false + }; + + // RegExpIdentifierName :: + // RegExpIdentifierStart + // RegExpIdentifierName RegExpIdentifierPart + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true + } + return false + }; + + // RegExpIdentifierStart :: + // UnicodeIDStart + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + pp$1.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ + } + + // RegExpIdentifierPart :: + // UnicodeIDContinue + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + // + // + pp$1.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape + pp$1.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false + }; + pp$1.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape + pp$1.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) + }; + pp$1.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape + pp$1.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter + pp$1.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence + pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if ( forceU === void 0 ) forceU = false; + + var start = state.pos; + var switchU = forceU || state.switchU; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true + } + if ( + switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + + return false + }; + function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape + pp$1.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false + } + + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape + pp$1.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false + }; + + // Return values used by character set parsing methods, needed to + // forbid negation of sets that can match strings. + var CharSetNone = 0; // Nothing parsed + var CharSetOk = 1; // Construct parsed, cannot contain strings + var CharSetString = 2; // Construct parsed, can contain strings + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape + pp$1.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return CharSetOk + } + + var negate = false; + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + var result; + if ( + state.eat(0x7B /* { */) && + (result = this.regexp_eatUnicodePropertyValueExpression(state)) && + state.eat(0x7D /* } */) + ) { + if (negate && result === CharSetString) { state.raise("Invalid property name"); } + return result + } + state.raise("Invalid property name"); + } + + return CharSetNone + }; + + function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) + } + + // UnicodePropertyValueExpression :: + // UnicodePropertyName `=` UnicodePropertyValue + // LoneUnicodePropertyNameOrValue + pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return CharSetOk + } + } + state.pos = start; + + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) + } + return CharSetNone + }; + + pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!hasOwn(state.unicodeProperties.nonBinary, name)) + { state.raise("Invalid property name"); } + if (!state.unicodeProperties.nonBinary[name].test(value)) + { state.raise("Invalid property value"); } + }; + + pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk } + if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString } + state.raise("Invalid property name"); + }; + + // UnicodePropertyName :: + // UnicodePropertyNameCharacters + pp$1.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + + function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ + } + + // UnicodePropertyValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) + } + + // LoneUnicodePropertyNameOrValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass + pp$1.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (!state.eat(0x5D /* ] */)) + { state.raise("Unterminated character class"); } + if (negate && result === CharSetString) + { state.raise("Negated character class may contain strings"); } + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassContents + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges + pp$1.regexp_classContents = function(state) { + if (state.current() === 0x5D /* ] */) { return CharSetOk } + if (state.switchV) { return this.regexp_classSetExpression(state) } + this.regexp_nonEmptyClassRanges(state); + return CharSetOk + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash + pp$1.regexp_nonEmptyClassRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash + pp$1.regexp_eatClassAtom = function(state) { + var start = state.pos; + + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + + var ch = state.current(); + if (ch !== 0x5D /* ] */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape + pp$1.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } + + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } + + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) + }; + + // https://tc39.es/ecma262/#prod-ClassSetExpression + // https://tc39.es/ecma262/#prod-ClassUnion + // https://tc39.es/ecma262/#prod-ClassIntersection + // https://tc39.es/ecma262/#prod-ClassSubtraction + pp$1.regexp_classSetExpression = function(state) { + var result = CharSetOk, subResult; + if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) { + if (subResult === CharSetString) { result = CharSetString; } + // https://tc39.es/ecma262/#prod-ClassIntersection + var start = state.pos; + while (state.eatChars([0x26, 0x26] /* && */)) { + if ( + state.current() !== 0x26 /* & */ && + (subResult = this.regexp_eatClassSetOperand(state)) + ) { + if (subResult !== CharSetString) { result = CharSetOk; } + continue + } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + // https://tc39.es/ecma262/#prod-ClassSubtraction + while (state.eatChars([0x2D, 0x2D] /* -- */)) { + if (this.regexp_eatClassSetOperand(state)) { continue } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + } else { + state.raise("Invalid character in character class"); + } + // https://tc39.es/ecma262/#prod-ClassUnion + for (;;) { + if (this.regexp_eatClassSetRange(state)) { continue } + subResult = this.regexp_eatClassSetOperand(state); + if (!subResult) { return result } + if (subResult === CharSetString) { result = CharSetString; } + } + }; + + // https://tc39.es/ecma262/#prod-ClassSetRange + pp$1.regexp_eatClassSetRange = function(state) { + var start = state.pos; + if (this.regexp_eatClassSetCharacter(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) { + var right = state.lastIntValue; + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + return true + } + state.pos = start; + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetOperand + pp$1.regexp_eatClassSetOperand = function(state) { + if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk } + return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state) + }; + + // https://tc39.es/ecma262/#prod-NestedClass + pp$1.regexp_eatNestedClass = function(state) { + var start = state.pos; + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (state.eat(0x5D /* ] */)) { + if (negate && result === CharSetString) { + state.raise("Negated character class may contain strings"); + } + return result + } + state.pos = start; + } + if (state.eat(0x5C /* \ */)) { + var result$1 = this.regexp_eatCharacterClassEscape(state); + if (result$1) { + return result$1 + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunction + pp$1.regexp_eatClassStringDisjunction = function(state) { + var start = state.pos; + if (state.eatChars([0x5C, 0x71] /* \q */)) { + if (state.eat(0x7B /* { */)) { + var result = this.regexp_classStringDisjunctionContents(state); + if (state.eat(0x7D /* } */)) { + return result + } + } else { + // Make the same message as V8. + state.raise("Invalid escape"); + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents + pp$1.regexp_classStringDisjunctionContents = function(state) { + var result = this.regexp_classString(state); + while (state.eat(0x7C /* | */)) { + if (this.regexp_classString(state) === CharSetString) { result = CharSetString; } + } + return result + }; + + // https://tc39.es/ecma262/#prod-ClassString + // https://tc39.es/ecma262/#prod-NonEmptyClassString + pp$1.regexp_classString = function(state) { + var count = 0; + while (this.regexp_eatClassSetCharacter(state)) { count++; } + return count === 1 ? CharSetOk : CharSetString + }; + + // https://tc39.es/ecma262/#prod-ClassSetCharacter + pp$1.regexp_eatClassSetCharacter = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if ( + this.regexp_eatCharacterEscape(state) || + this.regexp_eatClassSetReservedPunctuator(state) + ) { + return true + } + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + state.pos = start; + return false + } + var ch = state.current(); + if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false } + if (isClassSetSyntaxCharacter(ch)) { return false } + state.advance(); + state.lastIntValue = ch; + return true + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator + function isClassSetReservedDoublePunctuatorCharacter(ch) { + return ( + ch === 0x21 /* ! */ || + ch >= 0x23 /* # */ && ch <= 0x26 /* & */ || + ch >= 0x2A /* * */ && ch <= 0x2C /* , */ || + ch === 0x2E /* . */ || + ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ || + ch === 0x5E /* ^ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter + function isClassSetSyntaxCharacter(ch) { + return ( + ch === 0x28 /* ( */ || + ch === 0x29 /* ) */ || + ch === 0x2D /* - */ || + ch === 0x2F /* / */ || + ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + pp$1.regexp_eatClassSetReservedPunctuator = function(state) { + var ch = state.current(); + if (isClassSetReservedPunctuator(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + function isClassSetReservedPunctuator(ch) { + return ( + ch === 0x21 /* ! */ || + ch === 0x23 /* # */ || + ch === 0x25 /* % */ || + ch === 0x26 /* & */ || + ch === 0x2C /* , */ || + ch === 0x2D /* - */ || + ch >= 0x3A /* : */ && ch <= 0x3E /* > */ || + ch === 0x40 /* @ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter + pp$1.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits + pp$1.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } + return state.pos !== start + }; + function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits + pp$1.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start + }; + function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) + } + function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) + } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence + // Allows only 0-377(octal) i.e. 0-255(decimal). + pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit + pp$1.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false + }; + function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit + // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true + }; + + // Object type used to represent tokens. Note that normally, tokens + // simply exist as properties on the parser object. This is only + // used for the onToken callback and the external tokenizer. + + var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } + }; + + // ## Tokenizer + + var pp = Parser.prototype; + + // Move to the next token + + pp.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) + { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } + if (this.options.onToken) + { this.options.onToken(new Token(this)); } + + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); + }; + + pp.getToken = function() { + this.next(); + return new Token(this) + }; + + // If we're in an ES6 environment, make parsers iterable + if (typeof Symbol !== "undefined") + { pp[Symbol.iterator] = function() { + var this$1$1 = this; + + return { + next: function () { + var token = this$1$1.getToken(); + return { + done: token.type === types$1.eof, + value: token + } + } + } + }; } + + // Toggle strict mode. Re-reads the next number or string to please + // pedantic tests (`"use strict"; 010;` should fail). + + // Read a single token, updating the parser object's token-related + // properties. + + pp.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } + + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } + + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } + }; + + pp.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } + + return this.getTokenFromCode(code) + }; + + pp.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xdc00) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 + }; + + pp.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } + }; + + pp.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } + }; + + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and. + + pp.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this.pos; + break + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: case 8232: case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break + case 47: // '/' + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: // '*' + this.skipBlockComment(); + break + case 47: + this.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop + } + } + } + }; + + // Called at the end of every token. Sets `end`, `val`, and + // maintains `context` and `exprAllowed`, and skips the space after + // the token, so that the next one's `start` will point at the + // right position. + + pp.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; + + this.updateContext(prevType); + }; + + // ### Token reading + + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + pp.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types$1.ellipsis) + } else { + ++this.pos; + return this.finishToken(types$1.dot) + } + }; + + pp.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.slash, 1) + }; + + pp.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types$1.star : types$1.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types$1.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + + if (next === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(tokentype, size) + }; + + pp.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { return this.finishOp(types$1.assign, 3) } + } + return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) + }; + + pp.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.bitwiseXOR, 1) + }; + + pp.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) + }; + + pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) +}; + +pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // ` +# Mime + +A comprehensive, compact MIME type module. + +[![Build Status](https://travis-ci.org/broofa/mime.svg?branch=master)](https://travis-ci.org/broofa/mime) + +## Install + +### NPM +``` +npm install mime +``` + +### Browser + +It is recommended that you use a bundler such as +[webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) to +package your code. However, browser-ready versions are available via +skypack.dev as follows: +``` +// Full version + +``` + +``` +// "lite" version + +``` + +## Quick Start + +For the full version (800+ MIME types, 1,000+ extensions): + +```javascript +const mime = require('mime'); + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getExtension('text/plain'); // ⇨ 'txt' +``` + +See [Mime API](#mime-api) below for API details. + +## Lite Version + +The "lite" version of this module omits vendor-specific (`*/vnd.*`) and +experimental (`*/x-*`) types. It weighs in at ~2.5KB, compared to 8KB for the +full version. To load the lite version: + +```javascript +const mime = require('mime/lite'); +``` + +## Mime .vs. mime-types .vs. mime-db modules + +For those of you wondering about the difference between these [popular] NPM modules, +here's a brief rundown ... + +[`mime-db`](https://github.com/jshttp/mime-db) is "the source of +truth" for MIME type information. It is not an API. Rather, it is a canonical +dataset of mime type definitions pulled from IANA, Apache, NGINX, and custom mappings +submitted by the Node.js community. + +[`mime-types`](https://github.com/jshttp/mime-types) is a thin +wrapper around mime-db that provides an API drop-in compatible(ish) with `mime @ < v1.3.6` API. + +`mime` is, as of v2, a self-contained module bundled with a pre-optimized version +of the `mime-db` dataset. It provides a simplified API with the following characteristics: + +* Intelligently resolved type conflicts (See [mime-score](https://github.com/broofa/mime-score) for details) +* Method naming consistent with industry best-practices +* Compact footprint. E.g. The minified+compressed sizes of the various modules: + +Module | Size +--- | --- +`mime-db` | 18 KB +`mime-types` | same as mime-db +`mime` | 8 KB +`mime/lite` | 2 KB + +## Mime API + +Both `require('mime')` and `require('mime/lite')` return instances of the MIME +class, documented below. + +Note: Inputs to this API are case-insensitive. Outputs (returned values) will +be lowercase. + +### new Mime(typeMap, ... more maps) + +Most users of this module will not need to create Mime instances directly. +However if you would like to create custom mappings, you may do so as follows +... + +```javascript +// Require Mime class +const Mime = require('mime/Mime'); + +// Define mime type -> extensions map +const typeMap = { + 'text/abc': ['abc', 'alpha', 'bet'], + 'text/def': ['leppard'] +}; + +// Create and use Mime instance +const myMime = new Mime(typeMap); +myMime.getType('abc'); // ⇨ 'text/abc' +myMime.getExtension('text/def'); // ⇨ 'leppard' +``` + +If more than one map argument is provided, each map is `define()`ed (see below), in order. + +### mime.getType(pathOrExtension) + +Get mime type for the given path or extension. E.g. + +```javascript +mime.getType('js'); // ⇨ 'application/javascript' +mime.getType('json'); // ⇨ 'application/json' + +mime.getType('txt'); // ⇨ 'text/plain' +mime.getType('dir/text.txt'); // ⇨ 'text/plain' +mime.getType('dir\\text.txt'); // ⇨ 'text/plain' +mime.getType('.text.txt'); // ⇨ 'text/plain' +mime.getType('.txt'); // ⇨ 'text/plain' +``` + +`null` is returned in cases where an extension is not detected or recognized + +```javascript +mime.getType('foo/txt'); // ⇨ null +mime.getType('bogus_type'); // ⇨ null +``` + +### mime.getExtension(type) +Get extension for the given mime type. Charset options (often included in +Content-Type headers) are ignored. + +```javascript +mime.getExtension('text/plain'); // ⇨ 'txt' +mime.getExtension('application/json'); // ⇨ 'json' +mime.getExtension('text/html; charset=utf8'); // ⇨ 'html' +``` + +### mime.define(typeMap[, force = false]) + +Define [more] type mappings. + +`typeMap` is a map of type -> extensions, as documented in `new Mime`, above. + +By default this method will throw an error if you try to map a type to an +extension that is already assigned to another type. Passing `true` for the +`force` argument will suppress this behavior (overriding any previous mapping). + +```javascript +mime.define({'text/x-abc': ['abc', 'abcd']}); + +mime.getType('abcd'); // ⇨ 'text/x-abc' +mime.getExtension('text/x-abc') // ⇨ 'abc' +``` + +## Command Line + + mime [path_or_extension] + +E.g. + + > mime scripts/jquery.js + application/javascript + +---- +Markdown generated from [src/README_js.md](src/README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/mime/cli.js b/node_modules/mime/cli.js new file mode 100644 index 0000000..ab70a49 --- /dev/null +++ b/node_modules/mime/cli.js @@ -0,0 +1,46 @@ +#!/usr/bin/env node + +'use strict'; + +process.title = 'mime'; +let mime = require('.'); +let pkg = require('./package.json'); +let args = process.argv.splice(2); + +if (args.includes('--version') || args.includes('-v') || args.includes('--v')) { + console.log(pkg.version); + process.exit(0); +} else if (args.includes('--name') || args.includes('-n') || args.includes('--n')) { + console.log(pkg.name); + process.exit(0); +} else if (args.includes('--help') || args.includes('-h') || args.includes('--h')) { + console.log(pkg.name + ' - ' + pkg.description + '\n'); + console.log(`Usage: + + mime [flags] [path_or_extension] + + Flags: + --help, -h Show this message + --version, -v Display the version + --name, -n Print the name of the program + + Note: the command will exit after it executes if a command is specified + The path_or_extension is the path to the file or the extension of the file. + + Examples: + mime --help + mime --version + mime --name + mime -v + mime src/log.js + mime new.py + mime foo.sh + `); + process.exit(0); +} + +let file = args[0]; +let type = mime.getType(file); + +process.stdout.write(type + '\n'); + diff --git a/node_modules/mime/index.js b/node_modules/mime/index.js new file mode 100644 index 0000000..fadcf8d --- /dev/null +++ b/node_modules/mime/index.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard'), require('./types/other')); diff --git a/node_modules/mime/lite.js b/node_modules/mime/lite.js new file mode 100644 index 0000000..835cffb --- /dev/null +++ b/node_modules/mime/lite.js @@ -0,0 +1,4 @@ +'use strict'; + +let Mime = require('./Mime'); +module.exports = new Mime(require('./types/standard')); diff --git a/node_modules/mime/package.json b/node_modules/mime/package.json new file mode 100644 index 0000000..84f5132 --- /dev/null +++ b/node_modules/mime/package.json @@ -0,0 +1,52 @@ +{ + "author": { + "name": "Robert Kieffer", + "url": "http://github.com/broofa", + "email": "robert@broofa.com" + }, + "engines": { + "node": ">=10.0.0" + }, + "bin": { + "mime": "cli.js" + }, + "contributors": [], + "description": "A comprehensive library for mime-type mapping", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "benchmark": "*", + "chalk": "4.1.2", + "eslint": "8.1.0", + "mime-db": "1.50.0", + "mime-score": "1.2.0", + "mime-types": "2.1.33", + "mocha": "9.1.3", + "runmd": "*", + "standard-version": "9.3.2" + }, + "files": [ + "index.js", + "lite.js", + "Mime.js", + "cli.js", + "/types" + ], + "scripts": { + "prepare": "node src/build.js && runmd --output README.md src/README_js.md", + "release": "standard-version", + "benchmark": "node src/benchmark.js", + "md": "runmd --watch --output README.md src/README_js.md", + "test": "mocha src/test.js" + }, + "keywords": [ + "util", + "mime" + ], + "name": "mime", + "repository": { + "url": "https://github.com/broofa/mime", + "type": "git" + }, + "version": "3.0.0" +} diff --git a/node_modules/mime/types/other.js b/node_modules/mime/types/other.js new file mode 100644 index 0000000..bb6a035 --- /dev/null +++ b/node_modules/mime/types/other.js @@ -0,0 +1 @@ +module.exports = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}; \ No newline at end of file diff --git a/node_modules/mime/types/standard.js b/node_modules/mime/types/standard.js new file mode 100644 index 0000000..5ee9937 --- /dev/null +++ b/node_modules/mime/types/standard.js @@ -0,0 +1 @@ +module.exports = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}; \ No newline at end of file diff --git a/node_modules/miniflare/README.md b/node_modules/miniflare/README.md new file mode 100644 index 0000000..3447949 --- /dev/null +++ b/node_modules/miniflare/README.md @@ -0,0 +1,652 @@ +# 🔥 Miniflare + +**Miniflare 3** is a simulator for developing and testing +[**Cloudflare Workers**](https://workers.cloudflare.com/), powered by +[`workerd`](https://github.com/cloudflare/workerd). + +> :warning: Miniflare 3 is API-only, and does not expose a CLI. Use Wrangler +> with `wrangler dev` to develop your Workers locally with Miniflare 3. + +## Quick Start + +```shell +$ npm install miniflare --save-dev +``` + +```js +import { Miniflare } from "miniflare"; + +// Create a new Miniflare instance, starting a workerd server +const mf = new Miniflare({ + script: `addEventListener("fetch", (event) => { + event.respondWith(new Response("Hello Miniflare!")); + })`, +}); + +// Send a request to the workerd server, the host is ignored +const response = await mf.dispatchFetch("http://localhost:8787/"); +console.log(await response.text()); // Hello Miniflare! + +// Cleanup Miniflare, shutting down the workerd server +await mf.dispose(); +``` + +## API + +### `type Awaitable` + +`T | Promise` + +Represents a value that can be `await`ed. Used in callback types to allow +`Promise`s to be returned if necessary. + +### `type Json` + +`string | number | boolean | null | Record | Json[]` + +Represents a JSON-serialisable value. + +### `type ModuleRuleType` + +`"ESModule" | "CommonJS" | "Text" | "Data" | "CompiledWasm"` + +Represents how a module's contents should be interpreted. + +- `"ESModule"`: interpret as + [ECMAScript module](https://tc39.es/ecma262/#sec-modules) +- `"CommonJS"`: interpret as + [CommonJS module](https://nodejs.org/api/modules.html#modules-commonjs-modules) +- `"Text"`: interpret as UTF8-encoded data, expose in runtime with + `string`-typed `default` export +- `"Data"`: interpret as arbitrary binary data, expose in runtime with + `ArrayBuffer`-typed `default` export +- `"CompiledWasm"`: interpret as binary WebAssembly module data, expose in + runtime with `WebAssembly.Module`-typed `default` export + +### `interface ModuleDefinition` + +Represents a manually defined module. + +- `type: ModuleRuleType` + + How this module's contents should be interpreted. + +- `path: string` + + Path of this module. The module's "name" will be obtained by converting this + to a relative path. The original path will be used to read `contents` if it's + omitted. + +- `contents?: string | Uint8Array` + + Contents override for this module. Binary data should be passed as + `Uint8Array`s. If omitted, will be read from `path`. + +### `interface ModuleRule` + +Represents a rule for identifying the `ModuleRuleType` of automatically located +modules. + +- `type: ModuleRuleType` + + How to interpret modules that match the `include` patterns. + +- `include: string[]` + + Glob patterns to match located module paths against (e.g. `["**/*.txt"]`). + +- `fallthrough?: boolean` + + If `true`, ignore any further rules of this `type`. This is useful for + disabling the built-in `ESModule` and `CommonJS` rules that match `*.mjs` and + `*.js`/`*.cjs` files respectively. + +### `type Persistence` + +`boolean | string | undefined` + +Represents where data should be persisted, if anywhere. + +- If this is `undefined` or `false`, data will be stored in-memory and only + persist between `Miniflare#setOptions()` calls, not restarts nor + `new Miniflare` instances. +- If this is `true`, data will be stored on the file-system, in the `$PWD/.mf` + directory. +- If this looks like a URL, then: + - If the protocol is `memory:`, data will be stored in-memory as above. + - If the protocol is `file:`, data will be stored on the file-system, in the + specified directory (e.g. `file:///path/to/directory`). +- Otherwise, if this is just a regular `string`, data will be stored on the + file-system, using the value as the directory path. + +### `enum LogLevel` + +`NONE, ERROR, WARN, INFO, DEBUG, VERBOSE` + +Controls which messages Miniflare logs. All messages at or below the selected +level will be logged. + +### `interface LogOptions` + +- `prefix?: string` + + String to add before the level prefix when logging messages. Defaults to `mf`. + +- `suffix?: string` + + String to add after the level prefix when logging messages. + +### `class Log` + +- `constructor(level?: LogLevel, opts?: LogOptions)` + + Creates a new logger that logs all messages at or below the specified level to + the `console`. + +- `error(message: Error)` + + Logs a message at the `ERROR` level. If the constructed log `level` is less + than `ERROR`, `throw`s the `message` instead. + +- `warn(message: string)` + + Logs a message at the `WARN` level. + +- `info(message: string)` + + Logs a message at the `INFO` level. + +- `debug(message: string)` + + Logs a message at the `DEBUG` level. + +- `verbose(message: string)` + + Logs a message at the `VERBOSE` level. + +### `class NoOpLog extends Log` + +- `constructor()` + + Creates a new logger that logs nothing to the `console`, and always `throw`s + `message`s logged at the `ERROR` level. + +### `interface QueueConsumerOptions` + +- `maxBatchSize?: number` + + Maximum number of messages allowed in each batch. Defaults to `5`. + +- `maxBatchTimeout?: number` + + Maximum number of seconds to wait for a full batch. If a message is sent, and + this timeout elapses, a partial batch will be dispatched. Defaults to `1`. + +- `maxRetries?: number` + + Maximum number of times to retry dispatching a message, if handling it throws, + or it is explicitly retried. Defaults to `2`. + +- `deadLetterQueue?: string` + + Name of another Queue to send a message on if it fails processing after + `maxRetries`. If this isn't specified, failed messages will be discarded. + +### `interface WorkerOptions` + +Options for an individual Worker/"nanoservice". All bindings are accessible on +the global scope in service-worker format Workers, or via the 2nd `env` +parameter in module format Workers. + +#### Core + +- `name?: string` + + Unique name for this worker. Only required if multiple `workers` are + specified. + +- `script?: string` + + JavaScript code for this worker. If this is a service worker format Worker, it + must not have any imports. If this is a modules format Worker, it must not + have any _npm_ imports, and `modules: true` must be set. If it does have + imports, `scriptPath` must also be set so Miniflare knows where to resolve + them relative to. + +- `scriptPath?: string` + + Path of JavaScript entrypoint. If this is a service worker format Worker, it + must not have any imports. If this is a modules format Worker, it must not + have any _npm_ imports, and `modules: true` must be set. + +- `modules?: boolean | ModuleDefinition[]` + + - If `true`, Miniflare will treat `script`/`scriptPath` as an ES Module and + automatically locate transitive module dependencies according to + `modulesRules`. Note that automatic location is not perfect: if the + specifier to a dynamic `import()` or `require()` is not a string literal, an + exception will be thrown. + + - If set to an array, modules can be defined manually. Transitive dependencies + must also be defined. Note the first module must be the entrypoint and have + type `"ESModule"`. + +- `modulesRoot?: string` + + If `modules` is set to `true` or an array, modules' "name"s will be their + `path`s relative to this value. This ensures file paths in stack traces are + correct. + + + + +- `modulesRules?: ModuleRule[]` + + Rules for identifying the `ModuleRuleType` of automatically located modules + when `modules: true` is set. Note the following default rules are always + included at the end: + + ```js + [ + { type: "ESModule", include: ["**/*.mjs"] }, + { type: "CommonJS", include: ["**/*.js", "**/*.cjs"] }, + ] + ``` + + > If `script` and `scriptPath` are set, and `modules` is set to an array, + > `modules` takes priority for a Worker's code, followed by `script`, then + > `scriptPath`. + + + +- `compatibilityDate?: string` + + [Compatibility date](https://developers.cloudflare.com/workers/platform/compatibility-dates/) + to use for this Worker. Defaults to a date far in the past. + +- `compatibilityFlags?: string[]` + + [Compatibility flags](https://developers.cloudflare.com/workers/platform/compatibility-dates/) + to use for this Worker. + +- `bindings?: Record` + + Record mapping binding name to arbitrary JSON-serialisable values to inject as + bindings into this Worker. + +- `wasmBindings?: Record` + + Record mapping binding name to paths containing binary WebAssembly module data + to inject as `WebAssembly.Module` bindings into this Worker. + +- `textBlobBindings?: Record` + + Record mapping binding name to paths containing UTF8-encoded data to inject as + `string` bindings into this Worker. + +- `dataBlobBindings?: Record` + + Record mapping binding name to paths containing arbitrary binary data to + inject as `ArrayBuffer` bindings into this Worker. + +- `serviceBindings?: Record Awaitable>` + + Record mapping binding name to service designators to inject as + `{ fetch: typeof fetch }` + [service bindings](https://developers.cloudflare.com/workers/platform/bindings/about-service-bindings/) + into this Worker. + + - If the designator is a `string`, requests will be dispatched to the Worker + with that `name`. + - If the designator is an object of the form `{ network: { ... } }`, where + `network` is a + [`workerd` `Network` struct](https://github.com/cloudflare/workerd/blob/bdbd6075c7c53948050c52d22f2dfa37bf376253/src/workerd/server/workerd.capnp#L555-L598), + requests will be dispatched according to the `fetch`ed URL. + - If the designator is an object of the form `{ external: { ... } }` where + `external` is a + [`workerd` `ExternalServer` struct](https://github.com/cloudflare/workerd/blob/bdbd6075c7c53948050c52d22f2dfa37bf376253/src/workerd/server/workerd.capnp#L504-L553), + requests will be dispatched to the specified remote server. + - If the designator is an object of the form `{ disk: { ... } }` where `disk` + is a + [`workerd` `DiskDirectory` struct](https://github.com/cloudflare/workerd/blob/bdbd6075c7c53948050c52d22f2dfa37bf376253/src/workerd/server/workerd.capnp#L600-L643), + requests will be dispatched to an HTTP service backed by an on-disk + directory. + - If the designator is a function, requests will be dispatched to your custom + handler. This allows you to access data and functions defined in Node.js + from your Worker. + +- `outboundService?: string | { network: Network } | { external: ExternalServer } | { disk: DiskDirectory } | (request: Request) => Awaitable` + + Dispatch this Worker's global `fetch()` and `connect()` requests to the + configured service. Service designators follow the same rules above for + `serviceBindings`. + +- `fetchMock?: import("undici").MockAgent` + + An [`undici` `MockAgent`](https://undici.nodejs.org/#/docs/api/MockAgent) to + dispatch this Worker's global `fetch()` requests through. + + > :warning: `outboundService` and `fetchMock` are mutually exclusive options. + > At most one of them may be specified per Worker. + +- `routes?: string[]` + + Array of route patterns for this Worker. These follow the same + [routing rules](https://developers.cloudflare.com/workers/platform/triggers/routes/#matching-behavior) + as deployed Workers. If no routes match, Miniflare will fallback to the Worker + defined first. + +#### Cache + +- `cache?: boolean` + + If `false`, default and named caches will be disabled. The Cache API will + still be available, it just won't cache anything. + +- `cacheWarnUsage?: boolean` + + If `true`, the first use of the Cache API will log a warning stating that the + Cache API is unsupported on `workers.dev` subdomains. + +#### Durable Objects + +- `durableObjects?: Record` + + Record mapping binding name to Durable Object class designators to inject as + `DurableObjectNamespace` bindings into this Worker. + + - If the designator is a `string`, it should be the name of a `class` exported + by this Worker. + - If the designator is an object, and `scriptName` is `undefined`, `className` + should be the name of a `class` exported by this Worker. + - Otherwise, `className` should be the name of a `class` exported by the + Worker with a `name` of `scriptName`. + +#### KV + +- `kvNamespaces?: Record | string[]` + + Record mapping binding name to KV namespace IDs to inject as `KVNamespace` + bindings into this Worker. Different Workers may bind to the same namespace ID + with different binding names. If a `string[]` of binding names is specified, + the binding name and KV namespace ID are assumed to be the same. + +- `sitePath?: string` + + Path to serve Workers Sites files from. If set, `__STATIC_CONTENT` and + `__STATIC_CONTENT_MANIFEST` bindings will be injected into this Worker. In + modules mode, `__STATIC_CONTENT_MANIFEST` will also be exposed as a module + with a `string`-typed `default` export, containing the JSON-stringified + manifest. Note Workers Sites files are never cached in Miniflare. + +- `siteInclude?: string[]` + + If set, only files with paths matching these glob patterns will be served. + +- `siteExclude?: string[]` + + If set, only files with paths _not_ matching these glob patterns will be + served. + +#### R2 + +- `r2Buckets?: Record | string[]` + + Record mapping binding name to R2 bucket names to inject as `R2Bucket` + bindings into this Worker. Different Workers may bind to the same bucket name + with different binding names. If a `string[]` of binding names is specified, + the binding name and bucket name are assumed to be the same. + +#### D1 + +- `d1Databases?: Record | string[]` + + Record mapping binding name to D1 database IDs to inject as `Fetcher` bindings + into this Worker. Note these bindings must be wrapped with a facade to provide + the expected `D1Database` API. Different Workers may bind to the same database + ID with different binding names. If a `string[]` of binding names is + specified, the binding name and database ID are assumed to be the same. + +#### Queues + +- `queueProducers?: Record | string[]` + + Record mapping binding name to queue names to inject as `WorkerQueue` bindings + into this Worker. Different Workers may bind to the same queue name with + different binding names. If a `string[]` of binding names is specified, the + binding name and queue name are assumed to be the same. + +- `queueConsumers?: Record | string[]` + + Record mapping queue name to consumer options. Messages enqueued on the + corresponding queues will be dispatched to this Worker. Note each queue can + have at most one consumer. If a `string[]` of queue names is specified, + default consumer options will be used. + +#### Analytics Engine + +_Not yet supported_ + +### `interface SharedOptions` + +Options shared between all Workers/"nanoservices". + +#### Core + +- `host?: string` + + Hostname that the `workerd` server should listen on. Defaults to `127.0.0.1`. + +- `port?: number` + + Port that the `workerd` server should listen on. Tries to default to `8787`, + but falls back to a random free port if this is in use. Note if a manually + specified port is in use, Miniflare throws an error, rather than attempting to + find a free port. + +- `https?: boolean` + + If `true`, start an HTTPS server using a pre-generated self-signed certificate + for `localhost`. Note this certificate is not valid for any other hostnames or + IP addresses. If you need to access the HTTPS server from another device, + you'll need to generate your own certificate and use the other `https*` + options below. + + ```shell + $ openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out cert.pem + ``` + + ```js + new Miniflare({ + httpsKeyPath: "key.pem", + httpsCertPath: "cert.pem", + }); + ``` + +- `httpsKey?: string` + + When one of `httpsCert` or `httpCertPath` is also specified, starts an HTTPS + server using the value of this option as the PEM encoded private key. + +- `httpsKeyPath?: string` + + When one of `httpsCert` or `httpCertPath` is also specified, starts an HTTPS + server using the PEM encoded private key stored at this file path. + +- `httpsCert?: string` + + When one of `httpsKey` or `httpsKeyPath` is also specified, starts an HTTPS + server using the value of this option as the PEM encoded certificate chain. + +- `httpsCertPath?: string` + + When one of `httpsKey` or `httpsKeyPath` is also specified, starts an HTTPS + server using the PEM encoded certificate chain stored at this file path. + +- `inspectorPort?: number` + + Port that `workerd` should start a DevTools inspector server on. Visit + `chrome://inspect` in a Chromium-based browser to connect to this. This can be + used to see detailed `console.log`s, profile CPU usage, and will eventually + allow step-through debugging. + +- `verbose?: boolean` + + Enable `workerd`'s `--verbose` flag for verbose logging. This can be used to + see simplified `console.log`s. + +- `log?: Log` + + Logger implementation for Miniflare's errors, warnings and informative + messages. + +- `upstream?: string` + + URL to use as the origin for incoming requests. If specified, all incoming + `request.url`s will be rewritten to start with this string. This is especially + useful when testing Workers that act as a proxy, and not as origins + themselves. + +- `cf?: boolean | string | Record` + + Controls the object returned from incoming `Request`'s `cf` property. + + - If set to a falsy value, an object with default placeholder values will be + used + - If set to an object, that object will be used + - If set to `true`, a real `cf` object will be fetched from a trusted + Cloudflare endpoint and cached in `node_modules/.mf` for 30 days + - If set to a `string`, a real `cf` object will be fetched and cached at the + provided path for 30 days + +- `liveReload?: boolean` + + If `true`, Miniflare will inject a script into HTML responses that + automatically reloads the page in-browser whenever the Miniflare instance's + options are updated. + +#### Cache, Durable Objects, KV, R2 and D1 + +- `cachePersist?: Persistence` + + Where to persist data cached in default or named caches. See docs for + `Persistence`. + +- `durableObjectsPersist?: Persistence` + + Where to persist data stored in Durable Objects. See docs for `Persistence`. + +- `kvPersist?: Persistence` + + Where to persist data stored in KV namespaces. See docs for `Persistence`. + +- `r2Persist?: Persistence` + + Where to persist data stored in R2 buckets. See docs for `Persistence`. + +- `d1Persist?: Persistence` + + Where to persist data stored in D1 databases. See docs for `Persistence`. + +#### Analytics Engine + +_Not yet supported_ + +### `type MiniflareOptions` + +`SharedOptions & (WorkerOptions | { workers: WorkerOptions[] })` + +Miniflare accepts either a single Worker configuration or multiple Worker +configurations in the `workers` array. When specifying an array of Workers, the +first Worker is designated the entrypoint and will receive all incoming HTTP +requests. Some options are shared between all workers and should always be +defined at the top-level. + +### `class Miniflare` + +- `constructor(opts: MiniflareOptions)` + + Creates a Miniflare instance and starts a new `workerd` server. Note unlike + Miniflare 2, Miniflare 3 _always_ starts a HTTP server listening on the + configured `host` and `port`: there are no `createServer`/`startServer` + functions. + +- `setOptions(opts: MiniflareOptions)` + + Updates the configuration for this Miniflare instance and restarts the + `workerd` server. Note unlike Miniflare 2, this does _not_ merge the new + configuration with the old configuration. Note that calling this function will + invalidate any existing values returned by the `Miniflare#get*()` methods, + preventing them from being used. + +- `ready: Promise` + + Returns a `Promise` that resolves with a `http` `URL` to the `workerd` server + once it has started and is able to accept requests. + +- `dispatchFetch(input: RequestInfo, init?: RequestInit): Promise` + + Sends a HTTP request to the `workerd` server, dispatching a `fetch` event in + the entrypoint Worker. Returns a `Promise` that resolves with the response. + Note that this implicitly waits for the `ready` `Promise` to resolve, there's + no need to do that yourself first. Additionally, the host of the request's URL + is always ignored and replaced with the `workerd` server's. + +- `getBindings = Record>(workerName?: string): Promise` + + Returns a `Promise` that resolves with a record mapping binding names to + bindings, for all bindings in the Worker with the specified `workerName`. If + `workerName` is not specified, defaults to the entrypoint Worker. + +- `getCaches(): Promise` + + Returns a `Promise` that resolves with the + [`CacheStorage`](https://developers.cloudflare.com/workers/runtime-apis/cache/) + instance of the entrypoint Worker. This means if `cache: false` is set on the + entrypoint, calling methods on the resolved value won't do anything. + +- `getD1Database(bindingName: string, workerName?: string): Promise` + + Returns a `Promise` that resolves with the + [`D1Database`](https://developers.cloudflare.com/d1/platform/client-api/) + instance corresponding to the specified `bindingName` of `workerName`. Note + `bindingName` must not begin with `__D1_BETA__`. If `workerName` is not + specified, defaults to the entrypoint Worker. + +- `getDurableObjectNamespace(bindingName: string, workerName?: string): Promise` + + Returns a `Promise` that resolves with the + [`DurableObjectNamespace`](https://developers.cloudflare.com/workers/runtime-apis/durable-objects/#access-a-durable-object-from-a-worker) + instance corresponding to the specified `bindingName` of `workerName`. If + `workerName` is not specified, defaults to the entrypoint Worker. + +- `getKVNamespace(bindingName: string, workerName?: string): Promise` + + Returns a `Promise` that resolves with the + [`KVNamespace`](https://developers.cloudflare.com/workers/runtime-apis/kv/) + instance corresponding to the specified `bindingName` of `workerName`. If + `workerName` is not specified, defaults to the entrypoint Worker. + +- `getQueueProducer(bindingName: string, workerName?: string): Promise>` + + Returns a `Promise` that resolves with the + [`Queue`](https://developers.cloudflare.com/queues/platform/javascript-apis/) + producer instance corresponding to the specified `bindingName` of + `workerName`. If `workerName` is not specified, defaults to the entrypoint + Worker. + +- `getR2Bucket(bindingName: string, workerName?: string): Promise` + + Returns a `Promise` that resolves with the + [`R2Bucket`](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/) + producer instance corresponding to the specified `bindingName` of + `workerName`. If `workerName` is not specified, defaults to the entrypoint + Worker. + +- `dispose(): Promise` + + Cleans up the Miniflare instance, and shuts down the `workerd` server. Note + that after this is called, `Miniflare#setOptions()` and + `Miniflare#dispatchFetch()` cannot be called. Additionally, calling this + function will invalidate any values returned by the `Miniflare#get*()` + methods, preventing them from being used. diff --git a/node_modules/miniflare/bootstrap.js b/node_modules/miniflare/bootstrap.js new file mode 100644 index 0000000..d75712e --- /dev/null +++ b/node_modules/miniflare/bootstrap.js @@ -0,0 +1,10 @@ +const { Log } = require("."); + +const log = new Log(); +log.error( + [ + "`miniflare@3` no longer includes a CLI. Please use `npx wrangler dev` instead.", + "As of `wrangler@3`, this will use Miniflare by default.", + "See https://miniflare.dev/get-started/migrating for more details.", + ].join("\n") +); diff --git a/node_modules/miniflare/dist/src/index.d.ts b/node_modules/miniflare/dist/src/index.d.ts new file mode 100644 index 0000000..361144e --- /dev/null +++ b/node_modules/miniflare/dist/src/index.d.ts @@ -0,0 +1,4239 @@ +/// + +import type { Abortable } from 'events'; +import type { AbortSignal as AbortSignal_2 } from '@cloudflare/workers-types/experimental'; +import type { Blob as Blob_2 } from '@cloudflare/workers-types/experimental'; +import { Blob as Blob_3 } from 'buffer'; +import { BodyInit } from 'undici'; +import type { CacheStorage } from '@cloudflare/workers-types/experimental'; +import type { D1Database } from '@cloudflare/workers-types/experimental'; +import { default as default_2 } from 'undici/types/mock-agent'; +import { Dispatcher } from 'undici'; +import type { DurableObjectNamespace } from '@cloudflare/workers-types/experimental'; +import { File } from 'undici'; +import type { File as File_2 } from '@cloudflare/workers-types/experimental'; +import { FormData } from 'undici'; +import { Headers } from 'undici'; +import type { Headers as Headers_2 } from '@cloudflare/workers-types/experimental'; +import { HeadersInit } from 'undici'; +import { IncomingRequestCfProperties } from '@cloudflare/workers-types/experimental'; +import type { KVNamespace } from '@cloudflare/workers-types/experimental'; +import { MockAgent } from 'undici'; +import NodeWebSocket from 'ws'; +import type { Queue } from '@cloudflare/workers-types/experimental'; +import type { R2Bucket } from '@cloudflare/workers-types/experimental'; +import type { ReadableStream } from '@cloudflare/workers-types/experimental'; +import { ReadableStream as ReadableStream_2 } from 'stream/web'; +import { ReferrerPolicy } from 'undici'; +import { Request as Request_2 } from 'undici'; +import type { Request as Request_3 } from '@cloudflare/workers-types/experimental'; +import { RequestCache } from 'undici'; +import { RequestCredentials } from 'undici'; +import { RequestDestination } from 'undici'; +import { RequestDuplex } from 'undici'; +import { RequestInfo as RequestInfo_2 } from 'undici'; +import { RequestInit as RequestInit_2 } from 'undici'; +import type { RequestInit as RequestInit_3 } from '@cloudflare/workers-types/experimental'; +import type { RequestInitCfProperties } from '@cloudflare/workers-types/experimental'; +import { RequestMode } from 'undici'; +import { RequestRedirect } from 'undici'; +import { Response as Response_2 } from 'undici'; +import type { Response as Response_3 } from '@cloudflare/workers-types/experimental'; +import { ResponseInit as ResponseInit_2 } from 'undici'; +import { ResponseRedirectStatus } from 'undici'; +import { ResponseType } from 'undici'; +import type { ServiceWorkerGlobalScope } from '@cloudflare/workers-types/experimental'; +import { compatibilityDate as supportedCompatibilityDate } from 'workerd'; +import { Transform } from 'stream'; +import { z } from 'zod'; + +export declare type Awaitable = T | Promise; + +export declare function base64Decode(encoded: string): string; + +export declare function base64Encode(value: string): string; + +export { BodyInit } + +export declare const CACHE_PLUGIN: Plugin; + +export declare const CACHE_PLUGIN_NAME = "cache"; + +export declare const CacheBindings: { + readonly MAYBE_JSON_CACHE_WARN_USAGE: "MINIFLARE_CACHE_WARN_USAGE"; +}; + +export declare const CacheHeaders: { + readonly NAMESPACE: "cf-cache-namespace"; + readonly STATUS: "cf-cache-status"; +}; + +export declare interface CacheObjectCf { + miniflare?: { + cacheWarnUsage?: boolean; + }; +} + +export declare const CacheOptionsSchema: z.ZodObject<{ + cache: z.ZodOptional; + cacheWarnUsage: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; +}, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; +}>; + +export declare const CacheSharedOptionsSchema: z.ZodObject<{ + cachePersist: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + cachePersist?: string | boolean | undefined; +}, { + cachePersist?: string | boolean | undefined; +}>; + +export declare class CloseEvent extends Event { + readonly code: number; + readonly reason: string; + readonly wasClean: boolean; + constructor(type: "close", init?: { + code?: number; + reason?: string; + wasClean?: boolean; + }); +} + +export declare interface Config { + services?: Service[]; + sockets?: Socket[]; + v8Flags?: string[]; + extensions?: Extension[]; +} + +export declare function configureEntrySocket(coreOpts: z.infer): Promise; + +export declare const CORE_PLUGIN: Plugin; + +export declare const CORE_PLUGIN_NAME = "core"; + +export declare const CoreBindings: { + readonly SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK"; + readonly SERVICE_USER_ROUTE_PREFIX: "MINIFLARE_USER_ROUTE_"; + readonly SERVICE_USER_FALLBACK: "MINIFLARE_USER_FALLBACK"; + readonly TEXT_CUSTOM_SERVICE: "MINIFLARE_CUSTOM_SERVICE"; + readonly TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL"; + readonly JSON_CF_BLOB: "CF_BLOB"; + readonly JSON_ROUTES: "MINIFLARE_ROUTES"; + readonly JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL"; + readonly DATA_LIVE_RELOAD_SCRIPT: "MINIFLARE_LIVE_RELOAD_SCRIPT"; + readonly DURABLE_OBJECT_NAMESPACE_PROXY: "MINIFLARE_PROXY"; +}; + +export declare const CoreHeaders: { + readonly CUSTOM_SERVICE: "MF-Custom-Service"; + readonly ORIGINAL_URL: "MF-Original-URL"; + readonly ERROR_STACK: "MF-Experimental-Error-Stack"; + readonly ROUTE_OVERRIDE: "MF-Route-Override"; + readonly OP: "MF-Op"; + readonly OP_TARGET: "MF-Op-Target"; + readonly OP_KEY: "MF-Op-Key"; + readonly OP_SYNC: "MF-Op-Sync"; + readonly OP_STRINGIFIED_SIZE: "MF-Op-Stringified-Size"; + readonly OP_RESULT_TYPE: "MF-Op-Result-Type"; +}; + +export declare const CoreOptionsSchema: z.ZodEffects; + path: z.ZodString; + contents: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }>, "many">; + modulesRoot: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; +}, { + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; +}>, z.ZodObject<{ + script: z.ZodString; + scriptPath: z.ZodOptional; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }>, "many">>; + modulesRoot: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; +}, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; +}>, z.ZodObject<{ + scriptPath: z.ZodString; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }>, "many">>; + modulesRoot: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; +}, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; +}>]>, z.ZodObject<{ + name: z.ZodOptional; + compatibilityDate: z.ZodOptional; + compatibilityFlags: z.ZodOptional>; + routes: z.ZodOptional>; + bindings: z.ZodOptional>>; + wasmBindings: z.ZodOptional>; + textBlobBindings: z.ZodOptional>; + dataBlobBindings: z.ZodOptional>; + serviceBindings: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer; + }, { + external: ExternalServer; + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + writable?: boolean | undefined; + path: string; + }, { + writable?: boolean | undefined; + path: string; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }>, z.ZodFunction, z.ZodTypeDef, Request>], z.ZodUnknown>, z.ZodUnion<[z.ZodType, z.ZodPromise>]>>]>>>; + outboundService: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer; + }, { + external: ExternalServer; + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + writable?: boolean | undefined; + path: string; + }, { + writable?: boolean | undefined; + path: string; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }>, z.ZodFunction, z.ZodTypeDef, Request>], z.ZodUnknown>, z.ZodUnion<[z.ZodType, z.ZodPromise>]>>]>>; + fetchMock: z.ZodOptional, z.ZodTypeDef, MockAgent>>; + unsafeEphemeralDurableObjects: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; +}, { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; +}>>, ({ + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; +} & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; +}) | ({ + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; +} & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; +}) | ({ + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; +} & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; +}), ({ + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; +} | { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; +} | { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; +}) & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: MockAgent | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; +}>; + +export declare const CoreSharedOptionsSchema: z.ZodObject<{ + host: z.ZodOptional; + port: z.ZodOptional; + https: z.ZodOptional; + httpsKey: z.ZodOptional; + httpsKeyPath: z.ZodOptional; + httpsCert: z.ZodOptional; + httpsCertPath: z.ZodOptional; + inspectorPort: z.ZodOptional; + verbose: z.ZodOptional; + log: z.ZodOptional>; + upstream: z.ZodOptional; + cf: z.ZodOptional]>>; + liveReload: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + host?: string | undefined; + port?: number | undefined; + cf?: string | boolean | Record | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + log?: Log | undefined; + upstream?: string | undefined; + liveReload?: boolean | undefined; +}, { + host?: string | undefined; + port?: number | undefined; + cf?: string | boolean | Record | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + log?: Log | undefined; + upstream?: string | undefined; + liveReload?: boolean | undefined; +}>; + +export declare function coupleWebSocket(ws: NodeWebSocket, pair: WebSocket): Promise; + +export declare function createFetchMock(): MockAgent; + +export declare function createHTTPReducers(impl: PlatformImpl): ReducersRevivers; + +export declare function createHTTPRevivers(impl: PlatformImpl): ReducersRevivers; + +export declare const D1_PLUGIN: Plugin; + +export declare const D1_PLUGIN_NAME = "d1"; + +export declare const D1OptionsSchema: z.ZodObject<{ + d1Databases: z.ZodOptional, z.ZodArray]>>; +}, "strip", z.ZodTypeAny, { + d1Databases?: string[] | Record | undefined; +}, { + d1Databases?: string[] | Record | undefined; +}>; + +export declare const D1SharedOptionsSchema: z.ZodObject<{ + d1Persist: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + d1Persist?: string | boolean | undefined; +}, { + d1Persist?: string | boolean | undefined; +}>; + +export declare function decodeSitesKey(key: string): string; + +export declare const DEFAULT_PERSIST_ROOT = ".mf"; + +export declare class DeferredPromise extends Promise { + readonly resolve: DeferredPromiseResolve; + readonly reject: DeferredPromiseReject; + constructor(executor?: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void); +} + +export declare type DeferredPromiseReject = (reason?: any) => void; + +export declare type DeferredPromiseResolve = (value: T | PromiseLike) => void; + +export declare function deserialiseRegExps(matcher: SerialisableMatcherRegExps): MatcherRegExps; + +export declare function deserialiseSiteRegExps(siteRegExps: SerialisableSiteMatcherRegExps): SiteMatcherRegExps; + +export declare interface DiskDirectory { + path?: string; + writable?: boolean; +} + +export declare type DispatchFetch = (input: RequestInfo, init?: RequestInit>) => Promise; + +export declare const DURABLE_OBJECTS_PLUGIN: Plugin; + +export declare const DURABLE_OBJECTS_PLUGIN_NAME = "do"; + +export declare const DURABLE_OBJECTS_STORAGE_SERVICE_NAME: string; + +export declare type DurableObjectClassNames = Map>; + +export declare const DurableObjectsOptionsSchema: z.ZodObject<{ + durableObjects: z.ZodOptional; + unsafeUniqueKey: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + scriptName?: string | undefined; + unsafeUniqueKey?: string | undefined; + className: string; + }, { + scriptName?: string | undefined; + unsafeUniqueKey?: string | undefined; + className: string; + }>]>>>; +}, "strip", z.ZodTypeAny, { + durableObjects?: Record | undefined; +}, { + durableObjects?: Record | undefined; +}>; + +export declare const DurableObjectsSharedOptionsSchema: z.ZodObject<{ + durableObjectsPersist: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + durableObjectsPersist?: string | boolean | undefined; +}, { + durableObjectsPersist?: string | boolean | undefined; +}>; + +export declare function encodeSitesKey(key: string): string; + +export declare class ErrorEvent extends Event { + readonly error: Error | null; + constructor(type: "error", init?: { + error?: Error; + }); +} + +export declare interface Extension { + modules?: Extension_Module[]; +} + +export declare interface Extension_Module { + name?: string; + internal?: boolean; + esModule?: string; +} + +export declare type ExternalServer = { + address?: string; +} & ({ + http: HttpOptions; +} | { + https: ExternalServer_Https; +}); + +export declare interface ExternalServer_Https { + options?: HttpOptions; + tlsOptions?: TlsOptions; + certificateHost?: string; +} + +export declare function fetch(input: RequestInfo, init?: RequestInit | Request): Promise; + +export { File } + +export declare function _forceColour(enabled?: boolean): void; + +/* Excluded from this release type: _formatZodError */ +export { FormData } + +export declare function getAccessibleHosts(ipv4Only?: boolean): string[]; + +export declare function getCacheServiceName(workerIndex: number): string; + +export declare function getGlobalServices({ sharedOptions, allWorkerRoutes, fallbackWorkerName, loopbackPort, log, proxyBindings, }: GlobalServicesOptions): Service[]; + +export declare function getPersistPath(pluginName: string, tmpPath: string, persist: Persistence): string; + +export declare interface GlobalServicesOptions { + sharedOptions: z.infer; + allWorkerRoutes: Map; + fallbackWorkerName: string | undefined; + loopbackPort: number; + log: Log; + proxyBindings: Worker_Binding[]; +} + +export declare function globsToRegExps(globs?: string[]): MatcherRegExps; + +export declare const HEADER_CF_BLOB = "MF-CF-Blob"; + +export { Headers } + +export { HeadersInit } + +export declare interface HttpOptions { + style?: HttpOptions_Style; + forwardedProtoHeader?: string; + cfBlobHeader?: string; + injectRequestHeaders?: HttpOptions_Header[]; + injectResponseHeaders?: HttpOptions_Header[]; +} + +export declare interface HttpOptions_Header { + name?: string; + value?: string; +} + +export declare enum HttpOptions_Style { + HOST = 0, + PROXY = 1 +} + +export declare interface InclusiveRange { + start: number; + end: number; +} + +/* Excluded from this release type: _initialiseInstanceRegistry */ + +export declare function isFetcherFetch(targetName: string, key: string): boolean; + +export declare function isR2ObjectWriteHttpMetadata(targetName: string, key: string): boolean; + +export declare function isSitesRequest(request: { + url: string; +}): boolean; + +export declare type Json = Literal | { + [key: string]: Json; +} | Json[]; + +export declare interface JsonError { + message?: string; + name?: string; + stack?: string; + cause?: JsonError; +} + +export declare const JsonSchema: z.ZodType; + +declare const kAccepted: unique symbol; + +declare const kCf: unique symbol; + +declare const kClose: unique symbol; + +declare const kClosedIncoming: unique symbol; + +declare const kClosedOutgoing: unique symbol; + +declare const kCoupled: unique symbol; + +declare const kError: unique symbol; + +declare const kPair: unique symbol; + +export declare const kProxyNodeBinding: unique symbol; + +declare const kSend: unique symbol; + +export declare const KV_PLUGIN: Plugin; + +export declare const KV_PLUGIN_NAME = "kv"; + +export declare const KVHeaders: { + readonly EXPIRATION: "CF-Expiration"; + readonly METADATA: "CF-KV-Metadata"; +}; + +export declare const KVLimits: { + readonly MIN_CACHE_TTL: 60; + readonly MAX_LIST_KEYS: 1000; + readonly MAX_KEY_SIZE: 512; + readonly MAX_VALUE_SIZE: number; + readonly MAX_VALUE_SIZE_TEST: 1024; + readonly MAX_METADATA_SIZE: 1024; +}; + +export declare const kVoid: unique symbol; + +export declare const KVOptionsSchema: z.ZodObject<{ + kvNamespaces: z.ZodOptional, z.ZodArray]>>; + sitePath: z.ZodOptional; + siteInclude: z.ZodOptional>; + siteExclude: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; +}, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; +}>; + +export declare const KVParams: { + readonly URL_ENCODED: "urlencoded"; + readonly CACHE_TTL: "cache_ttl"; + readonly EXPIRATION: "expiration"; + readonly EXPIRATION_TTL: "expiration_ttl"; + readonly LIST_LIMIT: "key_count_limit"; + readonly LIST_PREFIX: "prefix"; + readonly LIST_CURSOR: "cursor"; +}; + +export declare const KVSharedOptionsSchema: z.ZodObject<{ + kvPersist: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + kvPersist?: string | boolean | undefined; +}, { + kvPersist?: string | boolean | undefined; +}>; + +declare const kWebSocket: unique symbol; + +export declare type Literal = z.infer; + +export declare const LiteralSchema: z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>; + +export declare class Log { + #private; + readonly level: LogLevel; + constructor(level?: LogLevel, opts?: LogOptions); + protected log(message: string): void; + logWithLevel(level: LogLevel, message: string): void; + error(message: Error): void; + warn(message: string): void; + info(message: string): void; + debug(message: string): void; + verbose(message: string): void; +} + +export declare enum LogLevel { + NONE = 0, + ERROR = 1, + WARN = 2, + INFO = 3, + DEBUG = 4, + VERBOSE = 5 +} + +export declare interface LogOptions { + prefix?: string; + suffix?: string; +} + +export declare interface MatcherRegExps { + include: RegExp[]; + exclude: RegExp[]; +} + +export declare function matchRoutes(routes: WorkerRoute[], url: URL): string | null; + +export declare function maybeApply(f: (value: From) => To, maybeValue: From | undefined): To | undefined; + +export declare function maybeGetSitesManifestModule(bindings: Worker_Binding[]): Worker_Module | undefined; + +export declare function maybeParseURL(url: Persistence): URL | undefined; + +export declare class MessageEvent extends Event { + readonly data: ArrayBuffer | string; + constructor(type: "message", init: { + data: ArrayBuffer | string; + }); +} + +export declare function migrateDatabase(log: Log, uniqueKey: string, persistPath: string, namespace: string): Promise; + +export declare class Miniflare { + #private; + constructor(opts: MiniflareOptions); + get ready(): Promise; + setOptions(opts: MiniflareOptions): Promise; + dispatchFetch: DispatchFetch; + /* Excluded from this release type: _getProxyClient */ + getBindings>(workerName?: string): Promise; + getCaches(): Promise>; + getD1Database(bindingName: string, workerName?: string): Promise; + getDurableObjectNamespace(bindingName: string, workerName?: string): Promise>; + getKVNamespace(bindingName: string, workerName?: string): Promise>; + getQueueProducer(bindingName: string, workerName?: string): Promise>; + getR2Bucket(bindingName: string, workerName?: string): Promise>; + /* Excluded from this release type: _getInternalDurableObjectNamespace */ + dispose(): Promise; +} + +export declare class MiniflareCoreError extends MiniflareError { +} + +export declare type MiniflareCoreErrorCode = "ERR_RUNTIME_FAILURE" | "ERR_DISPOSED" | "ERR_MODULE_PARSE" | "ERR_MODULE_STRING_SCRIPT" | "ERR_MODULE_DYNAMIC_SPEC" | "ERR_MODULE_RULE" | "ERR_PERSIST_UNSUPPORTED" | "ERR_PERSIST_REMOTE_UNAUTHENTICATED" | "ERR_PERSIST_REMOTE_UNSUPPORTED" | "ERR_FUTURE_COMPATIBILITY_DATE" | "ERR_NO_WORKERS" | "ERR_VALIDATION" | "ERR_DUPLICATE_NAME" | "ERR_DIFFERENT_UNIQUE_KEYS" | "ERR_MULTIPLE_OUTBOUNDS"; + +export declare class MiniflareError extends Error { + readonly code: Code; + readonly cause?: Error | undefined; + constructor(code: Code, message?: string, cause?: Error | undefined); +} + +export declare type MiniflareOptions = SharedOptions & (WorkerOptions | { + workers: WorkerOptions[]; +}); + +export declare type ModuleDefinition = z.infer; + +export declare const ModuleDefinitionSchema: z.ZodObject<{ + type: z.ZodEnum<["ESModule", "CommonJS", "NodeJsCompatModule", "Text", "Data", "CompiledWasm"]>; + path: z.ZodString; + contents: z.ZodOptional]>>; +}, "strip", z.ZodTypeAny, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; +}, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; +}>; + +export declare type ModuleRule = z.infer; + +export declare const ModuleRuleSchema: z.ZodObject<{ + type: z.ZodEnum<["ESModule", "CommonJS", "NodeJsCompatModule", "Text", "Data", "CompiledWasm"]>; + include: z.ZodArray; + fallthrough: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; +}, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; +}>; + +export declare type ModuleRuleType = z.infer; + +export declare const ModuleRuleTypeSchema: z.ZodEnum<["ESModule", "CommonJS", "NodeJsCompatModule", "Text", "Data", "CompiledWasm"]>; + +export declare class Mutex { + private locked; + private resolveQueue; + private drainQueue; + private lock; + private unlock; + get hasWaiting(): boolean; + runWith(closure: () => Awaitable): Promise; + drained(): Promise; +} + +export declare function namespaceEntries(namespaces?: Record | string[]): [bindingName: string, id: string][]; + +export declare function namespaceKeys(namespaces?: Record | string[]): string[]; + +export declare interface Network { + allow?: string[]; + deny?: string[]; + tlsOptions?: TlsOptions; +} + +export declare const NODE_PLATFORM_IMPL: PlatformImpl; + +export declare class NoOpLog extends Log { + constructor(); + protected log(): void; + error(message: Error): void; +} + +export declare function normaliseDurableObject(designator: NonNullable["durableObjects"]>[string]): { + className: string; + serviceName?: string; + unsafeUniqueKey?: string; +}; + +export declare function objectEntryWorker(durableObjectNamespace: Worker_Binding_DurableObjectNamespaceDesignator, namespace: string): Worker; + +export declare type OptionalZodTypeOf = T extends z.ZodTypeAny ? z.TypeOf : undefined; + +export declare type OverloadReplaceWorkersTypes = T extends (...args: any[]) => any ? UnionToIntersection>> : ReplaceWorkersTypes; + +export declare type OverloadUnion any> = Parameters extends [] ? T : OverloadUnion9; + +export declare type OverloadUnion2 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) : T; + +export declare type OverloadUnion3 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) : OverloadUnion2; + +export declare type OverloadUnion4 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) : OverloadUnion3; + +export declare type OverloadUnion5 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) : OverloadUnion4; + +export declare type OverloadUnion6 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; + (...args: infer P6): infer R6; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) | ((...args: P6) => R6) : OverloadUnion5; + +export declare type OverloadUnion7 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; + (...args: infer P6): infer R6; + (...args: infer P7): infer R7; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) | ((...args: P6) => R6) | ((...args: P7) => R7) : OverloadUnion6; + +export declare type OverloadUnion8 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; + (...args: infer P6): infer R6; + (...args: infer P7): infer R7; + (...args: infer P8): infer R8; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) | ((...args: P6) => R6) | ((...args: P7) => R7) | ((...args: P8) => R8) : OverloadUnion7; + +export declare type OverloadUnion9 = T extends { + (...args: infer P1): infer R1; + (...args: infer P2): infer R2; + (...args: infer P3): infer R3; + (...args: infer P4): infer R4; + (...args: infer P5): infer R5; + (...args: infer P6): infer R6; + (...args: infer P7): infer R7; + (...args: infer P8): infer R8; + (...args: infer P9): infer R9; +} ? ((...args: P1) => R1) | ((...args: P2) => R2) | ((...args: P3) => R3) | ((...args: P4) => R4) | ((...args: P5) => R5) | ((...args: P6) => R6) | ((...args: P7) => R7) | ((...args: P8) => R8) | ((...args: P9) => R9) : OverloadUnion8; + +/** + * Parses an HTTP `Range` header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range), + * returning either: + * - `undefined` indicating the range is unsatisfiable + * - An empty array indicating the entire response should be returned + * - A non-empty array of inclusive ranges of the response to return + */ +export declare function parseRanges(rangeHeader: string, length: number): InclusiveRange[] | undefined; + +export declare function parseRoutes(allRoutes: Map): WorkerRoute[]; + +export declare function parseWithReadableStreams(impl: PlatformImpl, stringified: StringifiedWithStream, revivers: ReducersRevivers): unknown; + +export declare type Persistence = z.infer; + +export declare const PersistenceSchema: z.ZodOptional>; + +export declare interface PlatformImpl { + Blob: typeof Blob_2; + File: typeof File_2; + Headers: typeof Headers_2; + Request: typeof Request_3; + Response: typeof Response_3; + isReadableStream(value: unknown): value is RS; + bufferReadableStream(stream: RS): Promise; + unbufferReadableStream(buffer: ArrayBuffer): RS; +} + +export declare type Plugin = PluginBase & (SharedOptions extends undefined ? { + sharedOptions?: undefined; +} : { + sharedOptions: SharedOptions; +}); + +export declare const PLUGIN_ENTRIES: ["cache" | "core" | "do" | "d1" | "kv" | "queues" | "r2", ValueOf<{ + core: Plugin; + path: z.ZodString; + contents: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }>, "many">; + modulesRoot: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; + }, { + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; + }>, z.ZodObject<{ + script: z.ZodString; + scriptPath: z.ZodOptional; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }>, "many">>; + modulesRoot: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; + }, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; + }>, z.ZodObject<{ + scriptPath: z.ZodString; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }>, "many">>; + modulesRoot: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; + }, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; + }>]>, z.ZodObject<{ + name: z.ZodOptional; + compatibilityDate: z.ZodOptional; + compatibilityFlags: z.ZodOptional>; + routes: z.ZodOptional>; + bindings: z.ZodOptional>>; + wasmBindings: z.ZodOptional>; + textBlobBindings: z.ZodOptional>; + dataBlobBindings: z.ZodOptional>; + serviceBindings: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer; + }, { + external: ExternalServer; + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + writable?: boolean | undefined; + path: string; + }, { + writable?: boolean | undefined; + path: string; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }>, z.ZodFunction, z.ZodTypeDef, Request>], z.ZodUnknown>, z.ZodUnion<[z.ZodType, z.ZodPromise>]>>]>>>; + outboundService: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer; + }, { + external: ExternalServer; + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + writable?: boolean | undefined; + path: string; + }, { + writable?: boolean | undefined; + path: string; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }>, z.ZodFunction, z.ZodTypeDef, Request>], z.ZodUnknown>, z.ZodUnion<[z.ZodType, z.ZodPromise>]>>]>>; + fetchMock: z.ZodOptional, z.ZodTypeDef, default_2>>; + unsafeEphemeralDurableObjects: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }, { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }>>, ({ + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; + } & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }) | ({ + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; + } & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }) | ({ + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; + } & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }), ({ + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; + } | { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; + } | { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; + }) & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }>, z.ZodObject<{ + host: z.ZodOptional; + port: z.ZodOptional; + https: z.ZodOptional; + httpsKey: z.ZodOptional; + httpsKeyPath: z.ZodOptional; + httpsCert: z.ZodOptional; + httpsCertPath: z.ZodOptional; + inspectorPort: z.ZodOptional; + verbose: z.ZodOptional; + log: z.ZodOptional>; + upstream: z.ZodOptional; + cf: z.ZodOptional]>>; + liveReload: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + host?: string | undefined; + port?: number | undefined; + cf?: string | boolean | Record | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + log?: Log | undefined; + upstream?: string | undefined; + liveReload?: boolean | undefined; + }, { + host?: string | undefined; + port?: number | undefined; + cf?: string | boolean | Record | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + log?: Log | undefined; + upstream?: string | undefined; + liveReload?: boolean | undefined; + }>>; + cache: Plugin; + cacheWarnUsage: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; + }, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; + }>, z.ZodObject<{ + cachePersist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + cachePersist?: string | boolean | undefined; + }, { + cachePersist?: string | boolean | undefined; + }>>; + d1: Plugin, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + d1Databases?: string[] | Record | undefined; + }, { + d1Databases?: string[] | Record | undefined; + }>, z.ZodObject<{ + d1Persist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + d1Persist?: string | boolean | undefined; + }, { + d1Persist?: string | boolean | undefined; + }>>; + do: Plugin; + unsafeUniqueKey: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + scriptName?: string | undefined; + unsafeUniqueKey?: string | undefined; + className: string; + }, { + scriptName?: string | undefined; + unsafeUniqueKey?: string | undefined; + className: string; + }>]>>>; + }, "strip", z.ZodTypeAny, { + durableObjects?: Record | undefined; + }, { + durableObjects?: Record | undefined; + }>, z.ZodObject<{ + durableObjectsPersist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + durableObjectsPersist?: string | boolean | undefined; + }, { + durableObjectsPersist?: string | boolean | undefined; + }>>; + kv: Plugin, z.ZodArray]>>; + sitePath: z.ZodOptional; + siteInclude: z.ZodOptional>; + siteExclude: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; + }, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; + }>, z.ZodObject<{ + kvPersist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + kvPersist?: string | boolean | undefined; + }, { + kvPersist?: string | boolean | undefined; + }>>; + queues: Plugin, z.ZodArray]>>; + queueConsumers: z.ZodOptional; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + }, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + }>>, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + queueProducers?: string[] | Record | undefined; + queueConsumers?: string[] | Record | undefined; + }, { + queueProducers?: string[] | Record | undefined; + queueConsumers?: string[] | Record | undefined; + }>>; + r2: Plugin, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + r2Buckets?: string[] | Record | undefined; + }, { + r2Buckets?: string[] | Record | undefined; + }>, z.ZodObject<{ + r2Persist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + r2Persist?: string | boolean | undefined; + }, { + r2Persist?: string | boolean | undefined; + }>>; +}>][]; + +export declare interface PluginBase { + options: Options; + getBindings(options: z.infer, workerIndex: number): Awaitable; + getNodeBindings(options: z.infer): Awaitable>; + getServices(options: PluginServicesOptions): Awaitable; +} + +export declare const PLUGINS: { + core: Plugin; + path: z.ZodString; + contents: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }>, "many">; + modulesRoot: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; + }, { + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; + }>, z.ZodObject<{ + script: z.ZodString; + scriptPath: z.ZodOptional; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }>, "many">>; + modulesRoot: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; + }, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; + }>, z.ZodObject<{ + scriptPath: z.ZodString; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }>, "many">>; + modulesRoot: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; + }, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; + }>]>, z.ZodObject<{ + name: z.ZodOptional; + compatibilityDate: z.ZodOptional; + compatibilityFlags: z.ZodOptional>; + routes: z.ZodOptional>; + bindings: z.ZodOptional>>; + wasmBindings: z.ZodOptional>; + textBlobBindings: z.ZodOptional>; + dataBlobBindings: z.ZodOptional>; + serviceBindings: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer; + }, { + external: ExternalServer; + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + writable?: boolean | undefined; + path: string; + }, { + writable?: boolean | undefined; + path: string; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }>, z.ZodFunction, z.ZodTypeDef, Request>], z.ZodUnknown>, z.ZodUnion<[z.ZodType, z.ZodPromise>]>>]>>>; + outboundService: z.ZodOptional>; + deny: z.ZodOptional>; + tlsOptions: z.ZodOptional; + certificateChain: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }, { + privateKey?: string | undefined; + certificateChain?: string | undefined; + }>>; + requireClientCerts: z.ZodOptional; + trustBrowserCas: z.ZodOptional; + trustedCertificates: z.ZodOptional>; + minVersion: z.ZodOptional>; + cipherList: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }, { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + }>>; + }, "strip", z.ZodTypeAny, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }, { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }>; + }, "strip", z.ZodTypeAny, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }, { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + }>, z.ZodObject<{ + external: z.ZodType; + }, "strip", z.ZodTypeAny, { + external: ExternalServer; + }, { + external: ExternalServer; + }>, z.ZodObject<{ + disk: z.ZodObject<{ + path: z.ZodString; + writable: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + writable?: boolean | undefined; + path: string; + }, { + writable?: boolean | undefined; + path: string; + }>; + }, "strip", z.ZodTypeAny, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }, { + disk: { + writable?: boolean | undefined; + path: string; + }; + }>, z.ZodFunction, z.ZodTypeDef, Request>], z.ZodUnknown>, z.ZodUnion<[z.ZodType, z.ZodPromise>]>>]>>; + fetchMock: z.ZodOptional, z.ZodTypeDef, default_2>>; + unsafeEphemeralDurableObjects: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }, { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }>>, ({ + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; + } & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }) | ({ + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; + } & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }) | ({ + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; + } & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }), ({ + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; + } | { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; + } | { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; + }) & { + name?: string | undefined; + compatibilityDate?: string | undefined; + bindings?: Record | undefined; + compatibilityFlags?: string[] | undefined; + routes?: string[] | undefined; + wasmBindings?: Record | undefined; + textBlobBindings?: Record | undefined; + dataBlobBindings?: Record | undefined; + serviceBindings?: Record, ...args_1: unknown[]) => Response | Promise)> | undefined; + outboundService?: string | { + network: { + allow?: string[] | undefined; + deny?: string[] | undefined; + tlsOptions?: { + minVersion?: TlsOptions_Version | undefined; + keypair?: { + privateKey?: string | undefined; + certificateChain?: string | undefined; + } | undefined; + requireClientCerts?: boolean | undefined; + trustBrowserCas?: boolean | undefined; + trustedCertificates?: string[] | undefined; + cipherList?: string | undefined; + } | undefined; + }; + } | { + external: ExternalServer; + } | { + disk: { + writable?: boolean | undefined; + path: string; + }; + } | ((args_0: Request, ...args_1: unknown[]) => Response | Promise) | undefined; + fetchMock?: default_2 | undefined; + unsafeEphemeralDurableObjects?: boolean | undefined; + }>, z.ZodObject<{ + host: z.ZodOptional; + port: z.ZodOptional; + https: z.ZodOptional; + httpsKey: z.ZodOptional; + httpsKeyPath: z.ZodOptional; + httpsCert: z.ZodOptional; + httpsCertPath: z.ZodOptional; + inspectorPort: z.ZodOptional; + verbose: z.ZodOptional; + log: z.ZodOptional>; + upstream: z.ZodOptional; + cf: z.ZodOptional]>>; + liveReload: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + host?: string | undefined; + port?: number | undefined; + cf?: string | boolean | Record | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + log?: Log | undefined; + upstream?: string | undefined; + liveReload?: boolean | undefined; + }, { + host?: string | undefined; + port?: number | undefined; + cf?: string | boolean | Record | undefined; + inspectorPort?: number | undefined; + verbose?: boolean | undefined; + https?: boolean | undefined; + httpsKey?: string | undefined; + httpsKeyPath?: string | undefined; + httpsCert?: string | undefined; + httpsCertPath?: string | undefined; + log?: Log | undefined; + upstream?: string | undefined; + liveReload?: boolean | undefined; + }>>; + cache: Plugin; + cacheWarnUsage: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; + }, { + cache?: boolean | undefined; + cacheWarnUsage?: boolean | undefined; + }>, z.ZodObject<{ + cachePersist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + cachePersist?: string | boolean | undefined; + }, { + cachePersist?: string | boolean | undefined; + }>>; + d1: Plugin, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + d1Databases?: string[] | Record | undefined; + }, { + d1Databases?: string[] | Record | undefined; + }>, z.ZodObject<{ + d1Persist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + d1Persist?: string | boolean | undefined; + }, { + d1Persist?: string | boolean | undefined; + }>>; + do: Plugin; + unsafeUniqueKey: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + scriptName?: string | undefined; + unsafeUniqueKey?: string | undefined; + className: string; + }, { + scriptName?: string | undefined; + unsafeUniqueKey?: string | undefined; + className: string; + }>]>>>; + }, "strip", z.ZodTypeAny, { + durableObjects?: Record | undefined; + }, { + durableObjects?: Record | undefined; + }>, z.ZodObject<{ + durableObjectsPersist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + durableObjectsPersist?: string | boolean | undefined; + }, { + durableObjectsPersist?: string | boolean | undefined; + }>>; + kv: Plugin, z.ZodArray]>>; + sitePath: z.ZodOptional; + siteInclude: z.ZodOptional>; + siteExclude: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; + }, { + kvNamespaces?: string[] | Record | undefined; + sitePath?: string | undefined; + siteInclude?: string[] | undefined; + siteExclude?: string[] | undefined; + }>, z.ZodObject<{ + kvPersist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + kvPersist?: string | boolean | undefined; + }, { + kvPersist?: string | boolean | undefined; + }>>; + queues: Plugin, z.ZodArray]>>; + queueConsumers: z.ZodOptional; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + }, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + }>>, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + queueProducers?: string[] | Record | undefined; + queueConsumers?: string[] | Record | undefined; + }, { + queueProducers?: string[] | Record | undefined; + queueConsumers?: string[] | Record | undefined; + }>>; + r2: Plugin, z.ZodArray]>>; + }, "strip", z.ZodTypeAny, { + r2Buckets?: string[] | Record | undefined; + }, { + r2Buckets?: string[] | Record | undefined; + }>, z.ZodObject<{ + r2Persist: z.ZodOptional>; + }, "strip", z.ZodTypeAny, { + r2Persist?: string | boolean | undefined; + }, { + r2Persist?: string | boolean | undefined; + }>>; +}; + +export declare type Plugins = typeof PLUGINS; + +export declare interface PluginServicesOptions { + log: Log; + options: z.infer; + sharedOptions: OptionalZodTypeOf; + workerBindings: Worker_Binding[]; + workerIndex: number; + additionalModules: Worker_Module[]; + tmpPath: string; + workerNames: string[]; + durableObjectClassNames: DurableObjectClassNames; + queueConsumers: QueueConsumers; +} + +export declare function prefixError(prefix: string, e: any): Error; + +export declare function prefixStream(prefix: Uint8Array, stream: ReadableStream_2): ReadableStream_2; + +export declare const ProxyAddresses: { + readonly GLOBAL: 0; + readonly ENV: 1; + readonly USER_START: 2; +}; + +export declare class ProxyClient { + #private; + constructor(runtimeEntryURL: URL, dispatchFetch: DispatchFetch); + get global(): ServiceWorkerGlobalScope; + get env(): Record; + poisonProxies(runtimeEntryURL?: URL): void; + dispose(): Promise; +} + +export declare const ProxyOps: { + readonly GET: "GET"; + readonly CALL: "CALL"; + readonly FREE: "FREE"; +}; + +export declare const QueueBindings: { + readonly SERVICE_WORKER_PREFIX: "MINIFLARE_WORKER_"; + readonly MAYBE_JSON_QUEUE_CONSUMERS: "MINIFLARE_QUEUE_CONSUMERS"; +}; + +export declare type QueueConsumer = z.infer; + +export declare const QueueConsumerOptionsSchema: z.ZodObject<{ + maxBatchSize: z.ZodOptional; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; +}, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; +}>; + +export declare type QueueConsumers = Map>; + +export declare const QueueConsumerSchema: z.ZodIntersection; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; +}, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; +}>, z.ZodObject<{ + workerName: z.ZodString; +}, "strip", z.ZodTypeAny, { + workerName: string; +}, { + workerName: string; +}>>; + +export declare const QueueConsumersSchema: z.ZodRecord; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; +}, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; +}>, z.ZodObject<{ + workerName: z.ZodString; +}, "strip", z.ZodTypeAny, { + workerName: string; +}, { + workerName: string; +}>>>; + +export declare type QueueContentType = z.infer; + +export declare const QueueContentTypeSchema: z.ZodDefault>; + +export declare type QueueIncomingMessage = z.infer; + +export declare const QueueIncomingMessageSchema: z.ZodObject<{ + contentType: z.ZodDefault>; + body: z.ZodEffects; + id: z.ZodOptional; + timestamp: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + id?: string | undefined; + timestamp?: number | undefined; + body: Buffer; + contentType: "text" | "json" | "bytes" | "v8"; +}, { + contentType?: "text" | "json" | "bytes" | "v8" | undefined; + id?: string | undefined; + timestamp?: number | undefined; + body: string; +}>; + +export declare type QueueOutgoingMessage = z.input; + +export declare const QUEUES_PLUGIN: Plugin; + +export declare const QUEUES_PLUGIN_NAME = "queues"; + +export declare const QueuesBatchRequestSchema: z.ZodObject<{ + messages: z.ZodArray>; + body: z.ZodEffects; + id: z.ZodOptional; + timestamp: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + id?: string | undefined; + timestamp?: number | undefined; + body: Buffer; + contentType: "text" | "json" | "bytes" | "v8"; + }, { + contentType?: "text" | "json" | "bytes" | "v8" | undefined; + id?: string | undefined; + timestamp?: number | undefined; + body: string; + }>, "many">; +}, "strip", z.ZodTypeAny, { + messages: { + id?: string | undefined; + timestamp?: number | undefined; + body: Buffer; + contentType: "text" | "json" | "bytes" | "v8"; + }[]; +}, { + messages: { + contentType?: "text" | "json" | "bytes" | "v8" | undefined; + id?: string | undefined; + timestamp?: number | undefined; + body: string; + }[]; +}>; + +export declare class QueuesError extends MiniflareError { +} + +export declare type QueuesErrorCode = "ERR_MULTIPLE_CONSUMERS" | "ERR_DEAD_LETTER_QUEUE_CYCLE"; + +export declare const QueuesOptionsSchema: z.ZodObject<{ + queueProducers: z.ZodOptional, z.ZodArray]>>; + queueConsumers: z.ZodOptional; + maxBatchTimeout: z.ZodOptional; + maxRetires: z.ZodOptional; + deadLetterQueue: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + }, { + maxBatchSize?: number | undefined; + maxBatchTimeout?: number | undefined; + maxRetires?: number | undefined; + deadLetterQueue?: string | undefined; + }>>, z.ZodArray]>>; +}, "strip", z.ZodTypeAny, { + queueProducers?: string[] | Record | undefined; + queueConsumers?: string[] | Record | undefined; +}, { + queueProducers?: string[] | Record | undefined; + queueConsumers?: string[] | Record | undefined; +}>; + +export declare type QueuesOutgoingBatchRequest = z.input; + +export declare const R2_PLUGIN: Plugin; + +export declare const R2_PLUGIN_NAME = "r2"; + +export declare const R2OptionsSchema: z.ZodObject<{ + r2Buckets: z.ZodOptional, z.ZodArray]>>; +}, "strip", z.ZodTypeAny, { + r2Buckets?: string[] | Record | undefined; +}, { + r2Buckets?: string[] | Record | undefined; +}>; + +export declare const R2SharedOptionsSchema: z.ZodObject<{ + r2Persist: z.ZodOptional>; +}, "strip", z.ZodTypeAny, { + r2Persist?: string | boolean | undefined; +}, { + r2Persist?: string | boolean | undefined; +}>; + +export declare function readPrefix(stream: ReadableStream_2, prefixLength: number): Promise<[prefix: Buffer, rest: ReadableStream_2]>; + +export declare function reduceError(e: any): JsonError; + +export declare type ReducerReviver = (value: unknown) => unknown; + +export declare type ReducersRevivers = Record; + +export { ReferrerPolicy } + +export declare function registerAllowUnauthorizedDispatcher(dispatcher: Dispatcher): void; + +export declare type ReplaceWorkersTypes = T extends Request_3 ? Request : T extends Response_3 ? Response : T extends ReadableStream ? ReadableStream_2 : Required extends Required ? RequestInit : T extends Headers_2 ? Headers : T extends Blob_2 ? Blob_3 : T extends AbortSignal_2 ? AbortSignal : T extends Promise ? Promise> : T extends (...args: infer P) => infer R ? (...args: ReplaceWorkersTypes

) => ReplaceWorkersTypes : T extends object ? { + [K in keyof T]: OverloadReplaceWorkersTypes; +} : T; + +export declare class Request extends Request_2 { + [kCf]?: CfType; + constructor(input: RequestInfo, init?: RequestInit); + get cf(): CfType | undefined; + /** @ts-expect-error `clone` is actually defined as a method internally */ + clone(): Request; +} + +export { RequestCache } + +export { RequestCredentials } + +export { RequestDestination } + +export { RequestDuplex } + +export declare type RequestInfo = RequestInfo_2 | Request; + +export declare interface RequestInit extends RequestInit_2 { + cf?: CfType; +} + +export declare type RequestInitCfType = Partial | RequestInitCfProperties; + +export { RequestMode } + +export { RequestRedirect } + +export declare class Response extends Response_2 { + readonly [kWebSocket]: WebSocket | null; + static error(): Response; + static redirect(url: string | URL, status: ResponseRedirectStatus): Response; + static json(data: any, init?: ResponseInit): Response; + constructor(body?: BodyInit, init?: ResponseInit); + /** @ts-expect-error `status` is actually defined as a getter internally */ + get status(): number; + get webSocket(): WebSocket | null; + /** @ts-expect-error `clone` is actually defined as a method internally */ + clone(): Response; +} + +export declare interface ResponseInit extends ResponseInit_2 { + webSocket?: WebSocket | null; +} + +export { ResponseRedirectStatus } + +export { ResponseType } + +export declare class RouterError extends MiniflareError { +} + +export declare type RouterErrorCode = "ERR_QUERY_STRING" | "ERR_INFIX_WILDCARD"; + +export declare class Runtime { + #private; + private opts; + constructor(opts: RuntimeOptions); + updateConfig(configBuffer: Buffer, options?: Abortable & Partial>): Promise; + dispose(): Awaitable; +} + +export declare interface RuntimeOptions { + entryHost: string; + entryPort: number; + loopbackPort: number; + inspectorPort?: number; + verbose?: boolean; +} + +export declare function sanitisePath(unsafe: string): string; + +export declare interface SerialisableMatcherRegExps { + include: string[]; + exclude: string[]; +} + +export declare interface SerialisableSiteMatcherRegExps { + include?: SerialisableMatcherRegExps; + exclude?: SerialisableMatcherRegExps; +} + +export declare function serialiseRegExps(matcher: MatcherRegExps): SerialisableMatcherRegExps; + +export declare function serialiseSiteRegExps(siteRegExps: SiteMatcherRegExps): SerialisableSiteMatcherRegExps; + +export declare function serializeConfig(config: Config): Buffer; + +export declare type Service = { + name?: string; +} & ({ + worker?: Worker; +} | { + network?: Network; +} | { + external?: ExternalServer; +} | { + disk?: DiskDirectory; +}); + +export declare const SERVICE_ENTRY: string; + +export declare const SERVICE_LOOPBACK = "loopback"; + +export declare interface ServiceDesignator { + name?: string; + entrypoint?: string; +} + +export declare const SharedBindings: { + readonly TEXT_NAMESPACE: "MINIFLARE_NAMESPACE"; + readonly DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT"; + readonly MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS"; + readonly MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK"; +}; + +export declare const SharedHeaders: { + readonly LOG_LEVEL: "MF-Log-Level"; +}; + +export declare type SharedOptions = z.infer & z.infer & z.infer & z.infer & z.infer & z.infer; + +export declare const SiteBindings: { + readonly KV_NAMESPACE_SITE: "__STATIC_CONTENT"; + readonly JSON_SITE_MANIFEST: "__STATIC_CONTENT_MANIFEST"; + readonly JSON_SITE_FILTER: "MINIFLARE_SITE_FILTER"; +}; + +export declare interface SiteMatcherRegExps { + include?: MatcherRegExps; + exclude?: MatcherRegExps; +} + +export declare const SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/"; + +export declare type Socket = { + name?: string; + address?: string; + service?: ServiceDesignator; +} & ({ + http?: HttpOptions; +} | { + https?: Socket_Https; +}); + +export declare const SOCKET_ENTRY = "entry"; + +export declare interface Socket_Https { + options?: HttpOptions; + tlsOptions?: TlsOptions; +} + +export declare type SourceOptions = z.infer; + +export declare const SourceOptionsSchema: z.ZodUnion<[z.ZodObject<{ + modules: z.ZodArray; + path: z.ZodString; + contents: z.ZodOptional]>>; + }, "strip", z.ZodTypeAny, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }, { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }>, "many">; + modulesRoot: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; +}, { + modulesRoot?: string | undefined; + modules: { + contents?: string | Uint8Array | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + path: string; + }[]; +}>, z.ZodObject<{ + script: z.ZodString; + scriptPath: z.ZodOptional; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }>, "many">>; + modulesRoot: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; +}, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + scriptPath?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + script: string; +}>, z.ZodObject<{ + scriptPath: z.ZodString; + modules: z.ZodOptional; + modulesRules: z.ZodOptional; + include: z.ZodArray; + fallthrough: z.ZodOptional; + }, "strip", z.ZodTypeAny, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }, { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }>, "many">>; + modulesRoot: z.ZodOptional; +}, "strip", z.ZodTypeAny, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; +}, { + modules?: boolean | undefined; + modulesRoot?: string | undefined; + modulesRules?: { + fallthrough?: boolean | undefined; + type: "ESModule" | "CommonJS" | "NodeJsCompatModule" | "Text" | "Data" | "CompiledWasm"; + include: string[]; + }[] | undefined; + scriptPath: string; +}>]>; + +export declare interface StringifiedWithStream { + value: string; + unbufferedStream?: RS; +} + +export declare function stringifyWithStreams(impl: PlatformImpl, value: unknown, reducers: ReducersRevivers, allowUnbufferedStream: boolean): StringifiedWithStream | Promise>; + +export declare function stripAnsi(value: string): string; + +export declare const structuredSerializableReducers: ReducersRevivers; + +export declare const structuredSerializableRevivers: ReducersRevivers; + +export { supportedCompatibilityDate } + +export declare function testRegExps(matcher: MatcherRegExps, value: string): boolean; + +export declare function testSiteRegExps(regExps: SiteMatcherRegExps, key: string): boolean; + +export declare interface TlsOptions { + keypair?: TlsOptions_Keypair; + requireClientCerts?: boolean; + trustBrowserCas?: boolean; + trustedCertificates?: string[]; + minVersion?: TlsOptions_Version; + cipherList?: string; +} + +export declare interface TlsOptions_Keypair { + privateKey?: string; + certificateChain?: string; +} + +export declare enum TlsOptions_Version { + GOOD_DEFAULT = 0, + SSL3 = 1, + TLS1DOT0 = 2, + TLS1DOT1 = 3, + TLS1DOT2 = 4, + TLS1DOT3 = 5 +} + +export declare function _transformsForContentEncoding(encoding?: string): Transform[]; + +export declare type TypedEventListener = ((e: E) => void) | { + handleEvent(e: E): void; +}; + +export declare class TypedEventTarget> extends EventTarget { + addEventListener(type: Type, listener: TypedEventListener | null, options?: AddEventListenerOptions | boolean): void; + removeEventListener(type: Type, listener: TypedEventListener | null, options?: EventListenerOptions | boolean): void; + dispatchEvent(event: ValueOf): boolean; +} + +export declare type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +export declare type ValueOf = T[keyof T]; + +export declare function viewToBuffer(view: ArrayBufferView): ArrayBuffer; + +export declare type Void = typeof kVoid; + +export declare class WaitGroup { + private counter; + private resolveQueue; + add(): void; + done(): void; + wait(): Promise; +} + +export declare class WebSocket extends TypedEventTarget { + #private; + static readonly READY_STATE_CONNECTING = 0; + static readonly READY_STATE_OPEN = 1; + static readonly READY_STATE_CLOSING = 2; + static readonly READY_STATE_CLOSED = 3; + [kPair]?: WebSocket; + [kAccepted]: boolean; + [kCoupled]: boolean; + [kClosedOutgoing]: boolean; + [kClosedIncoming]: boolean; + get readyState(): number; + accept(): void; + send(message: ArrayBuffer | string): void; + [kSend](message: ArrayBuffer | string): void; + close(code?: number, reason?: string): void; + [kClose](code?: number, reason?: string): void; + [kError](error?: Error): void; +} + +export declare type WebSocketEventMap = { + message: MessageEvent; + close: CloseEvent; + error: ErrorEvent; +}; + +export declare type WebSocketPair = { + 0: WebSocket; + 1: WebSocket; +}; + +export declare const WebSocketPair: new () => WebSocketPair; + +export declare type Worker = ({ + modules?: Worker_Module[]; +} | { + serviceWorkerScript?: string; +} | { + inherit?: string; +}) & { + compatibilityDate?: string; + compatibilityFlags?: string[]; + bindings?: Worker_Binding[]; + globalOutbound?: ServiceDesignator; + cacheApiOutbound?: ServiceDesignator; + durableObjectNamespaces?: Worker_DurableObjectNamespace[]; + durableObjectUniqueKeyModifier?: string; + durableObjectStorage?: Worker_DurableObjectStorage; +}; + +export declare type Worker_Binding = { + name?: string; +} & ({ + parameter?: Worker_Binding_Parameter; +} | { + text?: string; +} | { + data?: Uint8Array; +} | { + json?: string; +} | { + wasmModule?: Uint8Array; +} | { + cryptoKey?: Worker_Binding_CryptoKey; +} | { + service?: ServiceDesignator; +} | { + durableObjectNamespace?: Worker_Binding_DurableObjectNamespaceDesignator; +} | { + kvNamespace?: ServiceDesignator; +} | { + r2Bucket?: ServiceDesignator; +} | { + r2Admin?: ServiceDesignator; +} | { + wrapped?: Worker_Binding_WrappedBinding; +} | { + queue?: ServiceDesignator; +} | { + fromEnvironment?: string; +} | { + analyticsEngine?: ServiceDesignator; +}); + +export declare type Worker_Binding_CryptoKey = ({ + raw?: Uint8Array; +} | { + hex?: string; +} | { + base64?: string; +} | { + pkcs8?: string; +} | { + spki?: string; +} | { + jwk?: string; +}) & { + algorithm?: Worker_Binding_CryptoKey_Algorithm; + extractable?: boolean; + usages?: Worker_Binding_CryptoKey_Usage[]; +}; + +export declare type Worker_Binding_CryptoKey_Algorithm = { + name?: string; +} | { + json?: string; +}; + +export declare enum Worker_Binding_CryptoKey_Usage { + ENCRYPT = 0, + DECRYPT = 1, + SIGN = 2, + VERIFY = 3, + DERIVE_KEY = 4, + DERIVE_BITS = 5, + WRAP_KEY = 6, + UNWRAP_KEY = 7 +} + +export declare type Worker_Binding_DurableObjectNamespaceDesignator = { + className?: string; + serviceName?: string; +}; + +export declare interface Worker_Binding_Parameter { + type?: Worker_Binding_Type; + optional?: boolean; +} + +export declare const WORKER_BINDING_SERVICE_LOOPBACK: Worker_Binding; + +export declare type Worker_Binding_Type = { + text?: Void; +} | { + data?: Void; +} | { + json?: Void; +} | { + wasm?: Void; +} | { + cryptoKey?: Worker_Binding_CryptoKey_Usage[]; +} | { + service?: Void; +} | { + durableObjectNamespace: Void; +} | { + kvNamespace?: Void; +} | { + r2Bucket?: Void; +} | { + r2Admin?: Void; +} | { + queue?: Void; +} | { + analyticsEngine?: Void; +}; + +export declare interface Worker_Binding_WrappedBinding { + moduleName?: string; + entrypoint?: string; + innerBindings?: Worker_Binding[]; +} + +export declare type Worker_DurableObjectNamespace = { + className?: string; +} & ({ + uniqueKey?: string; +} | { + ephemeralLocal?: Void; +}); + +export declare type Worker_DurableObjectStorage = { + none?: Void; +} | { + inMemory?: Void; +} | { + localDisk?: string; +}; + +export declare type Worker_Module = { + name: string; +} & ({ + esModule?: string; +} | { + commonJsModule?: string; +} | { + text?: string; +} | { + data?: Uint8Array; +} | { + wasm?: Uint8Array; +} | { + json?: string; +} | { + nodeJsCompatModule?: string; +}); + +export declare type WorkerOptions = z.infer & z.infer & z.infer & z.infer & z.infer & z.infer & z.infer; + +export declare interface WorkerRoute { + target: string; + route: string; + specificity: number; + protocol?: string; + allowHostnamePrefix: boolean; + hostname: string; + path: string; + allowPathSuffix: boolean; +} + +export declare function zAwaitable(type: T): z.ZodUnion<[T, z.ZodPromise]>; + +export { } diff --git a/node_modules/miniflare/dist/src/index.js b/node_modules/miniflare/dist/src/index.js new file mode 100644 index 0000000..3347e78 --- /dev/null +++ b/node_modules/miniflare/dist/src/index.js @@ -0,0 +1,8150 @@ +"use strict"; +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 __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 = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; +var __privateMethod = (obj, member, method) => { + __accessCheck(obj, member, "access private method"); + return method; +}; + +// packages/miniflare/src/runtime/config/workerd.capnp.js +var require_workerd_capnp = __commonJS({ + "packages/miniflare/src/runtime/config/workerd.capnp.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Extension = exports.Extension_Module = exports.TlsOptions = exports.TlsOptions_Version = exports.TlsOptions_Keypair = exports.HttpOptions = exports.HttpOptions_Header = exports.HttpOptions_Style = exports.DiskDirectory = exports.Network = exports.ExternalServer = exports.ExternalServer_Which = exports.ExternalServer_Https = exports.Worker = exports.Worker_Which = exports.Worker_DurableObjectStorage = exports.Worker_DurableObjectStorage_Which = exports.Worker_DurableObjectNamespace = exports.Worker_DurableObjectNamespace_Which = exports.Worker_Binding = exports.Worker_Binding_Which = exports.Worker_Binding_Parameter = exports.Worker_Binding_WrappedBinding = exports.Worker_Binding_CryptoKey = exports.Worker_Binding_CryptoKey_Which = exports.Worker_Binding_CryptoKey_Algorithm = exports.Worker_Binding_CryptoKey_Algorithm_Which = exports.Worker_Binding_CryptoKey_Usage = exports.Worker_Binding_DurableObjectNamespaceDesignator = exports.Worker_Binding_Type = exports.Worker_Binding_Type_Which = exports.Worker_Module = exports.Worker_Module_Which = exports.ServiceDesignator = exports.Service = exports.Service_Which = exports.Socket = exports.Socket_Which = exports.Socket_Https = exports.Config = exports._capnpFileId = void 0; + var capnp = require("capnp-ts"); + var capnp_ts_1 = require("capnp-ts"); + exports._capnpFileId = "e6afd26682091c01"; + var Config3 = class extends capnp_ts_1.Struct { + adoptServices(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownServices() { + return capnp_ts_1.Struct.disown(this.getServices()); + } + getServices() { + return capnp_ts_1.Struct.getList(0, Config3._Services, this); + } + hasServices() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initServices(length) { + return capnp_ts_1.Struct.initList(0, Config3._Services, length, this); + } + setServices(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + adoptSockets(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownSockets() { + return capnp_ts_1.Struct.disown(this.getSockets()); + } + getSockets() { + return capnp_ts_1.Struct.getList(1, Config3._Sockets, this); + } + hasSockets() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initSockets(length) { + return capnp_ts_1.Struct.initList(1, Config3._Sockets, length, this); + } + setSockets(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptV8Flags(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownV8Flags() { + return capnp_ts_1.Struct.disown(this.getV8Flags()); + } + getV8Flags() { + return capnp_ts_1.Struct.getList(2, capnp.TextList, this); + } + hasV8Flags() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initV8Flags(length) { + return capnp_ts_1.Struct.initList(2, capnp.TextList, length, this); + } + setV8Flags(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + adoptExtensions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this)); + } + disownExtensions() { + return capnp_ts_1.Struct.disown(this.getExtensions()); + } + getExtensions() { + return capnp_ts_1.Struct.getList(3, Config3._Extensions, this); + } + hasExtensions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this)); + } + initExtensions(length) { + return capnp_ts_1.Struct.initList(3, Config3._Extensions, length, this); + } + setExtensions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this)); + } + toString() { + return "Config_" + super.toString(); + } + }; + exports.Config = Config3; + Config3._capnp = { displayName: "Config", id: "8794486c76aaa7d6", size: new capnp_ts_1.ObjectSize(0, 4) }; + var Socket_Https = class extends capnp_ts_1.Struct { + adoptOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownOptions() { + return capnp_ts_1.Struct.disown(this.getOptions()); + } + getOptions() { + return capnp_ts_1.Struct.getStruct(2, HttpOptions, this); + } + hasOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initOptions() { + return capnp_ts_1.Struct.initStructAt(2, HttpOptions, this); + } + setOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + adoptTlsOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this)); + } + disownTlsOptions() { + return capnp_ts_1.Struct.disown(this.getTlsOptions()); + } + getTlsOptions() { + return capnp_ts_1.Struct.getStruct(3, TlsOptions, this); + } + hasTlsOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this)); + } + initTlsOptions() { + return capnp_ts_1.Struct.initStructAt(3, TlsOptions, this); + } + setTlsOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this)); + } + toString() { + return "Socket_Https_" + super.toString(); + } + }; + exports.Socket_Https = Socket_Https; + Socket_Https._capnp = { displayName: "https", id: "de123876383cbbdc", size: new capnp_ts_1.ObjectSize(8, 5) }; + var Socket_Which; + (function(Socket_Which2) { + Socket_Which2[Socket_Which2["HTTP"] = 0] = "HTTP"; + Socket_Which2[Socket_Which2["HTTPS"] = 1] = "HTTPS"; + })(Socket_Which = exports.Socket_Which || (exports.Socket_Which = {})); + var Socket2 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getAddress() { + return capnp_ts_1.Struct.getText(1, this); + } + setAddress(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + adoptHttp(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownHttp() { + return capnp_ts_1.Struct.disown(this.getHttp()); + } + getHttp() { + capnp_ts_1.Struct.testWhich("http", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getStruct(2, HttpOptions, this); + } + hasHttp() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initHttp() { + capnp_ts_1.Struct.setUint16(0, 0, this); + return capnp_ts_1.Struct.initStructAt(2, HttpOptions, this); + } + isHttp() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setHttp(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + getHttps() { + capnp_ts_1.Struct.testWhich("https", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getAs(Socket_Https, this); + } + initHttps() { + capnp_ts_1.Struct.setUint16(0, 1, this); + return capnp_ts_1.Struct.getAs(Socket_Https, this); + } + isHttps() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setHttps() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + adoptService(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(4, this)); + } + disownService() { + return capnp_ts_1.Struct.disown(this.getService()); + } + getService() { + return capnp_ts_1.Struct.getStruct(4, ServiceDesignator2, this); + } + hasService() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(4, this)); + } + initService() { + return capnp_ts_1.Struct.initStructAt(4, ServiceDesignator2, this); + } + setService(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(4, this)); + } + toString() { + return "Socket_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Socket = Socket2; + Socket2.HTTP = Socket_Which.HTTP; + Socket2.HTTPS = Socket_Which.HTTPS; + Socket2._capnp = { displayName: "Socket", id: "9a0eba45530ee79f", size: new capnp_ts_1.ObjectSize(8, 5) }; + var Service_Which; + (function(Service_Which2) { + Service_Which2[Service_Which2["UNSPECIFIED"] = 0] = "UNSPECIFIED"; + Service_Which2[Service_Which2["WORKER"] = 1] = "WORKER"; + Service_Which2[Service_Which2["NETWORK"] = 2] = "NETWORK"; + Service_Which2[Service_Which2["EXTERNAL"] = 3] = "EXTERNAL"; + Service_Which2[Service_Which2["DISK"] = 4] = "DISK"; + })(Service_Which = exports.Service_Which || (exports.Service_Which = {})); + var Service4 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + isUnspecified() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setUnspecified() { + capnp_ts_1.Struct.setUint16(0, 0, this); + } + adoptWorker(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownWorker() { + return capnp_ts_1.Struct.disown(this.getWorker()); + } + getWorker() { + capnp_ts_1.Struct.testWhich("worker", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getStruct(1, Worker2, this); + } + hasWorker() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initWorker() { + capnp_ts_1.Struct.setUint16(0, 1, this); + return capnp_ts_1.Struct.initStructAt(1, Worker2, this); + } + isWorker() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setWorker(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptNetwork(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownNetwork() { + return capnp_ts_1.Struct.disown(this.getNetwork()); + } + getNetwork() { + capnp_ts_1.Struct.testWhich("network", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getStruct(1, Network, this); + } + hasNetwork() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initNetwork() { + capnp_ts_1.Struct.setUint16(0, 2, this); + return capnp_ts_1.Struct.initStructAt(1, Network, this); + } + isNetwork() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setNetwork(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptExternal(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownExternal() { + return capnp_ts_1.Struct.disown(this.getExternal()); + } + getExternal() { + capnp_ts_1.Struct.testWhich("external", capnp_ts_1.Struct.getUint16(0, this), 3, this); + return capnp_ts_1.Struct.getStruct(1, ExternalServer2, this); + } + hasExternal() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initExternal() { + capnp_ts_1.Struct.setUint16(0, 3, this); + return capnp_ts_1.Struct.initStructAt(1, ExternalServer2, this); + } + isExternal() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setExternal(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptDisk(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownDisk() { + return capnp_ts_1.Struct.disown(this.getDisk()); + } + getDisk() { + capnp_ts_1.Struct.testWhich("disk", capnp_ts_1.Struct.getUint16(0, this), 4, this); + return capnp_ts_1.Struct.getStruct(1, DiskDirectory, this); + } + hasDisk() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initDisk() { + capnp_ts_1.Struct.setUint16(0, 4, this); + return capnp_ts_1.Struct.initStructAt(1, DiskDirectory, this); + } + isDisk() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setDisk(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + toString() { + return "Service_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Service = Service4; + Service4.UNSPECIFIED = Service_Which.UNSPECIFIED; + Service4.WORKER = Service_Which.WORKER; + Service4.NETWORK = Service_Which.NETWORK; + Service4.EXTERNAL = Service_Which.EXTERNAL; + Service4.DISK = Service_Which.DISK; + Service4._capnp = { displayName: "Service", id: "e5c88e8bb7bcb6b9", size: new capnp_ts_1.ObjectSize(8, 2) }; + var ServiceDesignator2 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getEntrypoint() { + return capnp_ts_1.Struct.getText(1, this); + } + setEntrypoint(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "ServiceDesignator_" + super.toString(); + } + }; + exports.ServiceDesignator = ServiceDesignator2; + ServiceDesignator2._capnp = { displayName: "ServiceDesignator", id: "ae8ec91cee724450", size: new capnp_ts_1.ObjectSize(0, 2) }; + var Worker_Module_Which; + (function(Worker_Module_Which2) { + Worker_Module_Which2[Worker_Module_Which2["ES_MODULE"] = 0] = "ES_MODULE"; + Worker_Module_Which2[Worker_Module_Which2["COMMON_JS_MODULE"] = 1] = "COMMON_JS_MODULE"; + Worker_Module_Which2[Worker_Module_Which2["TEXT"] = 2] = "TEXT"; + Worker_Module_Which2[Worker_Module_Which2["DATA"] = 3] = "DATA"; + Worker_Module_Which2[Worker_Module_Which2["WASM"] = 4] = "WASM"; + Worker_Module_Which2[Worker_Module_Which2["JSON"] = 5] = "JSON"; + Worker_Module_Which2[Worker_Module_Which2["NODE_JS_COMPAT_MODULE"] = 6] = "NODE_JS_COMPAT_MODULE"; + })(Worker_Module_Which = exports.Worker_Module_Which || (exports.Worker_Module_Which = {})); + var Worker_Module3 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getEsModule() { + capnp_ts_1.Struct.testWhich("esModule", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getText(1, this); + } + isEsModule() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setEsModule(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getCommonJsModule() { + capnp_ts_1.Struct.testWhich("commonJsModule", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getText(1, this); + } + isCommonJsModule() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setCommonJsModule(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getText() { + capnp_ts_1.Struct.testWhich("text", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getText(1, this); + } + isText() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setText(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.setText(1, value, this); + } + adoptData(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownData() { + return capnp_ts_1.Struct.disown(this.getData()); + } + getData() { + capnp_ts_1.Struct.testWhich("data", capnp_ts_1.Struct.getUint16(0, this), 3, this); + return capnp_ts_1.Struct.getData(1, this); + } + hasData() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initData(length) { + capnp_ts_1.Struct.setUint16(0, 3, this); + return capnp_ts_1.Struct.initData(1, length, this); + } + isData() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setData(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptWasm(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownWasm() { + return capnp_ts_1.Struct.disown(this.getWasm()); + } + getWasm() { + capnp_ts_1.Struct.testWhich("wasm", capnp_ts_1.Struct.getUint16(0, this), 4, this); + return capnp_ts_1.Struct.getData(1, this); + } + hasWasm() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initWasm(length) { + capnp_ts_1.Struct.setUint16(0, 4, this); + return capnp_ts_1.Struct.initData(1, length, this); + } + isWasm() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setWasm(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getJson() { + capnp_ts_1.Struct.testWhich("json", capnp_ts_1.Struct.getUint16(0, this), 5, this); + return capnp_ts_1.Struct.getText(1, this); + } + isJson() { + return capnp_ts_1.Struct.getUint16(0, this) === 5; + } + setJson(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getNodeJsCompatModule() { + capnp_ts_1.Struct.testWhich("nodeJsCompatModule", capnp_ts_1.Struct.getUint16(0, this), 6, this); + return capnp_ts_1.Struct.getText(1, this); + } + isNodeJsCompatModule() { + return capnp_ts_1.Struct.getUint16(0, this) === 6; + } + setNodeJsCompatModule(value) { + capnp_ts_1.Struct.setUint16(0, 6, this); + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "Worker_Module_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_Module = Worker_Module3; + Worker_Module3.ES_MODULE = Worker_Module_Which.ES_MODULE; + Worker_Module3.COMMON_JS_MODULE = Worker_Module_Which.COMMON_JS_MODULE; + Worker_Module3.TEXT = Worker_Module_Which.TEXT; + Worker_Module3.DATA = Worker_Module_Which.DATA; + Worker_Module3.WASM = Worker_Module_Which.WASM; + Worker_Module3.JSON = Worker_Module_Which.JSON; + Worker_Module3.NODE_JS_COMPAT_MODULE = Worker_Module_Which.NODE_JS_COMPAT_MODULE; + Worker_Module3._capnp = { displayName: "Module", id: "d9d87a63770a12f3", size: new capnp_ts_1.ObjectSize(8, 2) }; + var Worker_Binding_Type_Which; + (function(Worker_Binding_Type_Which2) { + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["UNSPECIFIED"] = 0] = "UNSPECIFIED"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["TEXT"] = 1] = "TEXT"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["DATA"] = 2] = "DATA"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["JSON"] = 3] = "JSON"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["WASM"] = 4] = "WASM"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["CRYPTO_KEY"] = 5] = "CRYPTO_KEY"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["SERVICE"] = 6] = "SERVICE"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["DURABLE_OBJECT_NAMESPACE"] = 7] = "DURABLE_OBJECT_NAMESPACE"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["KV_NAMESPACE"] = 8] = "KV_NAMESPACE"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["R2BUCKET"] = 9] = "R2BUCKET"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["R2ADMIN"] = 10] = "R2ADMIN"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["QUEUE"] = 11] = "QUEUE"; + Worker_Binding_Type_Which2[Worker_Binding_Type_Which2["ANALYTICS_ENGINE"] = 12] = "ANALYTICS_ENGINE"; + })(Worker_Binding_Type_Which = exports.Worker_Binding_Type_Which || (exports.Worker_Binding_Type_Which = {})); + var Worker_Binding_Type = class extends capnp_ts_1.Struct { + isUnspecified() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setUnspecified() { + capnp_ts_1.Struct.setUint16(0, 0, this); + } + isText() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setText() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + isData() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setData() { + capnp_ts_1.Struct.setUint16(0, 2, this); + } + isJson() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setJson() { + capnp_ts_1.Struct.setUint16(0, 3, this); + } + isWasm() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setWasm() { + capnp_ts_1.Struct.setUint16(0, 4, this); + } + adoptCryptoKey(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownCryptoKey() { + return capnp_ts_1.Struct.disown(this.getCryptoKey()); + } + getCryptoKey() { + capnp_ts_1.Struct.testWhich("cryptoKey", capnp_ts_1.Struct.getUint16(0, this), 5, this); + return capnp_ts_1.Struct.getList(0, capnp.Uint16List, this); + } + hasCryptoKey() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initCryptoKey(length) { + capnp_ts_1.Struct.setUint16(0, 5, this); + return capnp_ts_1.Struct.initList(0, capnp.Uint16List, length, this); + } + isCryptoKey() { + return capnp_ts_1.Struct.getUint16(0, this) === 5; + } + setCryptoKey(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + isService() { + return capnp_ts_1.Struct.getUint16(0, this) === 6; + } + setService() { + capnp_ts_1.Struct.setUint16(0, 6, this); + } + isDurableObjectNamespace() { + return capnp_ts_1.Struct.getUint16(0, this) === 7; + } + setDurableObjectNamespace() { + capnp_ts_1.Struct.setUint16(0, 7, this); + } + isKvNamespace() { + return capnp_ts_1.Struct.getUint16(0, this) === 8; + } + setKvNamespace() { + capnp_ts_1.Struct.setUint16(0, 8, this); + } + isR2Bucket() { + return capnp_ts_1.Struct.getUint16(0, this) === 9; + } + setR2Bucket() { + capnp_ts_1.Struct.setUint16(0, 9, this); + } + isR2Admin() { + return capnp_ts_1.Struct.getUint16(0, this) === 10; + } + setR2Admin() { + capnp_ts_1.Struct.setUint16(0, 10, this); + } + isQueue() { + return capnp_ts_1.Struct.getUint16(0, this) === 11; + } + setQueue() { + capnp_ts_1.Struct.setUint16(0, 11, this); + } + isAnalyticsEngine() { + return capnp_ts_1.Struct.getUint16(0, this) === 12; + } + setAnalyticsEngine() { + capnp_ts_1.Struct.setUint16(0, 12, this); + } + toString() { + return "Worker_Binding_Type_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_Binding_Type = Worker_Binding_Type; + Worker_Binding_Type.UNSPECIFIED = Worker_Binding_Type_Which.UNSPECIFIED; + Worker_Binding_Type.TEXT = Worker_Binding_Type_Which.TEXT; + Worker_Binding_Type.DATA = Worker_Binding_Type_Which.DATA; + Worker_Binding_Type.JSON = Worker_Binding_Type_Which.JSON; + Worker_Binding_Type.WASM = Worker_Binding_Type_Which.WASM; + Worker_Binding_Type.CRYPTO_KEY = Worker_Binding_Type_Which.CRYPTO_KEY; + Worker_Binding_Type.SERVICE = Worker_Binding_Type_Which.SERVICE; + Worker_Binding_Type.DURABLE_OBJECT_NAMESPACE = Worker_Binding_Type_Which.DURABLE_OBJECT_NAMESPACE; + Worker_Binding_Type.KV_NAMESPACE = Worker_Binding_Type_Which.KV_NAMESPACE; + Worker_Binding_Type.R2BUCKET = Worker_Binding_Type_Which.R2BUCKET; + Worker_Binding_Type.R2ADMIN = Worker_Binding_Type_Which.R2ADMIN; + Worker_Binding_Type.QUEUE = Worker_Binding_Type_Which.QUEUE; + Worker_Binding_Type.ANALYTICS_ENGINE = Worker_Binding_Type_Which.ANALYTICS_ENGINE; + Worker_Binding_Type._capnp = { displayName: "Type", id: "8906a1296519bf8a", size: new capnp_ts_1.ObjectSize(8, 1) }; + var Worker_Binding_DurableObjectNamespaceDesignator2 = class extends capnp_ts_1.Struct { + getClassName() { + return capnp_ts_1.Struct.getText(0, this); + } + setClassName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getServiceName() { + return capnp_ts_1.Struct.getText(1, this); + } + setServiceName(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "Worker_Binding_DurableObjectNamespaceDesignator_" + super.toString(); + } + }; + exports.Worker_Binding_DurableObjectNamespaceDesignator = Worker_Binding_DurableObjectNamespaceDesignator2; + Worker_Binding_DurableObjectNamespaceDesignator2._capnp = { displayName: "DurableObjectNamespaceDesignator", id: "804f144ff477aac7", size: new capnp_ts_1.ObjectSize(0, 2) }; + var Worker_Binding_CryptoKey_Usage2; + (function(Worker_Binding_CryptoKey_Usage3) { + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["ENCRYPT"] = 0] = "ENCRYPT"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["DECRYPT"] = 1] = "DECRYPT"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["SIGN"] = 2] = "SIGN"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["VERIFY"] = 3] = "VERIFY"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["DERIVE_KEY"] = 4] = "DERIVE_KEY"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["DERIVE_BITS"] = 5] = "DERIVE_BITS"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["WRAP_KEY"] = 6] = "WRAP_KEY"; + Worker_Binding_CryptoKey_Usage3[Worker_Binding_CryptoKey_Usage3["UNWRAP_KEY"] = 7] = "UNWRAP_KEY"; + })(Worker_Binding_CryptoKey_Usage2 = exports.Worker_Binding_CryptoKey_Usage || (exports.Worker_Binding_CryptoKey_Usage = {})); + var Worker_Binding_CryptoKey_Algorithm_Which; + (function(Worker_Binding_CryptoKey_Algorithm_Which2) { + Worker_Binding_CryptoKey_Algorithm_Which2[Worker_Binding_CryptoKey_Algorithm_Which2["NAME"] = 0] = "NAME"; + Worker_Binding_CryptoKey_Algorithm_Which2[Worker_Binding_CryptoKey_Algorithm_Which2["JSON"] = 1] = "JSON"; + })(Worker_Binding_CryptoKey_Algorithm_Which = exports.Worker_Binding_CryptoKey_Algorithm_Which || (exports.Worker_Binding_CryptoKey_Algorithm_Which = {})); + var Worker_Binding_CryptoKey_Algorithm = class extends capnp_ts_1.Struct { + getName() { + capnp_ts_1.Struct.testWhich("name", capnp_ts_1.Struct.getUint16(2, this), 0, this); + return capnp_ts_1.Struct.getText(1, this); + } + isName() { + return capnp_ts_1.Struct.getUint16(2, this) === 0; + } + setName(value) { + capnp_ts_1.Struct.setUint16(2, 0, this); + capnp_ts_1.Struct.setText(1, value, this); + } + getJson() { + capnp_ts_1.Struct.testWhich("json", capnp_ts_1.Struct.getUint16(2, this), 1, this); + return capnp_ts_1.Struct.getText(1, this); + } + isJson() { + return capnp_ts_1.Struct.getUint16(2, this) === 1; + } + setJson(value) { + capnp_ts_1.Struct.setUint16(2, 1, this); + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "Worker_Binding_CryptoKey_Algorithm_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(2, this); + } + }; + exports.Worker_Binding_CryptoKey_Algorithm = Worker_Binding_CryptoKey_Algorithm; + Worker_Binding_CryptoKey_Algorithm.NAME = Worker_Binding_CryptoKey_Algorithm_Which.NAME; + Worker_Binding_CryptoKey_Algorithm.JSON = Worker_Binding_CryptoKey_Algorithm_Which.JSON; + Worker_Binding_CryptoKey_Algorithm._capnp = { displayName: "algorithm", id: "a1a040c5e00d7021", size: new capnp_ts_1.ObjectSize(8, 3) }; + var Worker_Binding_CryptoKey_Which; + (function(Worker_Binding_CryptoKey_Which2) { + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["RAW"] = 0] = "RAW"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["HEX"] = 1] = "HEX"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["BASE64"] = 2] = "BASE64"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["PKCS8"] = 3] = "PKCS8"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["SPKI"] = 4] = "SPKI"; + Worker_Binding_CryptoKey_Which2[Worker_Binding_CryptoKey_Which2["JWK"] = 5] = "JWK"; + })(Worker_Binding_CryptoKey_Which = exports.Worker_Binding_CryptoKey_Which || (exports.Worker_Binding_CryptoKey_Which = {})); + var Worker_Binding_CryptoKey = class extends capnp_ts_1.Struct { + adoptRaw(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownRaw() { + return capnp_ts_1.Struct.disown(this.getRaw()); + } + getRaw() { + capnp_ts_1.Struct.testWhich("raw", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getData(0, this); + } + hasRaw() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initRaw(length) { + capnp_ts_1.Struct.setUint16(0, 0, this); + return capnp_ts_1.Struct.initData(0, length, this); + } + isRaw() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setRaw(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + getHex() { + capnp_ts_1.Struct.testWhich("hex", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getText(0, this); + } + isHex() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setHex(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getBase64() { + capnp_ts_1.Struct.testWhich("base64", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getText(0, this); + } + isBase64() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setBase64(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getPkcs8() { + capnp_ts_1.Struct.testWhich("pkcs8", capnp_ts_1.Struct.getUint16(0, this), 3, this); + return capnp_ts_1.Struct.getText(0, this); + } + isPkcs8() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setPkcs8(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getSpki() { + capnp_ts_1.Struct.testWhich("spki", capnp_ts_1.Struct.getUint16(0, this), 4, this); + return capnp_ts_1.Struct.getText(0, this); + } + isSpki() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setSpki(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getJwk() { + capnp_ts_1.Struct.testWhich("jwk", capnp_ts_1.Struct.getUint16(0, this), 5, this); + return capnp_ts_1.Struct.getText(0, this); + } + isJwk() { + return capnp_ts_1.Struct.getUint16(0, this) === 5; + } + setJwk(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getAlgorithm() { + return capnp_ts_1.Struct.getAs(Worker_Binding_CryptoKey_Algorithm, this); + } + initAlgorithm() { + return capnp_ts_1.Struct.getAs(Worker_Binding_CryptoKey_Algorithm, this); + } + getExtractable() { + return capnp_ts_1.Struct.getBit(32, this, Worker_Binding_CryptoKey._capnp.defaultExtractable); + } + setExtractable(value) { + capnp_ts_1.Struct.setBit(32, value, this); + } + adoptUsages(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownUsages() { + return capnp_ts_1.Struct.disown(this.getUsages()); + } + getUsages() { + return capnp_ts_1.Struct.getList(2, capnp.Uint16List, this); + } + hasUsages() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initUsages(length) { + return capnp_ts_1.Struct.initList(2, capnp.Uint16List, length, this); + } + setUsages(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + toString() { + return "Worker_Binding_CryptoKey_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_Binding_CryptoKey = Worker_Binding_CryptoKey; + Worker_Binding_CryptoKey.RAW = Worker_Binding_CryptoKey_Which.RAW; + Worker_Binding_CryptoKey.HEX = Worker_Binding_CryptoKey_Which.HEX; + Worker_Binding_CryptoKey.BASE64 = Worker_Binding_CryptoKey_Which.BASE64; + Worker_Binding_CryptoKey.PKCS8 = Worker_Binding_CryptoKey_Which.PKCS8; + Worker_Binding_CryptoKey.SPKI = Worker_Binding_CryptoKey_Which.SPKI; + Worker_Binding_CryptoKey.JWK = Worker_Binding_CryptoKey_Which.JWK; + Worker_Binding_CryptoKey.Usage = Worker_Binding_CryptoKey_Usage2; + Worker_Binding_CryptoKey._capnp = { displayName: "CryptoKey", id: "b5e1bff0e57d6eb0", size: new capnp_ts_1.ObjectSize(8, 3), defaultExtractable: capnp.getBitMask(false, 0) }; + var Worker_Binding_WrappedBinding = class extends capnp_ts_1.Struct { + getModuleName() { + return capnp_ts_1.Struct.getText(0, this); + } + setModuleName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getEntrypoint() { + return capnp_ts_1.Struct.getText(1, this, Worker_Binding_WrappedBinding._capnp.defaultEntrypoint); + } + setEntrypoint(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + adoptInnerBindings(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownInnerBindings() { + return capnp_ts_1.Struct.disown(this.getInnerBindings()); + } + getInnerBindings() { + return capnp_ts_1.Struct.getList(2, Worker_Binding_WrappedBinding._InnerBindings, this); + } + hasInnerBindings() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initInnerBindings(length) { + return capnp_ts_1.Struct.initList(2, Worker_Binding_WrappedBinding._InnerBindings, length, this); + } + setInnerBindings(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + toString() { + return "Worker_Binding_WrappedBinding_" + super.toString(); + } + }; + exports.Worker_Binding_WrappedBinding = Worker_Binding_WrappedBinding; + Worker_Binding_WrappedBinding._capnp = { displayName: "WrappedBinding", id: "e6f066b75f0ea113", size: new capnp_ts_1.ObjectSize(0, 3), defaultEntrypoint: "default" }; + var Worker_Binding_Parameter = class extends capnp_ts_1.Struct { + adoptType(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownType() { + return capnp_ts_1.Struct.disown(this.getType()); + } + getType() { + return capnp_ts_1.Struct.getStruct(1, Worker_Binding_Type, this); + } + hasType() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initType() { + return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_Type, this); + } + setType(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getOptional() { + return capnp_ts_1.Struct.getBit(16, this); + } + setOptional(value) { + capnp_ts_1.Struct.setBit(16, value, this); + } + toString() { + return "Worker_Binding_Parameter_" + super.toString(); + } + }; + exports.Worker_Binding_Parameter = Worker_Binding_Parameter; + Worker_Binding_Parameter._capnp = { displayName: "parameter", id: "dc57e1258d26d152", size: new capnp_ts_1.ObjectSize(8, 2) }; + var Worker_Binding_Which; + (function(Worker_Binding_Which2) { + Worker_Binding_Which2[Worker_Binding_Which2["UNSPECIFIED"] = 0] = "UNSPECIFIED"; + Worker_Binding_Which2[Worker_Binding_Which2["PARAMETER"] = 1] = "PARAMETER"; + Worker_Binding_Which2[Worker_Binding_Which2["TEXT"] = 2] = "TEXT"; + Worker_Binding_Which2[Worker_Binding_Which2["DATA"] = 3] = "DATA"; + Worker_Binding_Which2[Worker_Binding_Which2["JSON"] = 4] = "JSON"; + Worker_Binding_Which2[Worker_Binding_Which2["WASM_MODULE"] = 5] = "WASM_MODULE"; + Worker_Binding_Which2[Worker_Binding_Which2["CRYPTO_KEY"] = 6] = "CRYPTO_KEY"; + Worker_Binding_Which2[Worker_Binding_Which2["SERVICE"] = 7] = "SERVICE"; + Worker_Binding_Which2[Worker_Binding_Which2["DURABLE_OBJECT_NAMESPACE"] = 8] = "DURABLE_OBJECT_NAMESPACE"; + Worker_Binding_Which2[Worker_Binding_Which2["KV_NAMESPACE"] = 9] = "KV_NAMESPACE"; + Worker_Binding_Which2[Worker_Binding_Which2["R2BUCKET"] = 10] = "R2BUCKET"; + Worker_Binding_Which2[Worker_Binding_Which2["R2ADMIN"] = 11] = "R2ADMIN"; + Worker_Binding_Which2[Worker_Binding_Which2["WRAPPED"] = 12] = "WRAPPED"; + Worker_Binding_Which2[Worker_Binding_Which2["QUEUE"] = 13] = "QUEUE"; + Worker_Binding_Which2[Worker_Binding_Which2["FROM_ENVIRONMENT"] = 14] = "FROM_ENVIRONMENT"; + Worker_Binding_Which2[Worker_Binding_Which2["ANALYTICS_ENGINE"] = 15] = "ANALYTICS_ENGINE"; + })(Worker_Binding_Which = exports.Worker_Binding_Which || (exports.Worker_Binding_Which = {})); + var Worker_Binding4 = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + isUnspecified() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setUnspecified() { + capnp_ts_1.Struct.setUint16(0, 0, this); + } + getParameter() { + capnp_ts_1.Struct.testWhich("parameter", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getAs(Worker_Binding_Parameter, this); + } + initParameter() { + capnp_ts_1.Struct.setUint16(0, 1, this); + return capnp_ts_1.Struct.getAs(Worker_Binding_Parameter, this); + } + isParameter() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setParameter() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + getText() { + capnp_ts_1.Struct.testWhich("text", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getText(1, this); + } + isText() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setText(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.setText(1, value, this); + } + adoptData(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownData() { + return capnp_ts_1.Struct.disown(this.getData()); + } + getData() { + capnp_ts_1.Struct.testWhich("data", capnp_ts_1.Struct.getUint16(0, this), 3, this); + return capnp_ts_1.Struct.getData(1, this); + } + hasData() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initData(length) { + capnp_ts_1.Struct.setUint16(0, 3, this); + return capnp_ts_1.Struct.initData(1, length, this); + } + isData() { + return capnp_ts_1.Struct.getUint16(0, this) === 3; + } + setData(value) { + capnp_ts_1.Struct.setUint16(0, 3, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getJson() { + capnp_ts_1.Struct.testWhich("json", capnp_ts_1.Struct.getUint16(0, this), 4, this); + return capnp_ts_1.Struct.getText(1, this); + } + isJson() { + return capnp_ts_1.Struct.getUint16(0, this) === 4; + } + setJson(value) { + capnp_ts_1.Struct.setUint16(0, 4, this); + capnp_ts_1.Struct.setText(1, value, this); + } + adoptWasmModule(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownWasmModule() { + return capnp_ts_1.Struct.disown(this.getWasmModule()); + } + getWasmModule() { + capnp_ts_1.Struct.testWhich("wasmModule", capnp_ts_1.Struct.getUint16(0, this), 5, this); + return capnp_ts_1.Struct.getData(1, this); + } + hasWasmModule() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initWasmModule(length) { + capnp_ts_1.Struct.setUint16(0, 5, this); + return capnp_ts_1.Struct.initData(1, length, this); + } + isWasmModule() { + return capnp_ts_1.Struct.getUint16(0, this) === 5; + } + setWasmModule(value) { + capnp_ts_1.Struct.setUint16(0, 5, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptCryptoKey(value) { + capnp_ts_1.Struct.setUint16(0, 6, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownCryptoKey() { + return capnp_ts_1.Struct.disown(this.getCryptoKey()); + } + getCryptoKey() { + capnp_ts_1.Struct.testWhich("cryptoKey", capnp_ts_1.Struct.getUint16(0, this), 6, this); + return capnp_ts_1.Struct.getStruct(1, Worker_Binding_CryptoKey, this); + } + hasCryptoKey() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initCryptoKey() { + capnp_ts_1.Struct.setUint16(0, 6, this); + return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_CryptoKey, this); + } + isCryptoKey() { + return capnp_ts_1.Struct.getUint16(0, this) === 6; + } + setCryptoKey(value) { + capnp_ts_1.Struct.setUint16(0, 6, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptService(value) { + capnp_ts_1.Struct.setUint16(0, 7, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownService() { + return capnp_ts_1.Struct.disown(this.getService()); + } + getService() { + capnp_ts_1.Struct.testWhich("service", capnp_ts_1.Struct.getUint16(0, this), 7, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasService() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initService() { + capnp_ts_1.Struct.setUint16(0, 7, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isService() { + return capnp_ts_1.Struct.getUint16(0, this) === 7; + } + setService(value) { + capnp_ts_1.Struct.setUint16(0, 7, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptDurableObjectNamespace(value) { + capnp_ts_1.Struct.setUint16(0, 8, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownDurableObjectNamespace() { + return capnp_ts_1.Struct.disown(this.getDurableObjectNamespace()); + } + getDurableObjectNamespace() { + capnp_ts_1.Struct.testWhich("durableObjectNamespace", capnp_ts_1.Struct.getUint16(0, this), 8, this); + return capnp_ts_1.Struct.getStruct(1, Worker_Binding_DurableObjectNamespaceDesignator2, this); + } + hasDurableObjectNamespace() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initDurableObjectNamespace() { + capnp_ts_1.Struct.setUint16(0, 8, this); + return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_DurableObjectNamespaceDesignator2, this); + } + isDurableObjectNamespace() { + return capnp_ts_1.Struct.getUint16(0, this) === 8; + } + setDurableObjectNamespace(value) { + capnp_ts_1.Struct.setUint16(0, 8, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptKvNamespace(value) { + capnp_ts_1.Struct.setUint16(0, 9, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownKvNamespace() { + return capnp_ts_1.Struct.disown(this.getKvNamespace()); + } + getKvNamespace() { + capnp_ts_1.Struct.testWhich("kvNamespace", capnp_ts_1.Struct.getUint16(0, this), 9, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasKvNamespace() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initKvNamespace() { + capnp_ts_1.Struct.setUint16(0, 9, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isKvNamespace() { + return capnp_ts_1.Struct.getUint16(0, this) === 9; + } + setKvNamespace(value) { + capnp_ts_1.Struct.setUint16(0, 9, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptR2Bucket(value) { + capnp_ts_1.Struct.setUint16(0, 10, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownR2Bucket() { + return capnp_ts_1.Struct.disown(this.getR2Bucket()); + } + getR2Bucket() { + capnp_ts_1.Struct.testWhich("r2Bucket", capnp_ts_1.Struct.getUint16(0, this), 10, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasR2Bucket() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initR2Bucket() { + capnp_ts_1.Struct.setUint16(0, 10, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isR2Bucket() { + return capnp_ts_1.Struct.getUint16(0, this) === 10; + } + setR2Bucket(value) { + capnp_ts_1.Struct.setUint16(0, 10, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptR2Admin(value) { + capnp_ts_1.Struct.setUint16(0, 11, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownR2Admin() { + return capnp_ts_1.Struct.disown(this.getR2Admin()); + } + getR2Admin() { + capnp_ts_1.Struct.testWhich("r2Admin", capnp_ts_1.Struct.getUint16(0, this), 11, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasR2Admin() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initR2Admin() { + capnp_ts_1.Struct.setUint16(0, 11, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isR2Admin() { + return capnp_ts_1.Struct.getUint16(0, this) === 11; + } + setR2Admin(value) { + capnp_ts_1.Struct.setUint16(0, 11, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptWrapped(value) { + capnp_ts_1.Struct.setUint16(0, 12, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownWrapped() { + return capnp_ts_1.Struct.disown(this.getWrapped()); + } + getWrapped() { + capnp_ts_1.Struct.testWhich("wrapped", capnp_ts_1.Struct.getUint16(0, this), 12, this); + return capnp_ts_1.Struct.getStruct(1, Worker_Binding_WrappedBinding, this); + } + hasWrapped() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initWrapped() { + capnp_ts_1.Struct.setUint16(0, 12, this); + return capnp_ts_1.Struct.initStructAt(1, Worker_Binding_WrappedBinding, this); + } + isWrapped() { + return capnp_ts_1.Struct.getUint16(0, this) === 12; + } + setWrapped(value) { + capnp_ts_1.Struct.setUint16(0, 12, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptQueue(value) { + capnp_ts_1.Struct.setUint16(0, 13, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownQueue() { + return capnp_ts_1.Struct.disown(this.getQueue()); + } + getQueue() { + capnp_ts_1.Struct.testWhich("queue", capnp_ts_1.Struct.getUint16(0, this), 13, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasQueue() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initQueue() { + capnp_ts_1.Struct.setUint16(0, 13, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isQueue() { + return capnp_ts_1.Struct.getUint16(0, this) === 13; + } + setQueue(value) { + capnp_ts_1.Struct.setUint16(0, 13, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getFromEnvironment() { + capnp_ts_1.Struct.testWhich("fromEnvironment", capnp_ts_1.Struct.getUint16(0, this), 14, this); + return capnp_ts_1.Struct.getText(1, this); + } + isFromEnvironment() { + return capnp_ts_1.Struct.getUint16(0, this) === 14; + } + setFromEnvironment(value) { + capnp_ts_1.Struct.setUint16(0, 14, this); + capnp_ts_1.Struct.setText(1, value, this); + } + adoptAnalyticsEngine(value) { + capnp_ts_1.Struct.setUint16(0, 15, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownAnalyticsEngine() { + return capnp_ts_1.Struct.disown(this.getAnalyticsEngine()); + } + getAnalyticsEngine() { + capnp_ts_1.Struct.testWhich("analyticsEngine", capnp_ts_1.Struct.getUint16(0, this), 15, this); + return capnp_ts_1.Struct.getStruct(1, ServiceDesignator2, this); + } + hasAnalyticsEngine() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initAnalyticsEngine() { + capnp_ts_1.Struct.setUint16(0, 15, this); + return capnp_ts_1.Struct.initStructAt(1, ServiceDesignator2, this); + } + isAnalyticsEngine() { + return capnp_ts_1.Struct.getUint16(0, this) === 15; + } + setAnalyticsEngine(value) { + capnp_ts_1.Struct.setUint16(0, 15, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + toString() { + return "Worker_Binding_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_Binding = Worker_Binding4; + Worker_Binding4.UNSPECIFIED = Worker_Binding_Which.UNSPECIFIED; + Worker_Binding4.PARAMETER = Worker_Binding_Which.PARAMETER; + Worker_Binding4.TEXT = Worker_Binding_Which.TEXT; + Worker_Binding4.DATA = Worker_Binding_Which.DATA; + Worker_Binding4.JSON = Worker_Binding_Which.JSON; + Worker_Binding4.WASM_MODULE = Worker_Binding_Which.WASM_MODULE; + Worker_Binding4.CRYPTO_KEY = Worker_Binding_Which.CRYPTO_KEY; + Worker_Binding4.SERVICE = Worker_Binding_Which.SERVICE; + Worker_Binding4.DURABLE_OBJECT_NAMESPACE = Worker_Binding_Which.DURABLE_OBJECT_NAMESPACE; + Worker_Binding4.KV_NAMESPACE = Worker_Binding_Which.KV_NAMESPACE; + Worker_Binding4.R2BUCKET = Worker_Binding_Which.R2BUCKET; + Worker_Binding4.R2ADMIN = Worker_Binding_Which.R2ADMIN; + Worker_Binding4.WRAPPED = Worker_Binding_Which.WRAPPED; + Worker_Binding4.QUEUE = Worker_Binding_Which.QUEUE; + Worker_Binding4.FROM_ENVIRONMENT = Worker_Binding_Which.FROM_ENVIRONMENT; + Worker_Binding4.ANALYTICS_ENGINE = Worker_Binding_Which.ANALYTICS_ENGINE; + Worker_Binding4.Type = Worker_Binding_Type; + Worker_Binding4.DurableObjectNamespaceDesignator = Worker_Binding_DurableObjectNamespaceDesignator2; + Worker_Binding4.CryptoKey = Worker_Binding_CryptoKey; + Worker_Binding4.WrappedBinding = Worker_Binding_WrappedBinding; + Worker_Binding4._capnp = { displayName: "Binding", id: "8e7e492fd7e35f3e", size: new capnp_ts_1.ObjectSize(8, 2) }; + var Worker_DurableObjectNamespace_Which; + (function(Worker_DurableObjectNamespace_Which2) { + Worker_DurableObjectNamespace_Which2[Worker_DurableObjectNamespace_Which2["UNIQUE_KEY"] = 0] = "UNIQUE_KEY"; + Worker_DurableObjectNamespace_Which2[Worker_DurableObjectNamespace_Which2["EPHEMERAL_LOCAL"] = 1] = "EPHEMERAL_LOCAL"; + })(Worker_DurableObjectNamespace_Which = exports.Worker_DurableObjectNamespace_Which || (exports.Worker_DurableObjectNamespace_Which = {})); + var Worker_DurableObjectNamespace = class extends capnp_ts_1.Struct { + getClassName() { + return capnp_ts_1.Struct.getText(0, this); + } + setClassName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getUniqueKey() { + capnp_ts_1.Struct.testWhich("uniqueKey", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getText(1, this); + } + isUniqueKey() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setUniqueKey(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.setText(1, value, this); + } + isEphemeralLocal() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setEphemeralLocal() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + toString() { + return "Worker_DurableObjectNamespace_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker_DurableObjectNamespace = Worker_DurableObjectNamespace; + Worker_DurableObjectNamespace.UNIQUE_KEY = Worker_DurableObjectNamespace_Which.UNIQUE_KEY; + Worker_DurableObjectNamespace.EPHEMERAL_LOCAL = Worker_DurableObjectNamespace_Which.EPHEMERAL_LOCAL; + Worker_DurableObjectNamespace._capnp = { displayName: "DurableObjectNamespace", id: "b429dd547d15747d", size: new capnp_ts_1.ObjectSize(8, 2) }; + var Worker_DurableObjectStorage_Which; + (function(Worker_DurableObjectStorage_Which2) { + Worker_DurableObjectStorage_Which2[Worker_DurableObjectStorage_Which2["NONE"] = 0] = "NONE"; + Worker_DurableObjectStorage_Which2[Worker_DurableObjectStorage_Which2["IN_MEMORY"] = 1] = "IN_MEMORY"; + Worker_DurableObjectStorage_Which2[Worker_DurableObjectStorage_Which2["LOCAL_DISK"] = 2] = "LOCAL_DISK"; + })(Worker_DurableObjectStorage_Which = exports.Worker_DurableObjectStorage_Which || (exports.Worker_DurableObjectStorage_Which = {})); + var Worker_DurableObjectStorage = class extends capnp_ts_1.Struct { + isNone() { + return capnp_ts_1.Struct.getUint16(2, this) === 0; + } + setNone() { + capnp_ts_1.Struct.setUint16(2, 0, this); + } + isInMemory() { + return capnp_ts_1.Struct.getUint16(2, this) === 1; + } + setInMemory() { + capnp_ts_1.Struct.setUint16(2, 1, this); + } + getLocalDisk() { + capnp_ts_1.Struct.testWhich("localDisk", capnp_ts_1.Struct.getUint16(2, this), 2, this); + return capnp_ts_1.Struct.getText(8, this); + } + isLocalDisk() { + return capnp_ts_1.Struct.getUint16(2, this) === 2; + } + setLocalDisk(value) { + capnp_ts_1.Struct.setUint16(2, 2, this); + capnp_ts_1.Struct.setText(8, value, this); + } + toString() { + return "Worker_DurableObjectStorage_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(2, this); + } + }; + exports.Worker_DurableObjectStorage = Worker_DurableObjectStorage; + Worker_DurableObjectStorage.NONE = Worker_DurableObjectStorage_Which.NONE; + Worker_DurableObjectStorage.IN_MEMORY = Worker_DurableObjectStorage_Which.IN_MEMORY; + Worker_DurableObjectStorage.LOCAL_DISK = Worker_DurableObjectStorage_Which.LOCAL_DISK; + Worker_DurableObjectStorage._capnp = { displayName: "durableObjectStorage", id: "cc72b3faa57827d4", size: new capnp_ts_1.ObjectSize(8, 9) }; + var Worker_Which; + (function(Worker_Which2) { + Worker_Which2[Worker_Which2["MODULES"] = 0] = "MODULES"; + Worker_Which2[Worker_Which2["SERVICE_WORKER_SCRIPT"] = 1] = "SERVICE_WORKER_SCRIPT"; + Worker_Which2[Worker_Which2["INHERIT"] = 2] = "INHERIT"; + })(Worker_Which = exports.Worker_Which || (exports.Worker_Which = {})); + var Worker2 = class extends capnp_ts_1.Struct { + adoptModules(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownModules() { + return capnp_ts_1.Struct.disown(this.getModules()); + } + getModules() { + capnp_ts_1.Struct.testWhich("modules", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getList(0, Worker2._Modules, this); + } + hasModules() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initModules(length) { + capnp_ts_1.Struct.setUint16(0, 0, this); + return capnp_ts_1.Struct.initList(0, Worker2._Modules, length, this); + } + isModules() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setModules(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + getServiceWorkerScript() { + capnp_ts_1.Struct.testWhich("serviceWorkerScript", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getText(0, this); + } + isServiceWorkerScript() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setServiceWorkerScript(value) { + capnp_ts_1.Struct.setUint16(0, 1, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getInherit() { + capnp_ts_1.Struct.testWhich("inherit", capnp_ts_1.Struct.getUint16(0, this), 2, this); + return capnp_ts_1.Struct.getText(0, this); + } + isInherit() { + return capnp_ts_1.Struct.getUint16(0, this) === 2; + } + setInherit(value) { + capnp_ts_1.Struct.setUint16(0, 2, this); + capnp_ts_1.Struct.setText(0, value, this); + } + getCompatibilityDate() { + return capnp_ts_1.Struct.getText(1, this); + } + setCompatibilityDate(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + adoptCompatibilityFlags(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownCompatibilityFlags() { + return capnp_ts_1.Struct.disown(this.getCompatibilityFlags()); + } + getCompatibilityFlags() { + return capnp_ts_1.Struct.getList(2, capnp.TextList, this); + } + hasCompatibilityFlags() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initCompatibilityFlags(length) { + return capnp_ts_1.Struct.initList(2, capnp.TextList, length, this); + } + setCompatibilityFlags(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + adoptBindings(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this)); + } + disownBindings() { + return capnp_ts_1.Struct.disown(this.getBindings()); + } + getBindings() { + return capnp_ts_1.Struct.getList(3, Worker2._Bindings, this); + } + hasBindings() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this)); + } + initBindings(length) { + return capnp_ts_1.Struct.initList(3, Worker2._Bindings, length, this); + } + setBindings(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this)); + } + adoptGlobalOutbound(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(4, this)); + } + disownGlobalOutbound() { + return capnp_ts_1.Struct.disown(this.getGlobalOutbound()); + } + getGlobalOutbound() { + return capnp_ts_1.Struct.getStruct(4, ServiceDesignator2, this, Worker2._capnp.defaultGlobalOutbound); + } + hasGlobalOutbound() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(4, this)); + } + initGlobalOutbound() { + return capnp_ts_1.Struct.initStructAt(4, ServiceDesignator2, this); + } + setGlobalOutbound(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(4, this)); + } + adoptCacheApiOutbound(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(7, this)); + } + disownCacheApiOutbound() { + return capnp_ts_1.Struct.disown(this.getCacheApiOutbound()); + } + getCacheApiOutbound() { + return capnp_ts_1.Struct.getStruct(7, ServiceDesignator2, this); + } + hasCacheApiOutbound() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(7, this)); + } + initCacheApiOutbound() { + return capnp_ts_1.Struct.initStructAt(7, ServiceDesignator2, this); + } + setCacheApiOutbound(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(7, this)); + } + adoptDurableObjectNamespaces(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(5, this)); + } + disownDurableObjectNamespaces() { + return capnp_ts_1.Struct.disown(this.getDurableObjectNamespaces()); + } + getDurableObjectNamespaces() { + return capnp_ts_1.Struct.getList(5, Worker2._DurableObjectNamespaces, this); + } + hasDurableObjectNamespaces() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(5, this)); + } + initDurableObjectNamespaces(length) { + return capnp_ts_1.Struct.initList(5, Worker2._DurableObjectNamespaces, length, this); + } + setDurableObjectNamespaces(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(5, this)); + } + getDurableObjectUniqueKeyModifier() { + return capnp_ts_1.Struct.getText(6, this); + } + setDurableObjectUniqueKeyModifier(value) { + capnp_ts_1.Struct.setText(6, value, this); + } + getDurableObjectStorage() { + return capnp_ts_1.Struct.getAs(Worker_DurableObjectStorage, this); + } + initDurableObjectStorage() { + return capnp_ts_1.Struct.getAs(Worker_DurableObjectStorage, this); + } + toString() { + return "Worker_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.Worker = Worker2; + Worker2.MODULES = Worker_Which.MODULES; + Worker2.SERVICE_WORKER_SCRIPT = Worker_Which.SERVICE_WORKER_SCRIPT; + Worker2.INHERIT = Worker_Which.INHERIT; + Worker2.Module = Worker_Module3; + Worker2.Binding = Worker_Binding4; + Worker2.DurableObjectNamespace = Worker_DurableObjectNamespace; + Worker2._capnp = { displayName: "Worker", id: "acfa77e88fd97d1c", size: new capnp_ts_1.ObjectSize(8, 9), defaultGlobalOutbound: capnp.readRawPointer(new Uint8Array([16, 5, 64, 2, 17, 5, 74, 0, 0, 255, 105, 110, 116, 101, 114, 110, 101, 116, 0, 0, 0]).buffer) }; + var ExternalServer_Https = class extends capnp_ts_1.Struct { + adoptOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownOptions() { + return capnp_ts_1.Struct.disown(this.getOptions()); + } + getOptions() { + return capnp_ts_1.Struct.getStruct(1, HttpOptions, this); + } + hasOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initOptions() { + return capnp_ts_1.Struct.initStructAt(1, HttpOptions, this); + } + setOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptTlsOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownTlsOptions() { + return capnp_ts_1.Struct.disown(this.getTlsOptions()); + } + getTlsOptions() { + return capnp_ts_1.Struct.getStruct(2, TlsOptions, this); + } + hasTlsOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initTlsOptions() { + return capnp_ts_1.Struct.initStructAt(2, TlsOptions, this); + } + setTlsOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + getCertificateHost() { + return capnp_ts_1.Struct.getText(3, this); + } + setCertificateHost(value) { + capnp_ts_1.Struct.setText(3, value, this); + } + toString() { + return "ExternalServer_Https_" + super.toString(); + } + }; + exports.ExternalServer_Https = ExternalServer_Https; + ExternalServer_Https._capnp = { displayName: "https", id: "ac37e02afd3dc6db", size: new capnp_ts_1.ObjectSize(8, 4) }; + var ExternalServer_Which; + (function(ExternalServer_Which2) { + ExternalServer_Which2[ExternalServer_Which2["HTTP"] = 0] = "HTTP"; + ExternalServer_Which2[ExternalServer_Which2["HTTPS"] = 1] = "HTTPS"; + })(ExternalServer_Which = exports.ExternalServer_Which || (exports.ExternalServer_Which = {})); + var ExternalServer2 = class extends capnp_ts_1.Struct { + getAddress() { + return capnp_ts_1.Struct.getText(0, this); + } + setAddress(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + adoptHttp(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownHttp() { + return capnp_ts_1.Struct.disown(this.getHttp()); + } + getHttp() { + capnp_ts_1.Struct.testWhich("http", capnp_ts_1.Struct.getUint16(0, this), 0, this); + return capnp_ts_1.Struct.getStruct(1, HttpOptions, this); + } + hasHttp() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initHttp() { + capnp_ts_1.Struct.setUint16(0, 0, this); + return capnp_ts_1.Struct.initStructAt(1, HttpOptions, this); + } + isHttp() { + return capnp_ts_1.Struct.getUint16(0, this) === 0; + } + setHttp(value) { + capnp_ts_1.Struct.setUint16(0, 0, this); + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getHttps() { + capnp_ts_1.Struct.testWhich("https", capnp_ts_1.Struct.getUint16(0, this), 1, this); + return capnp_ts_1.Struct.getAs(ExternalServer_Https, this); + } + initHttps() { + capnp_ts_1.Struct.setUint16(0, 1, this); + return capnp_ts_1.Struct.getAs(ExternalServer_Https, this); + } + isHttps() { + return capnp_ts_1.Struct.getUint16(0, this) === 1; + } + setHttps() { + capnp_ts_1.Struct.setUint16(0, 1, this); + } + toString() { + return "ExternalServer_" + super.toString(); + } + which() { + return capnp_ts_1.Struct.getUint16(0, this); + } + }; + exports.ExternalServer = ExternalServer2; + ExternalServer2.HTTP = ExternalServer_Which.HTTP; + ExternalServer2.HTTPS = ExternalServer_Which.HTTPS; + ExternalServer2._capnp = { displayName: "ExternalServer", id: "ff209f9aa352f5a4", size: new capnp_ts_1.ObjectSize(8, 4) }; + var Network = class extends capnp_ts_1.Struct { + adoptAllow(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownAllow() { + return capnp_ts_1.Struct.disown(this.getAllow()); + } + getAllow() { + return capnp_ts_1.Struct.getList(0, capnp.TextList, this, Network._capnp.defaultAllow); + } + hasAllow() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initAllow(length) { + return capnp_ts_1.Struct.initList(0, capnp.TextList, length, this); + } + setAllow(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + adoptDeny(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownDeny() { + return capnp_ts_1.Struct.disown(this.getDeny()); + } + getDeny() { + return capnp_ts_1.Struct.getList(1, capnp.TextList, this); + } + hasDeny() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initDeny(length) { + return capnp_ts_1.Struct.initList(1, capnp.TextList, length, this); + } + setDeny(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + adoptTlsOptions(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownTlsOptions() { + return capnp_ts_1.Struct.disown(this.getTlsOptions()); + } + getTlsOptions() { + return capnp_ts_1.Struct.getStruct(2, TlsOptions, this); + } + hasTlsOptions() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initTlsOptions() { + return capnp_ts_1.Struct.initStructAt(2, TlsOptions, this); + } + setTlsOptions(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + toString() { + return "Network_" + super.toString(); + } + }; + exports.Network = Network; + Network._capnp = { displayName: "Network", id: "fa42244f950c9b9c", size: new capnp_ts_1.ObjectSize(0, 3), defaultAllow: capnp.readRawPointer(new Uint8Array([16, 3, 17, 1, 14, 17, 1, 58, 63, 112, 117, 98, 108, 105, 99]).buffer) }; + var DiskDirectory = class extends capnp_ts_1.Struct { + getPath() { + return capnp_ts_1.Struct.getText(0, this); + } + setPath(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getWritable() { + return capnp_ts_1.Struct.getBit(0, this, DiskDirectory._capnp.defaultWritable); + } + setWritable(value) { + capnp_ts_1.Struct.setBit(0, value, this); + } + getAllowDotfiles() { + return capnp_ts_1.Struct.getBit(1, this, DiskDirectory._capnp.defaultAllowDotfiles); + } + setAllowDotfiles(value) { + capnp_ts_1.Struct.setBit(1, value, this); + } + toString() { + return "DiskDirectory_" + super.toString(); + } + }; + exports.DiskDirectory = DiskDirectory; + DiskDirectory._capnp = { displayName: "DiskDirectory", id: "9048ab22835f51c3", size: new capnp_ts_1.ObjectSize(8, 1), defaultWritable: capnp.getBitMask(false, 0), defaultAllowDotfiles: capnp.getBitMask(false, 1) }; + var HttpOptions_Style2; + (function(HttpOptions_Style3) { + HttpOptions_Style3[HttpOptions_Style3["HOST"] = 0] = "HOST"; + HttpOptions_Style3[HttpOptions_Style3["PROXY"] = 1] = "PROXY"; + })(HttpOptions_Style2 = exports.HttpOptions_Style || (exports.HttpOptions_Style = {})); + var HttpOptions_Header = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getValue() { + return capnp_ts_1.Struct.getText(1, this); + } + setValue(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "HttpOptions_Header_" + super.toString(); + } + }; + exports.HttpOptions_Header = HttpOptions_Header; + HttpOptions_Header._capnp = { displayName: "Header", id: "dc0394b5a6f3417e", size: new capnp_ts_1.ObjectSize(0, 2) }; + var HttpOptions = class extends capnp_ts_1.Struct { + getStyle() { + return capnp_ts_1.Struct.getUint16(0, this, HttpOptions._capnp.defaultStyle); + } + setStyle(value) { + capnp_ts_1.Struct.setUint16(0, value, this); + } + getForwardedProtoHeader() { + return capnp_ts_1.Struct.getText(0, this); + } + setForwardedProtoHeader(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getCfBlobHeader() { + return capnp_ts_1.Struct.getText(1, this); + } + setCfBlobHeader(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + adoptInjectRequestHeaders(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(2, this)); + } + disownInjectRequestHeaders() { + return capnp_ts_1.Struct.disown(this.getInjectRequestHeaders()); + } + getInjectRequestHeaders() { + return capnp_ts_1.Struct.getList(2, HttpOptions._InjectRequestHeaders, this); + } + hasInjectRequestHeaders() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(2, this)); + } + initInjectRequestHeaders(length) { + return capnp_ts_1.Struct.initList(2, HttpOptions._InjectRequestHeaders, length, this); + } + setInjectRequestHeaders(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(2, this)); + } + adoptInjectResponseHeaders(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(3, this)); + } + disownInjectResponseHeaders() { + return capnp_ts_1.Struct.disown(this.getInjectResponseHeaders()); + } + getInjectResponseHeaders() { + return capnp_ts_1.Struct.getList(3, HttpOptions._InjectResponseHeaders, this); + } + hasInjectResponseHeaders() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(3, this)); + } + initInjectResponseHeaders(length) { + return capnp_ts_1.Struct.initList(3, HttpOptions._InjectResponseHeaders, length, this); + } + setInjectResponseHeaders(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(3, this)); + } + toString() { + return "HttpOptions_" + super.toString(); + } + }; + exports.HttpOptions = HttpOptions; + HttpOptions.Style = HttpOptions_Style2; + HttpOptions.Header = HttpOptions_Header; + HttpOptions._capnp = { displayName: "HttpOptions", id: "aa8dc6885da78f19", size: new capnp_ts_1.ObjectSize(8, 4), defaultStyle: capnp.getUint16Mask(0) }; + var TlsOptions_Keypair = class extends capnp_ts_1.Struct { + getPrivateKey() { + return capnp_ts_1.Struct.getText(0, this); + } + setPrivateKey(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getCertificateChain() { + return capnp_ts_1.Struct.getText(1, this); + } + setCertificateChain(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "TlsOptions_Keypair_" + super.toString(); + } + }; + exports.TlsOptions_Keypair = TlsOptions_Keypair; + TlsOptions_Keypair._capnp = { displayName: "Keypair", id: "f546bf2d5d8bd13e", size: new capnp_ts_1.ObjectSize(0, 2) }; + var TlsOptions_Version2; + (function(TlsOptions_Version3) { + TlsOptions_Version3[TlsOptions_Version3["GOOD_DEFAULT"] = 0] = "GOOD_DEFAULT"; + TlsOptions_Version3[TlsOptions_Version3["SSL3"] = 1] = "SSL3"; + TlsOptions_Version3[TlsOptions_Version3["TLS1DOT0"] = 2] = "TLS1DOT0"; + TlsOptions_Version3[TlsOptions_Version3["TLS1DOT1"] = 3] = "TLS1DOT1"; + TlsOptions_Version3[TlsOptions_Version3["TLS1DOT2"] = 4] = "TLS1DOT2"; + TlsOptions_Version3[TlsOptions_Version3["TLS1DOT3"] = 5] = "TLS1DOT3"; + })(TlsOptions_Version2 = exports.TlsOptions_Version || (exports.TlsOptions_Version = {})); + var TlsOptions = class extends capnp_ts_1.Struct { + adoptKeypair(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownKeypair() { + return capnp_ts_1.Struct.disown(this.getKeypair()); + } + getKeypair() { + return capnp_ts_1.Struct.getStruct(0, TlsOptions_Keypair, this); + } + hasKeypair() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initKeypair() { + return capnp_ts_1.Struct.initStructAt(0, TlsOptions_Keypair, this); + } + setKeypair(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + getRequireClientCerts() { + return capnp_ts_1.Struct.getBit(0, this, TlsOptions._capnp.defaultRequireClientCerts); + } + setRequireClientCerts(value) { + capnp_ts_1.Struct.setBit(0, value, this); + } + getTrustBrowserCas() { + return capnp_ts_1.Struct.getBit(1, this, TlsOptions._capnp.defaultTrustBrowserCas); + } + setTrustBrowserCas(value) { + capnp_ts_1.Struct.setBit(1, value, this); + } + adoptTrustedCertificates(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(1, this)); + } + disownTrustedCertificates() { + return capnp_ts_1.Struct.disown(this.getTrustedCertificates()); + } + getTrustedCertificates() { + return capnp_ts_1.Struct.getList(1, capnp.TextList, this); + } + hasTrustedCertificates() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(1, this)); + } + initTrustedCertificates(length) { + return capnp_ts_1.Struct.initList(1, capnp.TextList, length, this); + } + setTrustedCertificates(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(1, this)); + } + getMinVersion() { + return capnp_ts_1.Struct.getUint16(2, this, TlsOptions._capnp.defaultMinVersion); + } + setMinVersion(value) { + capnp_ts_1.Struct.setUint16(2, value, this); + } + getCipherList() { + return capnp_ts_1.Struct.getText(2, this); + } + setCipherList(value) { + capnp_ts_1.Struct.setText(2, value, this); + } + toString() { + return "TlsOptions_" + super.toString(); + } + }; + exports.TlsOptions = TlsOptions; + TlsOptions.Keypair = TlsOptions_Keypair; + TlsOptions.Version = TlsOptions_Version2; + TlsOptions._capnp = { displayName: "TlsOptions", id: "aabb3c3778ac4311", size: new capnp_ts_1.ObjectSize(8, 3), defaultRequireClientCerts: capnp.getBitMask(false, 0), defaultTrustBrowserCas: capnp.getBitMask(false, 1), defaultMinVersion: capnp.getUint16Mask(0) }; + var Extension_Module = class extends capnp_ts_1.Struct { + getName() { + return capnp_ts_1.Struct.getText(0, this); + } + setName(value) { + capnp_ts_1.Struct.setText(0, value, this); + } + getInternal() { + return capnp_ts_1.Struct.getBit(0, this, Extension_Module._capnp.defaultInternal); + } + setInternal(value) { + capnp_ts_1.Struct.setBit(0, value, this); + } + getEsModule() { + return capnp_ts_1.Struct.getText(1, this); + } + setEsModule(value) { + capnp_ts_1.Struct.setText(1, value, this); + } + toString() { + return "Extension_Module_" + super.toString(); + } + }; + exports.Extension_Module = Extension_Module; + Extension_Module._capnp = { displayName: "Module", id: "d5d16e76fdedc37d", size: new capnp_ts_1.ObjectSize(8, 2), defaultInternal: capnp.getBitMask(false, 0) }; + var Extension2 = class extends capnp_ts_1.Struct { + adoptModules(value) { + capnp_ts_1.Struct.adopt(value, capnp_ts_1.Struct.getPointer(0, this)); + } + disownModules() { + return capnp_ts_1.Struct.disown(this.getModules()); + } + getModules() { + return capnp_ts_1.Struct.getList(0, Extension2._Modules, this); + } + hasModules() { + return !capnp_ts_1.Struct.isNull(capnp_ts_1.Struct.getPointer(0, this)); + } + initModules(length) { + return capnp_ts_1.Struct.initList(0, Extension2._Modules, length, this); + } + setModules(value) { + capnp_ts_1.Struct.copyFrom(value, capnp_ts_1.Struct.getPointer(0, this)); + } + toString() { + return "Extension_" + super.toString(); + } + }; + exports.Extension = Extension2; + Extension2.Module = Extension_Module; + Extension2._capnp = { displayName: "Extension", id: "e390128a861973a6", size: new capnp_ts_1.ObjectSize(0, 1) }; + Config3._Services = capnp.CompositeList(Service4); + Config3._Sockets = capnp.CompositeList(Socket2); + Config3._Extensions = capnp.CompositeList(Extension2); + Worker_Binding_WrappedBinding._InnerBindings = capnp.CompositeList(Worker_Binding4); + Worker2._Modules = capnp.CompositeList(Worker_Module3); + Worker2._Bindings = capnp.CompositeList(Worker_Binding4); + Worker2._DurableObjectNamespaces = capnp.CompositeList(Worker_DurableObjectNamespace); + HttpOptions._InjectRequestHeaders = capnp.CompositeList(HttpOptions_Header); + HttpOptions._InjectResponseHeaders = capnp.CompositeList(HttpOptions_Header); + Extension2._Modules = capnp.CompositeList(Extension_Module); + } +}); + +// packages/miniflare/src/index.ts +var src_exports = {}; +__export(src_exports, { + CACHE_PLUGIN: () => CACHE_PLUGIN, + CACHE_PLUGIN_NAME: () => CACHE_PLUGIN_NAME, + CORE_PLUGIN: () => CORE_PLUGIN, + CORE_PLUGIN_NAME: () => CORE_PLUGIN_NAME2, + CacheBindings: () => CacheBindings, + CacheHeaders: () => CacheHeaders, + CacheOptionsSchema: () => CacheOptionsSchema, + CacheSharedOptionsSchema: () => CacheSharedOptionsSchema, + CloseEvent: () => CloseEvent, + CoreBindings: () => CoreBindings, + CoreHeaders: () => CoreHeaders, + CoreOptionsSchema: () => CoreOptionsSchema, + CoreSharedOptionsSchema: () => CoreSharedOptionsSchema, + D1OptionsSchema: () => D1OptionsSchema, + D1SharedOptionsSchema: () => D1SharedOptionsSchema, + D1_PLUGIN: () => D1_PLUGIN, + D1_PLUGIN_NAME: () => D1_PLUGIN_NAME, + DEFAULT_PERSIST_ROOT: () => DEFAULT_PERSIST_ROOT, + DURABLE_OBJECTS_PLUGIN: () => DURABLE_OBJECTS_PLUGIN, + DURABLE_OBJECTS_PLUGIN_NAME: () => DURABLE_OBJECTS_PLUGIN_NAME, + DURABLE_OBJECTS_STORAGE_SERVICE_NAME: () => DURABLE_OBJECTS_STORAGE_SERVICE_NAME, + DeferredPromise: () => DeferredPromise, + DurableObjectsOptionsSchema: () => DurableObjectsOptionsSchema, + DurableObjectsSharedOptionsSchema: () => DurableObjectsSharedOptionsSchema, + ErrorEvent: () => ErrorEvent, + File: () => import_undici8.File, + FormData: () => import_undici8.FormData, + HEADER_CF_BLOB: () => HEADER_CF_BLOB, + Headers: () => import_undici8.Headers, + HttpOptions_Style: () => import_workerd_capnp.HttpOptions_Style, + JsonSchema: () => JsonSchema, + KVHeaders: () => KVHeaders, + KVLimits: () => KVLimits, + KVOptionsSchema: () => KVOptionsSchema, + KVParams: () => KVParams, + KVSharedOptionsSchema: () => KVSharedOptionsSchema, + KV_PLUGIN: () => KV_PLUGIN, + KV_PLUGIN_NAME: () => KV_PLUGIN_NAME, + LiteralSchema: () => LiteralSchema, + Log: () => Log, + LogLevel: () => LogLevel, + MessageEvent: () => MessageEvent, + Miniflare: () => Miniflare, + MiniflareCoreError: () => MiniflareCoreError, + MiniflareError: () => MiniflareError, + ModuleDefinitionSchema: () => ModuleDefinitionSchema, + ModuleRuleSchema: () => ModuleRuleSchema, + ModuleRuleTypeSchema: () => ModuleRuleTypeSchema, + Mutex: () => Mutex, + NoOpLog: () => NoOpLog, + PLUGINS: () => PLUGINS, + PLUGIN_ENTRIES: () => PLUGIN_ENTRIES, + PersistenceSchema: () => PersistenceSchema, + ProxyAddresses: () => ProxyAddresses, + ProxyClient: () => ProxyClient, + ProxyOps: () => ProxyOps, + QUEUES_PLUGIN: () => QUEUES_PLUGIN, + QUEUES_PLUGIN_NAME: () => QUEUES_PLUGIN_NAME, + QueueBindings: () => QueueBindings, + QueueConsumerOptionsSchema: () => QueueConsumerOptionsSchema, + QueueConsumerSchema: () => QueueConsumerSchema, + QueueConsumersSchema: () => QueueConsumersSchema, + QueueContentTypeSchema: () => QueueContentTypeSchema, + QueueIncomingMessageSchema: () => QueueIncomingMessageSchema, + QueuesBatchRequestSchema: () => QueuesBatchRequestSchema, + QueuesError: () => QueuesError, + QueuesOptionsSchema: () => QueuesOptionsSchema, + R2OptionsSchema: () => R2OptionsSchema, + R2SharedOptionsSchema: () => R2SharedOptionsSchema, + R2_PLUGIN: () => R2_PLUGIN, + R2_PLUGIN_NAME: () => R2_PLUGIN_NAME, + Request: () => Request, + Response: () => Response, + RouterError: () => RouterError, + Runtime: () => Runtime, + SERVICE_ENTRY: () => SERVICE_ENTRY, + SERVICE_LOOPBACK: () => SERVICE_LOOPBACK, + SITES_NO_CACHE_PREFIX: () => SITES_NO_CACHE_PREFIX, + SOCKET_ENTRY: () => SOCKET_ENTRY, + SharedBindings: () => SharedBindings, + SharedHeaders: () => SharedHeaders, + SiteBindings: () => SiteBindings, + SourceOptionsSchema: () => SourceOptionsSchema, + TlsOptions_Version: () => import_workerd_capnp.TlsOptions_Version, + TypedEventTarget: () => TypedEventTarget, + WORKER_BINDING_SERVICE_LOOPBACK: () => WORKER_BINDING_SERVICE_LOOPBACK, + WaitGroup: () => WaitGroup, + WebSocket: () => WebSocket, + WebSocketPair: () => WebSocketPair, + Worker_Binding_CryptoKey_Usage: () => import_workerd_capnp.Worker_Binding_CryptoKey_Usage, + _forceColour: () => _forceColour, + _formatZodError: () => _formatZodError, + _initialiseInstanceRegistry: () => _initialiseInstanceRegistry, + _transformsForContentEncoding: () => _transformsForContentEncoding, + base64Decode: () => base64Decode, + base64Encode: () => base64Encode, + configureEntrySocket: () => configureEntrySocket, + coupleWebSocket: () => coupleWebSocket, + createFetchMock: () => createFetchMock, + createHTTPReducers: () => createHTTPReducers, + createHTTPRevivers: () => createHTTPRevivers, + decodeSitesKey: () => decodeSitesKey, + deserialiseRegExps: () => deserialiseRegExps, + deserialiseSiteRegExps: () => deserialiseSiteRegExps, + encodeSitesKey: () => encodeSitesKey, + fetch: () => fetch2, + getAccessibleHosts: () => getAccessibleHosts, + getCacheServiceName: () => getCacheServiceName, + getGlobalServices: () => getGlobalServices, + getPersistPath: () => getPersistPath, + globsToRegExps: () => globsToRegExps, + isFetcherFetch: () => isFetcherFetch, + isR2ObjectWriteHttpMetadata: () => isR2ObjectWriteHttpMetadata, + isSitesRequest: () => isSitesRequest, + kProxyNodeBinding: () => kProxyNodeBinding, + kVoid: () => kVoid, + matchRoutes: () => matchRoutes, + maybeApply: () => maybeApply, + maybeGetSitesManifestModule: () => maybeGetSitesManifestModule, + maybeParseURL: () => maybeParseURL, + migrateDatabase: () => migrateDatabase, + namespaceEntries: () => namespaceEntries, + namespaceKeys: () => namespaceKeys, + normaliseDurableObject: () => normaliseDurableObject, + objectEntryWorker: () => objectEntryWorker, + parseRanges: () => parseRanges, + parseRoutes: () => parseRoutes, + parseWithReadableStreams: () => parseWithReadableStreams, + prefixError: () => prefixError, + prefixStream: () => prefixStream, + readPrefix: () => readPrefix, + reduceError: () => reduceError, + registerAllowUnauthorizedDispatcher: () => registerAllowUnauthorizedDispatcher, + sanitisePath: () => sanitisePath, + serialiseRegExps: () => serialiseRegExps, + serialiseSiteRegExps: () => serialiseSiteRegExps, + serializeConfig: () => serializeConfig, + stringifyWithStreams: () => stringifyWithStreams, + stripAnsi: () => stripAnsi, + structuredSerializableReducers: () => structuredSerializableReducers, + structuredSerializableRevivers: () => structuredSerializableRevivers, + supportedCompatibilityDate: () => import_workerd2.compatibilityDate, + testRegExps: () => testRegExps, + testSiteRegExps: () => testSiteRegExps, + viewToBuffer: () => viewToBuffer, + zAwaitable: () => zAwaitable +}); +module.exports = __toCommonJS(src_exports); +var import_assert11 = __toESM(require("assert")); +var import_crypto2 = __toESM(require("crypto")); +var import_fs17 = __toESM(require("fs")); +var import_http7 = __toESM(require("http")); +var import_net = __toESM(require("net")); +var import_os2 = __toESM(require("os")); +var import_path20 = __toESM(require("path")); +var import_web5 = require("stream/web"); +var import_util5 = __toESM(require("util")); +var import_zlib = __toESM(require("zlib")); +var import_exit_hook = __toESM(require("exit-hook")); + +// node_modules/kleur/colors.mjs +var FORCE_COLOR; +var NODE_DISABLE_COLORS; +var NO_COLOR; +var TERM; +var isTTY = true; +if (typeof process !== "undefined") { + ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}); + isTTY = process.stdout && process.stdout.isTTY; +} +var $ = { + enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY) +}; +function init(x, y) { + let rgx = new RegExp(`\\x1b\\[${y}m`, "g"); + let open = `\x1B[${x}m`, close = `\x1B[${y}m`; + return function(txt) { + if (!$.enabled || txt == null) + return txt; + return open + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close; + }; +} +var reset = init(0, 0); +var bold = init(1, 22); +var dim = init(2, 22); +var italic = init(3, 23); +var underline = init(4, 24); +var inverse = init(7, 27); +var hidden = init(8, 28); +var strikethrough = init(9, 29); +var black = init(30, 39); +var red = init(31, 39); +var green = init(32, 39); +var yellow = init(33, 39); +var blue = init(34, 39); +var magenta = init(35, 39); +var cyan = init(36, 39); +var white = init(37, 39); +var gray = init(90, 39); +var grey = init(90, 39); +var bgBlack = init(40, 49); +var bgRed = init(41, 49); +var bgGreen = init(42, 49); +var bgYellow = init(43, 49); +var bgBlue = init(44, 49); +var bgMagenta = init(45, 49); +var bgCyan = init(46, 49); +var bgWhite = init(47, 49); + +// packages/miniflare/src/index.ts +var import_stoppable = __toESM(require("stoppable")); +var import_undici9 = require("undici"); + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/shared/index.worker.ts +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_url = __toESM(require("url")); +var contents; +function index_worker_default() { + if (contents !== void 0) + return contents; + const filePath = import_path.default.join(__dirname, "workers", "shared/index.worker.js"); + contents = import_fs.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url.default.pathToFileURL(filePath); + return contents; +} + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/shared/zod.worker.ts +var import_fs2 = __toESM(require("fs")); +var import_path2 = __toESM(require("path")); +var import_url2 = __toESM(require("url")); +var contents2; +function zod_worker_default() { + if (contents2 !== void 0) + return contents2; + const filePath = import_path2.default.join(__dirname, "workers", "shared/zod.worker.js"); + contents2 = import_fs2.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url2.default.pathToFileURL(filePath); + return contents2; +} + +// packages/miniflare/src/index.ts +var import_ws3 = require("ws"); +var import_zod17 = require("zod"); + +// packages/miniflare/src/cf.ts +var import_assert = __toESM(require("assert")); +var import_promises = require("fs/promises"); +var import_path3 = __toESM(require("path")); +var import_undici = require("undici"); +var defaultCfPath = import_path3.default.resolve("node_modules", ".mf", "cf.json"); +var defaultCfFetchEndpoint = "https://workers.cloudflare.com/cf.json"; +var fallbackCf = { + asOrganization: "", + asn: 395747, + colo: "DFW", + city: "Austin", + region: "Texas", + regionCode: "TX", + metroCode: "635", + postalCode: "78701", + country: "US", + continent: "NA", + timezone: "America/Chicago", + latitude: "30.27130", + longitude: "-97.74260", + clientTcpRtt: 0, + httpProtocol: "HTTP/1.1", + requestPriority: "weight=192;exclusive=0", + tlsCipher: "AEAD-AES128-GCM-SHA256", + tlsVersion: "TLSv1.3", + tlsClientAuth: { + certPresented: "0", + certVerified: "NONE", + certRevoked: "0", + certIssuerDN: "", + certSubjectDN: "", + certIssuerDNRFC2253: "", + certSubjectDNRFC2253: "", + certIssuerDNLegacy: "", + certSubjectDNLegacy: "", + certSerial: "", + certIssuerSerial: "", + certSKI: "", + certIssuerSKI: "", + certFingerprintSHA1: "", + certFingerprintSHA256: "", + certNotBefore: "", + certNotAfter: "" + }, + edgeRequestKeepAliveStatus: 0, + hostMetadata: void 0, + clientTrustScore: 99, + botManagement: { + corporateProxy: false, + verifiedBot: false, + ja3Hash: "25b4882c2bcb50cd6b469ff28c596742", + staticResource: false, + detectionIds: [], + score: 99 + } +}; +var DAY = 864e5; +var CF_DAYS = 30; +async function setupCf(log, cf) { + if (!(cf ?? process.env.NODE_ENV !== "test")) { + return fallbackCf; + } + if (typeof cf === "object") { + return cf; + } + let cfPath = defaultCfPath; + if (typeof cf === "string") { + cfPath = cf; + } + try { + const storedCf = JSON.parse(await (0, import_promises.readFile)(cfPath, "utf8")); + const cfStat = await (0, import_promises.stat)(cfPath); + (0, import_assert.default)(Date.now() - cfStat.mtimeMs <= CF_DAYS * DAY); + return storedCf; + } catch { + } + try { + const res = await (0, import_undici.fetch)(defaultCfFetchEndpoint); + const cfText = await res.text(); + const storedCf = JSON.parse(cfText); + await (0, import_promises.mkdir)(import_path3.default.dirname(cfPath), { recursive: true }); + await (0, import_promises.writeFile)(cfPath, cfText, "utf8"); + log.debug("Updated `Request.cf` object cache!"); + return storedCf; + } catch (e) { + log.warn( + "Unable to fetch the `Request.cf` object! Falling back to a default placeholder...\n" + dim(e.cause ? e.cause.stack : e.stack) + ); + return fallbackCf; + } +} + +// packages/miniflare/src/http/fetch.ts +var import_undici4 = require("undici"); +var import_ws2 = __toESM(require("ws")); + +// packages/miniflare/src/workers/cache/constants.ts +var CacheHeaders = { + NAMESPACE: "cf-cache-namespace", + STATUS: "cf-cache-status" +}; +var CacheBindings = { + MAYBE_JSON_CACHE_WARN_USAGE: "MINIFLARE_CACHE_WARN_USAGE" +}; + +// packages/miniflare/src/workers/core/constants.ts +var CoreHeaders = { + CUSTOM_SERVICE: "MF-Custom-Service", + ORIGINAL_URL: "MF-Original-URL", + ERROR_STACK: "MF-Experimental-Error-Stack", + ROUTE_OVERRIDE: "MF-Route-Override", + // API Proxy + OP: "MF-Op", + OP_TARGET: "MF-Op-Target", + OP_KEY: "MF-Op-Key", + OP_SYNC: "MF-Op-Sync", + OP_STRINGIFIED_SIZE: "MF-Op-Stringified-Size", + OP_RESULT_TYPE: "MF-Op-Result-Type" +}; +var CoreBindings = { + SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK", + SERVICE_USER_ROUTE_PREFIX: "MINIFLARE_USER_ROUTE_", + SERVICE_USER_FALLBACK: "MINIFLARE_USER_FALLBACK", + TEXT_CUSTOM_SERVICE: "MINIFLARE_CUSTOM_SERVICE", + TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL", + JSON_CF_BLOB: "CF_BLOB", + JSON_ROUTES: "MINIFLARE_ROUTES", + JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL", + DATA_LIVE_RELOAD_SCRIPT: "MINIFLARE_LIVE_RELOAD_SCRIPT", + DURABLE_OBJECT_NAMESPACE_PROXY: "MINIFLARE_PROXY" +}; +var ProxyOps = { + // Get the target or a property of the target + GET: "GET", + // Call a method on the target + CALL: "CALL", + // Remove the strong reference to the target on the "heap", allowing it to be + // garbage collected + FREE: "FREE" +}; +var ProxyAddresses = { + GLOBAL: 0, + // globalThis + ENV: 1, + // env + USER_START: 2 +}; +function isFetcherFetch(targetName, key) { + return (targetName === "Fetcher" || targetName === "DurableObject") && key === "fetch"; +} +function isR2ObjectWriteHttpMetadata(targetName, key) { + return (targetName === "HeadResult" || targetName === "GetResult") && key === "writeHttpMetadata"; +} + +// packages/miniflare/src/workers/core/devalue.ts +var import_node_assert = __toESM(require("node:assert")); +var import_node_buffer = require("node:buffer"); + +// node_modules/devalue/src/utils.js +var escaped = { + "<": "\\u003C", + ">": "\\u003E", + "/": "\\u002F", + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + " ": "\\t", + "\0": "\\u0000", + "\u2028": "\\u2028", + "\u2029": "\\u2029" +}; +var DevalueError = class extends Error { + /** + * @param {string} message + * @param {string[]} keys + */ + constructor(message, keys) { + super(message); + this.name = "DevalueError"; + this.path = keys.join(""); + } +}; +function is_primitive(thing) { + return Object(thing) !== thing; +} +var object_proto_names = Object.getOwnPropertyNames(Object.prototype).sort().join("\0"); +function is_plain_object(thing) { + const proto = Object.getPrototypeOf(thing); + return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names; +} +function get_type(thing) { + return Object.prototype.toString.call(thing).slice(8, -1); +} +function stringify_string(str) { + let result = '"'; + for (let i = 0; i < str.length; i += 1) { + const char = str.charAt(i); + const code = char.charCodeAt(0); + if (char === '"') { + result += '\\"'; + } else if (char in escaped) { + result += escaped[char]; + } else if (code <= 31) { + result += `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`; + } else if (code >= 55296 && code <= 57343) { + const next = str.charCodeAt(i + 1); + if (code <= 56319 && next >= 56320 && next <= 57343) { + result += char + str[++i]; + } else { + result += `\\u${code.toString(16).toUpperCase()}`; + } + } else { + result += char; + } + } + result += '"'; + return result; +} + +// node_modules/devalue/src/constants.js +var UNDEFINED = -1; +var HOLE = -2; +var NAN = -3; +var POSITIVE_INFINITY = -4; +var NEGATIVE_INFINITY = -5; +var NEGATIVE_ZERO = -6; + +// node_modules/devalue/src/parse.js +function parse(serialized, revivers2) { + return unflatten(JSON.parse(serialized), revivers2); +} +function unflatten(parsed, revivers2) { + if (typeof parsed === "number") + return hydrate(parsed, true); + if (!Array.isArray(parsed) || parsed.length === 0) { + throw new Error("Invalid input"); + } + const values = ( + /** @type {any[]} */ + parsed + ); + const hydrated = Array(values.length); + function hydrate(index, standalone = false) { + if (index === UNDEFINED) + return void 0; + if (index === NAN) + return NaN; + if (index === POSITIVE_INFINITY) + return Infinity; + if (index === NEGATIVE_INFINITY) + return -Infinity; + if (index === NEGATIVE_ZERO) + return -0; + if (standalone) + throw new Error(`Invalid input`); + if (index in hydrated) + return hydrated[index]; + const value = values[index]; + if (!value || typeof value !== "object") { + hydrated[index] = value; + } else if (Array.isArray(value)) { + if (typeof value[0] === "string") { + const type = value[0]; + const reviver = revivers2?.[type]; + if (reviver) { + return hydrated[index] = reviver(hydrate(value[1])); + } + switch (type) { + case "Date": + hydrated[index] = new Date(value[1]); + break; + case "Set": + const set = /* @__PURE__ */ new Set(); + hydrated[index] = set; + for (let i = 1; i < value.length; i += 1) { + set.add(hydrate(value[i])); + } + break; + case "Map": + const map = /* @__PURE__ */ new Map(); + hydrated[index] = map; + for (let i = 1; i < value.length; i += 2) { + map.set(hydrate(value[i]), hydrate(value[i + 1])); + } + break; + case "RegExp": + hydrated[index] = new RegExp(value[1], value[2]); + break; + case "Object": + hydrated[index] = Object(value[1]); + break; + case "BigInt": + hydrated[index] = BigInt(value[1]); + break; + case "null": + const obj = /* @__PURE__ */ Object.create(null); + hydrated[index] = obj; + for (let i = 1; i < value.length; i += 2) { + obj[value[i]] = hydrate(value[i + 1]); + } + break; + default: + throw new Error(`Unknown type ${type}`); + } + } else { + const array = new Array(value.length); + hydrated[index] = array; + for (let i = 0; i < value.length; i += 1) { + const n = value[i]; + if (n === HOLE) + continue; + array[i] = hydrate(n); + } + } + } else { + const object = {}; + hydrated[index] = object; + for (const key in value) { + const n = value[key]; + object[key] = hydrate(n); + } + } + return hydrated[index]; + } + return hydrate(0); +} + +// node_modules/devalue/src/stringify.js +function stringify(value, reducers2) { + const stringified = []; + const indexes = /* @__PURE__ */ new Map(); + const custom = []; + for (const key in reducers2) { + custom.push({ key, fn: reducers2[key] }); + } + const keys = []; + let p = 0; + function flatten(thing) { + if (typeof thing === "function") { + throw new DevalueError(`Cannot stringify a function`, keys); + } + if (indexes.has(thing)) + return indexes.get(thing); + if (thing === void 0) + return UNDEFINED; + if (Number.isNaN(thing)) + return NAN; + if (thing === Infinity) + return POSITIVE_INFINITY; + if (thing === -Infinity) + return NEGATIVE_INFINITY; + if (thing === 0 && 1 / thing < 0) + return NEGATIVE_ZERO; + const index2 = p++; + indexes.set(thing, index2); + for (const { key, fn } of custom) { + const value2 = fn(thing); + if (value2) { + stringified[index2] = `["${key}",${flatten(value2)}]`; + return index2; + } + } + let str = ""; + if (is_primitive(thing)) { + str = stringify_primitive(thing); + } else { + const type = get_type(thing); + switch (type) { + case "Number": + case "String": + case "Boolean": + str = `["Object",${stringify_primitive(thing)}]`; + break; + case "BigInt": + str = `["BigInt",${thing}]`; + break; + case "Date": + str = `["Date","${thing.toISOString()}"]`; + break; + case "RegExp": + const { source, flags } = thing; + str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`; + break; + case "Array": + str = "["; + for (let i = 0; i < thing.length; i += 1) { + if (i > 0) + str += ","; + if (i in thing) { + keys.push(`[${i}]`); + str += flatten(thing[i]); + keys.pop(); + } else { + str += HOLE; + } + } + str += "]"; + break; + case "Set": + str = '["Set"'; + for (const value2 of thing) { + str += `,${flatten(value2)}`; + } + str += "]"; + break; + case "Map": + str = '["Map"'; + for (const [key, value2] of thing) { + keys.push( + `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})` + ); + str += `,${flatten(key)},${flatten(value2)}`; + } + str += "]"; + break; + default: + if (!is_plain_object(thing)) { + throw new DevalueError( + `Cannot stringify arbitrary non-POJOs`, + keys + ); + } + if (Object.getOwnPropertySymbols(thing).length > 0) { + throw new DevalueError( + `Cannot stringify POJOs with symbolic keys`, + keys + ); + } + if (Object.getPrototypeOf(thing) === null) { + str = '["null"'; + for (const key in thing) { + keys.push(`.${key}`); + str += `,${stringify_string(key)},${flatten(thing[key])}`; + keys.pop(); + } + str += "]"; + } else { + str = "{"; + let started = false; + for (const key in thing) { + if (started) + str += ","; + started = true; + keys.push(`.${key}`); + str += `${stringify_string(key)}:${flatten(thing[key])}`; + keys.pop(); + } + str += "}"; + } + } + } + stringified[index2] = str; + return index2; + } + const index = flatten(value); + if (index < 0) + return `${index}`; + return `[${stringified.join(",")}]`; +} +function stringify_primitive(thing) { + const type = typeof thing; + if (type === "string") + return stringify_string(thing); + if (thing instanceof String) + return stringify_string(thing.toString()); + if (thing === void 0) + return UNDEFINED.toString(); + if (thing === 0 && 1 / thing < 0) + return NEGATIVE_ZERO.toString(); + if (type === "bigint") + return `["BigInt","${thing}"]`; + return String(thing); +} + +// packages/miniflare/src/workers/core/devalue.ts +var ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS = [ + DataView, + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + BigInt64Array, + BigUint64Array +]; +var ALLOWED_ERROR_CONSTRUCTORS = [ + EvalError, + RangeError, + ReferenceError, + SyntaxError, + TypeError, + URIError, + Error + // `Error` last so more specific error subclasses preferred +]; +var structuredSerializableReducers = { + ArrayBuffer(value) { + if (value instanceof ArrayBuffer) { + return [import_node_buffer.Buffer.from(value).toString("base64")]; + } + }, + ArrayBufferView(value) { + if (ArrayBuffer.isView(value)) { + return [ + value.constructor.name, + value.buffer, + value.byteOffset, + value.byteLength + ]; + } + }, + Error(value) { + for (const ctor of ALLOWED_ERROR_CONSTRUCTORS) { + if (value instanceof ctor && value.name === ctor.name) { + return [value.name, value.message, value.stack, value.cause]; + } + } + if (value instanceof Error) { + return ["Error", value.message, value.stack, value.cause]; + } + } +}; +var structuredSerializableRevivers = { + ArrayBuffer(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [encoded] = value; + (0, import_node_assert.default)(typeof encoded === "string"); + const view = import_node_buffer.Buffer.from(encoded, "base64"); + return view.buffer.slice( + view.byteOffset, + view.byteOffset + view.byteLength + ); + }, + ArrayBufferView(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [name, buffer, byteOffset, byteLength] = value; + (0, import_node_assert.default)(typeof name === "string"); + (0, import_node_assert.default)(buffer instanceof ArrayBuffer); + (0, import_node_assert.default)(typeof byteOffset === "number"); + (0, import_node_assert.default)(typeof byteLength === "number"); + const ctor = globalThis[name]; + (0, import_node_assert.default)(ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.includes(ctor)); + let length = byteLength; + if ("BYTES_PER_ELEMENT" in ctor) + length /= ctor.BYTES_PER_ELEMENT; + return new ctor(buffer, byteOffset, length); + }, + Error(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [name, message, stack, cause] = value; + (0, import_node_assert.default)(typeof name === "string"); + (0, import_node_assert.default)(typeof message === "string"); + (0, import_node_assert.default)(stack === void 0 || typeof stack === "string"); + const ctor = globalThis[name]; + (0, import_node_assert.default)(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor)); + const error = new ctor(message, { cause }); + error.stack = stack; + return error; + } +}; +function createHTTPReducers(impl) { + return { + Headers(val) { + if (val instanceof impl.Headers) + return Object.fromEntries(val); + }, + Request(val) { + if (val instanceof impl.Request) { + return [val.method, val.url, val.headers, val.cf, val.body]; + } + }, + Response(val) { + if (val instanceof impl.Response) { + return [val.status, val.statusText, val.headers, val.cf, val.body]; + } + } + }; +} +function createHTTPRevivers(impl) { + return { + Headers(value) { + (0, import_node_assert.default)(typeof value === "object" && value !== null); + return new impl.Headers(value); + }, + Request(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [method, url13, headers, cf, body] = value; + (0, import_node_assert.default)(typeof method === "string"); + (0, import_node_assert.default)(typeof url13 === "string"); + (0, import_node_assert.default)(headers instanceof impl.Headers); + (0, import_node_assert.default)(body === null || impl.isReadableStream(body)); + return new impl.Request(url13, { + method, + headers, + cf, + // @ts-expect-error `duplex` is not required by `workerd` yet + duplex: body === null ? void 0 : "half", + body + }); + }, + Response(value) { + (0, import_node_assert.default)(Array.isArray(value)); + const [status, statusText, headers, cf, body] = value; + (0, import_node_assert.default)(typeof status === "number"); + (0, import_node_assert.default)(typeof statusText === "string"); + (0, import_node_assert.default)(headers instanceof impl.Headers); + (0, import_node_assert.default)(body === null || impl.isReadableStream(body)); + return new impl.Response(body, { + status, + statusText, + headers, + cf + }); + } + }; +} +function stringifyWithStreams(impl, value, reducers2, allowUnbufferedStream) { + let unbufferedStream; + const bufferPromises = []; + const streamReducers = { + ReadableStream(value2) { + if (impl.isReadableStream(value2)) { + if (allowUnbufferedStream && unbufferedStream === void 0) { + unbufferedStream = value2; + } else { + bufferPromises.push(impl.bufferReadableStream(value2)); + } + return true; + } + }, + Blob(value2) { + if (value2 instanceof impl.Blob) { + bufferPromises.push(value2.arrayBuffer()); + return true; + } + }, + ...reducers2 + }; + const stringifiedValue = stringify(value, streamReducers); + if (bufferPromises.length === 0) { + return { value: stringifiedValue, unbufferedStream }; + } + return Promise.all(bufferPromises).then((streamBuffers) => { + streamReducers.ReadableStream = function(value2) { + if (impl.isReadableStream(value2)) { + if (value2 === unbufferedStream) { + return true; + } else { + return streamBuffers.shift(); + } + } + }; + streamReducers.Blob = function(value2) { + if (value2 instanceof impl.Blob) { + const array = [streamBuffers.shift(), value2.type]; + if (value2 instanceof impl.File) { + array.push(value2.name, value2.lastModified); + } + return array; + } + }; + const stringifiedValue2 = stringify(value, streamReducers); + return { value: stringifiedValue2, unbufferedStream }; + }); +} +function parseWithReadableStreams(impl, stringified, revivers2) { + const streamRevivers = { + ReadableStream(value) { + if (value === true) { + (0, import_node_assert.default)(stringified.unbufferedStream !== void 0); + return stringified.unbufferedStream; + } + (0, import_node_assert.default)(value instanceof ArrayBuffer); + return impl.unbufferReadableStream(value); + }, + Blob(value) { + (0, import_node_assert.default)(Array.isArray(value)); + if (value.length === 2) { + const [buffer, type] = value; + (0, import_node_assert.default)(buffer instanceof ArrayBuffer); + (0, import_node_assert.default)(typeof type === "string"); + const opts = {}; + if (type !== "") + opts.type = type; + return new impl.Blob([buffer], opts); + } else { + (0, import_node_assert.default)(value.length === 4); + const [buffer, type, name, lastModified] = value; + (0, import_node_assert.default)(buffer instanceof ArrayBuffer); + (0, import_node_assert.default)(typeof type === "string"); + (0, import_node_assert.default)(typeof name === "string"); + (0, import_node_assert.default)(typeof lastModified === "number"); + const opts = { lastModified }; + if (type !== "") + opts.type = type; + return new impl.File([buffer], name, opts); + } + }, + ...revivers2 + }; + return parse(stringified.value, streamRevivers); +} + +// packages/miniflare/src/workers/core/routing.ts +function matchRoutes(routes, url13) { + for (const route of routes) { + if (route.protocol && route.protocol !== url13.protocol) + continue; + if (route.allowHostnamePrefix) { + if (!url13.hostname.endsWith(route.hostname)) + continue; + } else { + if (url13.hostname !== route.hostname) + continue; + } + const path21 = url13.pathname + url13.search; + if (route.allowPathSuffix) { + if (!path21.startsWith(route.path)) + continue; + } else { + if (path21 !== route.path) + continue; + } + return route.target; + } + return null; +} + +// packages/miniflare/src/workers/shared/constants.ts +var SharedHeaders = { + LOG_LEVEL: "MF-Log-Level" +}; +var SharedBindings = { + TEXT_NAMESPACE: "MINIFLARE_NAMESPACE", + DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT", + MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS", + MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK" +}; +var LogLevel = /* @__PURE__ */ ((LogLevel2) => { + LogLevel2[LogLevel2["NONE"] = 0] = "NONE"; + LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR"; + LogLevel2[LogLevel2["WARN"] = 2] = "WARN"; + LogLevel2[LogLevel2["INFO"] = 3] = "INFO"; + LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG"; + LogLevel2[LogLevel2["VERBOSE"] = 5] = "VERBOSE"; + return LogLevel2; +})(LogLevel || {}); + +// packages/miniflare/src/workers/shared/data.ts +var import_node_buffer2 = require("node:buffer"); +function viewToBuffer(view) { + return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength); +} +function base64Encode(value) { + return import_node_buffer2.Buffer.from(value, "utf8").toString("base64"); +} +function base64Decode(encoded) { + return import_node_buffer2.Buffer.from(encoded, "base64").toString("utf8"); +} +var dotRegexp = /(^|\/|\\)(\.+)(\/|\\|$)/g; +var illegalRegexp = /[?<>*"'^/\\:|\x00-\x1f\x80-\x9f]/g; +var windowsReservedRegexp = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; +var leadingRegexp = /^[ /\\]+/; +var trailingRegexp = /[ /\\]+$/; +function dotReplacement(match, g1, g2, g3) { + return `${g1}${"".padStart(g2.length, "_")}${g3}`; +} +function underscoreReplacement(match) { + return "".padStart(match.length, "_"); +} +function sanitisePath(unsafe) { + return unsafe.replace(dotRegexp, dotReplacement).replace(dotRegexp, dotReplacement).replace(illegalRegexp, "_").replace(windowsReservedRegexp, "_").replace(leadingRegexp, underscoreReplacement).replace(trailingRegexp, underscoreReplacement).substring(0, 255); +} + +// packages/miniflare/src/workers/shared/matcher.ts +function testRegExps(matcher, value) { + for (const exclude of matcher.exclude) + if (exclude.test(value)) + return false; + for (const include of matcher.include) + if (include.test(value)) + return true; + return false; +} + +// packages/miniflare/src/workers/shared/range.ts +var rangePrefixRegexp = /^ *bytes *=/i; +var rangeRegexp = /^ *(?\d+)? *- *(?\d+)? *$/; +function parseRanges(rangeHeader, length) { + const prefixMatch = rangePrefixRegexp.exec(rangeHeader); + if (prefixMatch === null) + return; + rangeHeader = rangeHeader.substring(prefixMatch[0].length); + if (rangeHeader.trimStart() === "") + return []; + const ranges = rangeHeader.split(","); + const result = []; + for (const range of ranges) { + const match = rangeRegexp.exec(range); + if (match === null) + return; + const { start, end } = match.groups; + if (start !== void 0 && end !== void 0) { + const rangeStart = parseInt(start); + let rangeEnd = parseInt(end); + if (rangeStart > rangeEnd) + return; + if (rangeStart >= length) + return; + if (rangeEnd >= length) + rangeEnd = length - 1; + result.push({ start: rangeStart, end: rangeEnd }); + } else if (start !== void 0 && end === void 0) { + const rangeStart = parseInt(start); + if (rangeStart >= length) + return; + result.push({ start: rangeStart, end: length - 1 }); + } else if (start === void 0 && end !== void 0) { + const suffix = parseInt(end); + if (suffix >= length) + return []; + if (suffix === 0) + continue; + result.push({ start: length - suffix, end: length - 1 }); + } else { + return; + } + } + return result; +} + +// packages/miniflare/src/workers/shared/sync.ts +var import_node_assert2 = __toESM(require("node:assert")); +var DeferredPromise = class extends Promise { + resolve; + reject; + constructor(executor = () => { + }) { + let promiseResolve; + let promiseReject; + super((resolve, reject) => { + promiseResolve = resolve; + promiseReject = reject; + return executor(resolve, reject); + }); + this.resolve = promiseResolve; + this.reject = promiseReject; + } +}; +var Mutex = class { + locked = false; + resolveQueue = []; + drainQueue = []; + lock() { + if (!this.locked) { + this.locked = true; + return; + } + return new Promise((resolve) => this.resolveQueue.push(resolve)); + } + unlock() { + (0, import_node_assert2.default)(this.locked); + if (this.resolveQueue.length > 0) { + this.resolveQueue.shift()?.(); + } else { + this.locked = false; + let resolve; + while ((resolve = this.drainQueue.shift()) !== void 0) + resolve(); + } + } + get hasWaiting() { + return this.resolveQueue.length > 0; + } + async runWith(closure) { + const acquireAwaitable = this.lock(); + if (acquireAwaitable instanceof Promise) + await acquireAwaitable; + try { + const awaitable = closure(); + if (awaitable instanceof Promise) + return await awaitable; + return awaitable; + } finally { + this.unlock(); + } + } + async drained() { + if (this.resolveQueue.length === 0) + return; + return new Promise((resolve) => this.drainQueue.push(resolve)); + } +}; +var WaitGroup = class { + counter = 0; + resolveQueue = []; + add() { + this.counter++; + } + done() { + (0, import_node_assert2.default)(this.counter > 0); + this.counter--; + if (this.counter === 0) { + let resolve; + while ((resolve = this.resolveQueue.shift()) !== void 0) + resolve(); + } + } + wait() { + if (this.counter === 0) + return Promise.resolve(); + return new Promise((resolve) => this.resolveQueue.push(resolve)); + } +}; + +// packages/miniflare/src/workers/shared/types.ts +function reduceError(e) { + return { + name: e?.name, + message: e?.message ?? String(e), + stack: e?.stack, + cause: e?.cause === void 0 ? void 0 : reduceError(e.cause) + }; +} +function maybeApply(f, maybeValue) { + return maybeValue === void 0 ? void 0 : f(maybeValue); +} + +// packages/miniflare/src/workers/kv/constants.ts +var KVLimits = { + MIN_CACHE_TTL: 60, + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 512, + MAX_VALUE_SIZE: 25 * 1024 * 1024, + MAX_VALUE_SIZE_TEST: 1024, + MAX_METADATA_SIZE: 1024 +}; +var KVParams = { + URL_ENCODED: "urlencoded", + CACHE_TTL: "cache_ttl", + EXPIRATION: "expiration", + EXPIRATION_TTL: "expiration_ttl", + LIST_LIMIT: "key_count_limit", + LIST_PREFIX: "prefix", + LIST_CURSOR: "cursor" +}; +var KVHeaders = { + EXPIRATION: "CF-Expiration", + METADATA: "CF-KV-Metadata" +}; +var SiteBindings = { + KV_NAMESPACE_SITE: "__STATIC_CONTENT", + JSON_SITE_MANIFEST: "__STATIC_CONTENT_MANIFEST", + JSON_SITE_FILTER: "MINIFLARE_SITE_FILTER" +}; +var SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/"; +function encodeSitesKey(key) { + return SITES_NO_CACHE_PREFIX + encodeURIComponent(key); +} +function decodeSitesKey(key) { + return key.startsWith(SITES_NO_CACHE_PREFIX) ? decodeURIComponent(key.substring(SITES_NO_CACHE_PREFIX.length)) : key; +} +function isSitesRequest(request) { + const url13 = new URL(request.url); + return url13.pathname.startsWith(`/${SITES_NO_CACHE_PREFIX}`); +} +function serialiseRegExp(regExp) { + const str = regExp.toString(); + return str.substring(str.indexOf("/") + 1, str.lastIndexOf("/")); +} +function serialiseRegExps(matcher) { + return { + include: matcher.include.map(serialiseRegExp), + exclude: matcher.exclude.map(serialiseRegExp) + }; +} +function deserialiseRegExps(matcher) { + return { + include: matcher.include.map((regExp) => new RegExp(regExp)), + exclude: matcher.exclude.map((regExp) => new RegExp(regExp)) + }; +} +function serialiseSiteRegExps(siteRegExps) { + return { + include: siteRegExps.include && serialiseRegExps(siteRegExps.include), + exclude: siteRegExps.exclude && serialiseRegExps(siteRegExps.exclude) + }; +} +function deserialiseSiteRegExps(siteRegExps) { + return { + include: siteRegExps.include && deserialiseRegExps(siteRegExps.include), + exclude: siteRegExps.exclude && deserialiseRegExps(siteRegExps.exclude) + }; +} +function testSiteRegExps(regExps, key) { + if (regExps.include !== void 0) + return testRegExps(regExps.include, key); + if (regExps.exclude !== void 0) + return !testRegExps(regExps.exclude, key); + return true; +} + +// packages/miniflare/src/workers/queues/constants.ts +var QueueBindings = { + SERVICE_WORKER_PREFIX: "MINIFLARE_WORKER_", + MAYBE_JSON_QUEUE_CONSUMERS: "MINIFLARE_QUEUE_CONSUMERS" +}; + +// packages/miniflare/src/workers/shared/zod.worker.ts +var import_node_buffer3 = require("node:buffer"); +var import_zod = require("zod"); +var import_zod2 = require("zod"); +var HEX_REGEXP = /^[0-9a-f]*$/i; +var BASE64_REGEXP = /^[0-9a-z+/=]*$/i; +var HexDataSchema = import_zod.z.string().regex(HEX_REGEXP).transform((hex) => import_node_buffer3.Buffer.from(hex, "hex")); +var Base64DataSchema = import_zod.z.string().regex(BASE64_REGEXP).transform((base64) => import_node_buffer3.Buffer.from(base64, "base64")); + +// packages/miniflare/src/workers/queues/schemas.ts +var QueueConsumerOptionsSchema = /* @__PURE__ */ import_zod2.z.object({ + // https://developers.cloudflare.com/queues/platform/configuration/#consumer + // https://developers.cloudflare.com/queues/platform/limits/ + maxBatchSize: import_zod2.z.number().min(0).max(100).optional(), + maxBatchTimeout: import_zod2.z.number().min(0).max(30).optional(), + // seconds + maxRetires: import_zod2.z.number().min(0).max(100).optional(), + deadLetterQueue: import_zod2.z.ostring() +}); +var QueueConsumerSchema = /* @__PURE__ */ import_zod2.z.intersection( + QueueConsumerOptionsSchema, + import_zod2.z.object({ workerName: import_zod2.z.string() }) +); +var QueueConsumersSchema = /* @__PURE__ */ import_zod2.z.record(QueueConsumerSchema); +var QueueContentTypeSchema = /* @__PURE__ */ import_zod2.z.enum(["text", "json", "bytes", "v8"]).default("v8"); +var QueueIncomingMessageSchema = /* @__PURE__ */ import_zod2.z.object({ + contentType: QueueContentTypeSchema, + body: Base64DataSchema, + // When enqueuing messages on dead-letter queues, we want to reuse the same ID + // and timestamp + id: import_zod2.z.ostring(), + timestamp: import_zod2.z.onumber() +}); +var QueuesBatchRequestSchema = /* @__PURE__ */ import_zod2.z.object({ + messages: import_zod2.z.array(QueueIncomingMessageSchema) +}); + +// packages/miniflare/src/http/request.ts +var import_undici2 = require("undici"); +var kCf = Symbol("kCf"); +var Request = class extends import_undici2.Request { + // We should be able to use a private `#cf` property here instead of a symbol + // here, but we need to set this on a clone, which would otherwise lead to a + // "Cannot write private member to an object whose class did not declare it" + // error. + [kCf]; + constructor(input, init2) { + super(input, init2); + this[kCf] = init2?.cf; + if (input instanceof Request) + this[kCf] ??= input.cf; + } + get cf() { + return this[kCf]; + } + // JSDoc comment so retained when bundling types with api-extractor + /** @ts-expect-error `clone` is actually defined as a method internally */ + clone() { + const request = super.clone(); + Object.setPrototypeOf(request, Request.prototype); + request[kCf] = this[kCf]; + return request; + } +}; + +// packages/miniflare/src/http/response.ts +var import_undici3 = require("undici"); +var kWebSocket = Symbol("kWebSocket"); +var Response = class extends import_undici3.Response { + // We should be able to use a private `#webSocket` property here instead of a + // symbol here, but `undici` calls `this.status` in its constructor, which + // causes a "Cannot read private member from an object whose class did not + // declare it" error. + [kWebSocket]; + // Override BaseResponse's static methods for building Responses to return + // our type instead. Ideally, we don't want to use `Object.setPrototypeOf`. + // Unfortunately, `error()` and `redirect()` set the internal header guard + // to "immutable". + static error() { + const response = import_undici3.Response.error(); + Object.setPrototypeOf(response, Response.prototype); + return response; + } + static redirect(url13, status) { + const response = import_undici3.Response.redirect(url13, status); + Object.setPrototypeOf(response, Response.prototype); + return response; + } + static json(data, init2) { + const body = JSON.stringify(data); + const response = new Response(body, init2); + response.headers.set("Content-Type", "application/json"); + return response; + } + constructor(body, init2) { + if (init2?.webSocket) { + if (init2.status !== 101) { + throw new RangeError( + "Responses with a WebSocket must have status code 101." + ); + } + init2 = { ...init2, status: 200 }; + } + super(body, init2); + this[kWebSocket] = init2?.webSocket ?? null; + } + // JSDoc comment so retained when bundling types with api-extractor + /** @ts-expect-error `status` is actually defined as a getter internally */ + get status() { + return this[kWebSocket] ? 101 : super.status; + } + get webSocket() { + return this[kWebSocket]; + } + // JSDoc comment so retained when bundling types with api-extractor + /** @ts-expect-error `clone` is actually defined as a method internally */ + clone() { + if (this[kWebSocket]) { + throw new TypeError("Cannot clone a response to a WebSocket handshake."); + } + const response = super.clone(); + Object.setPrototypeOf(response, Response.prototype); + return response; + } +}; + +// packages/miniflare/src/http/websocket.ts +var import_assert2 = __toESM(require("assert")); +var import_events = require("events"); +var import_ws = __toESM(require("ws")); + +// packages/miniflare/src/shared/colour.ts +var originalEnabled = $.enabled; +function _forceColour(enabled = originalEnabled) { + $.enabled = enabled; +} + +// packages/miniflare/src/shared/error.ts +var MiniflareError = class extends Error { + constructor(code, message, cause) { + super(message); + this.code = code; + this.cause = cause; + Object.setPrototypeOf(this, new.target.prototype); + this.name = `${new.target.name} [${code}]`; + } +}; +var MiniflareCoreError = class extends MiniflareError { +}; + +// packages/miniflare/src/shared/event.ts +var TypedEventTarget = class extends EventTarget { + addEventListener(type, listener, options) { + super.addEventListener( + type, + listener, + options + ); + } + removeEventListener(type, listener, options) { + super.removeEventListener( + type, + listener, + options + ); + } + dispatchEvent(event) { + return super.dispatchEvent(event); + } +}; + +// packages/miniflare/src/shared/log.ts +var import_path4 = __toESM(require("path")); +var cwd = process.cwd(); +var cwdNodeModules = import_path4.default.join(cwd, "node_modules"); +var LEVEL_PREFIX = { + [0 /* NONE */]: "", + [1 /* ERROR */]: "err", + [2 /* WARN */]: "wrn", + [3 /* INFO */]: "inf", + [4 /* DEBUG */]: "dbg", + [5 /* VERBOSE */]: "vrb" +}; +var LEVEL_COLOUR = { + [0 /* NONE */]: reset, + [1 /* ERROR */]: red, + [2 /* WARN */]: yellow, + [3 /* INFO */]: green, + [4 /* DEBUG */]: grey, + [5 /* VERBOSE */]: (input) => dim(grey(input)) +}; +function prefixError(prefix, e) { + if (e.stack) { + return new Proxy(e, { + get(target, propertyKey, receiver) { + const value = Reflect.get(target, propertyKey, receiver); + return propertyKey === "stack" ? `${prefix}: ${value}` : value; + } + }); + } + return e; +} +function dimInternalStackLine(line) { + if (line.startsWith(" at") && (!line.includes(cwd) || line.includes(cwdNodeModules))) { + return dim(line); + } + return line; +} +var Log = class { + constructor(level = 3 /* INFO */, opts = {}) { + this.level = level; + const prefix = opts.prefix ?? "mf"; + const suffix = opts.suffix ?? ""; + this.#prefix = prefix ? prefix + ":" : ""; + this.#suffix = suffix ? ":" + suffix : ""; + } + #prefix; + #suffix; + log(message) { + console.log(message); + } + logWithLevel(level, message) { + if (level <= this.level) { + const prefix = `[${this.#prefix}${LEVEL_PREFIX[level]}${this.#suffix}]`; + this.log(LEVEL_COLOUR[level](`${prefix} ${message}`)); + } + } + error(message) { + if (this.level < 1 /* ERROR */) { + throw message; + } else if (message.stack) { + const lines = message.stack.split("\n").map(dimInternalStackLine); + this.logWithLevel(1 /* ERROR */, lines.join("\n")); + } else { + this.logWithLevel(1 /* ERROR */, message.toString()); + } + if (message.cause) { + this.error(prefixError("Cause", message.cause)); + } + } + warn(message) { + this.logWithLevel(2 /* WARN */, message); + } + info(message) { + this.logWithLevel(3 /* INFO */, message); + } + debug(message) { + this.logWithLevel(4 /* DEBUG */, message); + } + verbose(message) { + this.logWithLevel(5 /* VERBOSE */, message); + } +}; +var NoOpLog = class extends Log { + constructor() { + super(0 /* NONE */); + } + log() { + } + error(message) { + throw message; + } +}; +var ansiRegexpPattern = [ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))" +].join("|"); +var ansiRegexp = new RegExp(ansiRegexpPattern, "g"); +function stripAnsi(value) { + return value.replace(ansiRegexp, ""); +} + +// packages/miniflare/src/shared/matcher.ts +var import_glob_to_regexp = __toESM(require("glob-to-regexp")); +function globsToRegExps(globs = []) { + const include = []; + const exclude = []; + const opts = { globstar: true, flags: "g" }; + for (const glob of globs) { + if (glob.startsWith("!")) { + exclude.push(new RegExp((0, import_glob_to_regexp.default)(glob.slice(1), opts), "")); + } else { + include.push(new RegExp((0, import_glob_to_regexp.default)(glob, opts), "")); + } + } + return { include, exclude }; +} + +// packages/miniflare/src/shared/streams.ts +var import_web = require("stream/web"); +function prefixStream(prefix, stream) { + const identity = new import_web.TransformStream(); + const writer = identity.writable.getWriter(); + void writer.write(prefix).then(() => { + writer.releaseLock(); + return stream.pipeTo(identity.writable); + }).catch((error) => { + return writer.abort(error); + }); + return identity.readable; +} +async function readPrefix(stream, prefixLength) { + const chunks = []; + let chunksLength = 0; + for await (const chunk of stream.values({ preventCancel: true })) { + chunks.push(chunk); + chunksLength += chunk.byteLength; + if (chunksLength >= prefixLength) + break; + } + if (chunksLength < prefixLength) { + throw new RangeError( + `Expected ${prefixLength} byte prefix, but received ${chunksLength} byte stream` + ); + } + const atLeastPrefix = Buffer.concat(chunks, chunksLength); + const prefix = atLeastPrefix.subarray(0, prefixLength); + let rest = stream; + if (chunksLength > prefixLength) { + rest = prefixStream(atLeastPrefix.subarray(prefixLength), stream); + } + return [prefix, rest]; +} + +// packages/miniflare/src/shared/types.ts +var import_zod3 = require("zod"); +function zAwaitable(type) { + return type.or(import_zod3.z.promise(type)); +} +var LiteralSchema = import_zod3.z.union([ + import_zod3.z.string(), + import_zod3.z.number(), + import_zod3.z.boolean(), + import_zod3.z.null() +]); +var JsonSchema = import_zod3.z.lazy( + () => import_zod3.z.union([LiteralSchema, import_zod3.z.array(JsonSchema), import_zod3.z.record(JsonSchema)]) +); + +// packages/miniflare/src/http/websocket.ts +var MessageEvent = class extends Event { + data; + constructor(type, init2) { + super(type); + this.data = init2.data; + } +}; +var CloseEvent = class extends Event { + code; + reason; + wasClean; + constructor(type, init2) { + super(type); + this.code = init2?.code ?? 1005; + this.reason = init2?.reason ?? ""; + this.wasClean = init2?.wasClean ?? false; + } +}; +var ErrorEvent = class extends Event { + error; + constructor(type, init2) { + super(type); + this.error = init2?.error ?? null; + } +}; +var kPair = Symbol("kPair"); +var kAccepted = Symbol("kAccepted"); +var kCoupled = Symbol("kCoupled"); +var kClosedOutgoing = Symbol("kClosedOutgoing"); +var kClosedIncoming = Symbol("kClosedIncoming"); +var kSend = Symbol("kSend"); +var kClose = Symbol("kClose"); +var kError = Symbol("kError"); +var _dispatchQueue, _a, _b, _c, _d, _e, _queuingDispatchToPair, queuingDispatchToPair_fn; +var _WebSocket = class extends TypedEventTarget { + constructor() { + super(...arguments); + __privateAdd(this, _queuingDispatchToPair); + __privateAdd(this, _dispatchQueue, []); + __publicField(this, _a); + __publicField(this, _b, false); + __publicField(this, _c, false); + __publicField(this, _d, false); + __publicField(this, _e, false); + } + get readyState() { + if (this[kClosedOutgoing] && this[kClosedIncoming]) { + return _WebSocket.READY_STATE_CLOSED; + } else if (this[kClosedOutgoing] || this[kClosedIncoming]) { + return _WebSocket.READY_STATE_CLOSING; + } + return _WebSocket.READY_STATE_OPEN; + } + accept() { + if (this[kCoupled]) { + throw new TypeError( + "Can't accept() WebSocket that was already used in a response." + ); + } + if (this[kAccepted]) + return; + this[kAccepted] = true; + if (__privateGet(this, _dispatchQueue) !== void 0) { + for (const event of __privateGet(this, _dispatchQueue)) + this.dispatchEvent(event); + __privateSet(this, _dispatchQueue, void 0); + } + } + send(message) { + if (!this[kAccepted]) { + throw new TypeError( + "You must call accept() on this WebSocket before sending messages." + ); + } + this[kSend](message); + } + [(_a = kPair, _b = kAccepted, _c = kCoupled, _d = kClosedOutgoing, _e = kClosedIncoming, kSend)](message) { + if (this[kClosedOutgoing]) { + throw new TypeError("Can't call WebSocket send() after close()."); + } + const event = new MessageEvent("message", { data: message }); + void __privateMethod(this, _queuingDispatchToPair, queuingDispatchToPair_fn).call(this, event); + } + close(code, reason) { + if (code) { + const validCode = code >= 1e3 && code < 5e3 && code !== 1004 && code !== 1005 && code !== 1006 && code !== 1015; + if (!validCode) + throw new TypeError("Invalid WebSocket close code."); + } + if (reason !== void 0 && code === void 0) { + throw new TypeError( + "If you specify a WebSocket close reason, you must also specify a code." + ); + } + if (!this[kAccepted]) { + throw new TypeError( + "You must call accept() on this WebSocket before sending messages." + ); + } + this[kClose](code, reason); + } + [kClose](code, reason) { + if (this[kClosedOutgoing]) + throw new TypeError("WebSocket already closed"); + const pair = this[kPair]; + (0, import_assert2.default)(pair !== void 0); + this[kClosedOutgoing] = true; + pair[kClosedIncoming] = true; + const event = new CloseEvent("close", { code, reason }); + void __privateMethod(this, _queuingDispatchToPair, queuingDispatchToPair_fn).call(this, event); + } + [kError](error) { + const event = new ErrorEvent("error", { error }); + void __privateMethod(this, _queuingDispatchToPair, queuingDispatchToPair_fn).call(this, event); + } +}; +var WebSocket = _WebSocket; +_dispatchQueue = new WeakMap(); +_queuingDispatchToPair = new WeakSet(); +queuingDispatchToPair_fn = async function(event) { + const pair = this[kPair]; + (0, import_assert2.default)(pair !== void 0); + if (pair[kAccepted]) { + pair.dispatchEvent(event); + } else { + (0, import_assert2.default)(__privateGet(pair, _dispatchQueue) !== void 0); + __privateGet(pair, _dispatchQueue).push(event); + } +}; +// The Workers runtime prefixes these constants with `READY_STATE_`, unlike +// those in the spec: https://websockets.spec.whatwg.org/#interface-definition +__publicField(WebSocket, "READY_STATE_CONNECTING", 0); +__publicField(WebSocket, "READY_STATE_OPEN", 1); +__publicField(WebSocket, "READY_STATE_CLOSING", 2); +__publicField(WebSocket, "READY_STATE_CLOSED", 3); +var WebSocketPair = function() { + if (!(this instanceof WebSocketPair)) { + throw new TypeError( + "Failed to construct 'WebSocketPair': Please use the 'new' operator, this object constructor cannot be called as a function." + ); + } + this[0] = new WebSocket(); + this[1] = new WebSocket(); + this[0][kPair] = this[1]; + this[1][kPair] = this[0]; +}; +async function coupleWebSocket(ws, pair) { + if (pair[kCoupled]) { + throw new TypeError( + "Can't return WebSocket that was already used in a response." + ); + } + if (pair[kAccepted]) { + throw new TypeError( + "Can't return WebSocket in a Response after calling accept()." + ); + } + ws.on("message", (message, isBinary) => { + if (!pair[kClosedOutgoing]) { + pair[kSend](isBinary ? viewToBuffer(message) : message.toString()); + } + }); + ws.on("close", (code, reason) => { + if (!pair[kClosedOutgoing]) { + pair[kClose](code, reason.toString()); + } + }); + ws.on("error", (error) => { + pair[kError](error); + }); + pair.addEventListener("message", (e) => { + ws.send(e.data); + }); + pair.addEventListener("close", (e) => { + if (e.code === 1005) { + ws.close(); + } else if (e.code === 1006) { + ws.terminate(); + } else { + ws.close(e.code, e.reason); + } + }); + if (ws.readyState === import_ws.default.CONNECTING) { + await (0, import_events.once)(ws, "open"); + } else if (ws.readyState >= import_ws.default.CLOSING) { + throw new TypeError("Incoming WebSocket connection already closed."); + } + pair.accept(); + pair[kCoupled] = true; +} + +// packages/miniflare/src/http/fetch.ts +var allowUnauthorizedDispatchers = /* @__PURE__ */ new WeakSet(); +function registerAllowUnauthorizedDispatcher(dispatcher) { + allowUnauthorizedDispatchers.add(dispatcher); +} +var ignored = ["transfer-encoding", "connection", "keep-alive", "expect"]; +function headersFromIncomingRequest(req) { + const entries = Object.entries(req.headers).filter( + (pair) => { + const [name, value] = pair; + return !ignored.includes(name) && value !== void 0; + } + ); + return new import_undici4.Headers(Object.fromEntries(entries)); +} +async function fetch2(input, init2) { + const requestInit = init2; + const request = new Request(input, requestInit); + if (request.method === "GET" && request.headers.get("upgrade") === "websocket") { + const url13 = new URL(request.url); + if (url13.protocol !== "http:" && url13.protocol !== "https:") { + throw new TypeError( + `Fetch API cannot load: ${url13.toString()}. +Make sure you're using http(s):// URLs for WebSocket requests via fetch.` + ); + } + url13.protocol = url13.protocol.replace("http", "ws"); + const headers = {}; + let protocols; + for (const [key, value] of request.headers.entries()) { + if (key.toLowerCase() === "sec-websocket-protocol") { + protocols = value.split(",").map((protocol) => protocol.trim()); + } else { + headers[key] = value; + } + } + const rejectUnauthorized = requestInit?.dispatcher !== void 0 && allowUnauthorizedDispatchers.has(requestInit?.dispatcher) ? { rejectUnauthorized: false } : {}; + const ws = new import_ws2.default(url13, protocols, { + followRedirects: request.redirect === "follow", + headers, + ...rejectUnauthorized + }); + const headersPromise = new DeferredPromise(); + ws.once("upgrade", (req) => { + headersPromise.resolve(headersFromIncomingRequest(req)); + }); + const [worker, client] = Object.values(new WebSocketPair()); + await coupleWebSocket(ws, client); + return new Response(null, { + status: 101, + webSocket: worker, + headers: await headersPromise + }); + } + const response = await (0, import_undici4.fetch)(request, { + dispatcher: requestInit?.dispatcher + }); + return new Response(response.body, response); +} + +// packages/miniflare/src/http/server.ts +var import_promises10 = __toESM(require("fs/promises")); + +// packages/miniflare/src/plugins/cache/index.ts +var import_promises3 = __toESM(require("fs/promises")); + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/cache/cache.worker.ts +var import_fs3 = __toESM(require("fs")); +var import_path5 = __toESM(require("path")); +var import_url3 = __toESM(require("url")); +var contents3; +function cache_worker_default() { + if (contents3 !== void 0) + return contents3; + const filePath = import_path5.default.join(__dirname, "workers", "cache/cache.worker.js"); + contents3 = import_fs3.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url3.default.pathToFileURL(filePath); + return contents3; +} + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/cache/cache-entry.worker.ts +var import_fs4 = __toESM(require("fs")); +var import_path6 = __toESM(require("path")); +var import_url4 = __toESM(require("url")); +var contents4; +function cache_entry_worker_default() { + if (contents4 !== void 0) + return contents4; + const filePath = import_path6.default.join(__dirname, "workers", "cache/cache-entry.worker.js"); + contents4 = import_fs4.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url4.default.pathToFileURL(filePath); + return contents4; +} + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/cache/cache-entry-noop.worker.ts +var import_fs5 = __toESM(require("fs")); +var import_path7 = __toESM(require("path")); +var import_url5 = __toESM(require("url")); +var contents5; +function cache_entry_noop_worker_default() { + if (contents5 !== void 0) + return contents5; + const filePath = import_path7.default.join(__dirname, "workers", "cache/cache-entry-noop.worker.js"); + contents5 = import_fs5.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url5.default.pathToFileURL(filePath); + return contents5; +} + +// packages/miniflare/src/plugins/cache/index.ts +var import_zod5 = require("zod"); + +// packages/miniflare/src/plugins/shared/index.ts +var import_crypto = __toESM(require("crypto")); +var import_fs7 = require("fs"); +var import_promises2 = __toESM(require("fs/promises")); +var import_path9 = __toESM(require("path")); +var import_url8 = require("url"); +var import_zod4 = require("zod"); + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/shared/object-entry.worker.ts +var import_fs6 = __toESM(require("fs")); +var import_path8 = __toESM(require("path")); +var import_url6 = __toESM(require("url")); +var contents6; +function object_entry_worker_default() { + if (contents6 !== void 0) + return contents6; + const filePath = import_path8.default.join(__dirname, "workers", "shared/object-entry.worker.js"); + contents6 = import_fs6.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url6.default.pathToFileURL(filePath); + return contents6; +} + +// packages/miniflare/src/plugins/shared/constants.ts +var SOCKET_ENTRY = "entry"; +var SERVICE_LOOPBACK = "loopback"; +var HEADER_CF_BLOB = "MF-CF-Blob"; +var WORKER_BINDING_SERVICE_LOOPBACK = { + name: CoreBindings.SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } +}; +function objectEntryWorker(durableObjectNamespace, namespace) { + return { + compatibilityDate: "2023-07-24", + modules: [ + { name: "object-entry.worker.js", esModule: object_entry_worker_default() } + ], + bindings: [ + { name: SharedBindings.TEXT_NAMESPACE, text: namespace }, + { + name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT, + durableObjectNamespace + } + ] + }; +} + +// packages/miniflare/src/plugins/shared/routing.ts +var import_url7 = require("url"); +var RouterError = class extends MiniflareError { +}; +function routeSpecificity(url13) { + const hostParts = url13.host.split("."); + let hostScore = hostParts.length; + if (hostParts[0] === "*") + hostScore -= 2; + const pathParts = url13.pathname.split("/"); + let pathScore = pathParts.length; + if (pathParts[pathParts.length - 1] === "*") + pathScore -= 2; + return hostScore * 26 + pathScore; +} +function parseRoutes(allRoutes) { + const routes = []; + for (const [target, targetRoutes] of allRoutes) { + for (const route of targetRoutes) { + const hasProtocol = /^[a-z0-9+\-.]+:\/\//i.test(route); + let urlInput = route; + if (!hasProtocol) + urlInput = `https://${urlInput}`; + const url13 = new import_url7.URL(urlInput); + const specificity = routeSpecificity(url13); + const protocol = hasProtocol ? url13.protocol : void 0; + const internationalisedAllowHostnamePrefix = url13.hostname.startsWith("xn--*"); + const allowHostnamePrefix = url13.hostname.startsWith("*") || internationalisedAllowHostnamePrefix; + const anyHostname = url13.hostname === "*"; + if (allowHostnamePrefix && !anyHostname) { + let hostname = url13.hostname; + if (internationalisedAllowHostnamePrefix) { + hostname = (0, import_url7.domainToUnicode)(hostname); + } + url13.hostname = hostname.substring(1); + } + const allowPathSuffix = url13.pathname.endsWith("*"); + if (allowPathSuffix) { + url13.pathname = url13.pathname.substring(0, url13.pathname.length - 1); + } + if (url13.search) { + throw new RouterError( + "ERR_QUERY_STRING", + `Route "${route}" for "${target}" contains a query string. This is not allowed.` + ); + } + if (url13.toString().includes("*") && !anyHostname) { + throw new RouterError( + "ERR_INFIX_WILDCARD", + `Route "${route}" for "${target}" contains an infix wildcard. This is not allowed.` + ); + } + routes.push({ + target, + route, + specificity, + protocol, + allowHostnamePrefix, + hostname: anyHostname ? "" : url13.hostname, + path: url13.pathname, + allowPathSuffix + }); + } + } + routes.sort((a, b) => { + if (a.specificity === b.specificity) { + return b.route.length - a.route.length; + } else { + return b.specificity - a.specificity; + } + }); + return routes; +} + +// packages/miniflare/src/plugins/shared/index.ts +var DEFAULT_PERSIST_ROOT = ".mf"; +var PersistenceSchema = import_zod4.z.boolean().or(import_zod4.z.string()).optional(); +var kProxyNodeBinding = Symbol("kProxyNodeBinding"); +function namespaceKeys(namespaces) { + if (Array.isArray(namespaces)) { + return namespaces; + } else if (namespaces !== void 0) { + return Object.keys(namespaces); + } else { + return []; + } +} +function namespaceEntries(namespaces) { + if (Array.isArray(namespaces)) { + return namespaces.map((bindingName) => [bindingName, bindingName]); + } else if (namespaces !== void 0) { + return Object.entries(namespaces); + } else { + return []; + } +} +function maybeParseURL(url13) { + if (typeof url13 !== "string" || import_path9.default.isAbsolute(url13)) + return; + try { + return new URL(url13); + } catch { + } +} +function getPersistPath(pluginName, tmpPath, persist) { + const memoryishPath = import_path9.default.join(tmpPath, pluginName); + if (persist === void 0 || persist === false) { + return memoryishPath; + } + const url13 = maybeParseURL(persist); + if (url13 !== void 0) { + if (url13.protocol === "memory:") { + return memoryishPath; + } else if (url13.protocol === "file:") { + return (0, import_url8.fileURLToPath)(url13); + } + throw new MiniflareCoreError( + "ERR_PERSIST_UNSUPPORTED", + `Unsupported "${url13.protocol}" persistence protocol for storage: ${url13.href}` + ); + } + return persist === true ? import_path9.default.join(DEFAULT_PERSIST_ROOT, pluginName) : persist; +} +function durableObjectNamespaceIdFromName(uniqueKey, name) { + const key = import_crypto.default.createHash("sha256").update(uniqueKey).digest(); + const nameHmac = import_crypto.default.createHmac("sha256", key).update(name).digest().subarray(0, 16); + const hmac = import_crypto.default.createHmac("sha256", key).update(nameHmac).digest().subarray(0, 16); + return Buffer.concat([nameHmac, hmac]).toString("hex"); +} +async function migrateDatabase(log, uniqueKey, persistPath, namespace) { + const sanitisedNamespace = sanitisePath(namespace); + const previousDir = import_path9.default.join(persistPath, sanitisedNamespace); + const previousPath = import_path9.default.join(previousDir, "db.sqlite"); + const previousWalPath = import_path9.default.join(previousDir, "db.sqlite-wal"); + if (!(0, import_fs7.existsSync)(previousPath)) + return; + const id = durableObjectNamespaceIdFromName(uniqueKey, namespace); + const newDir = import_path9.default.join(persistPath, uniqueKey); + const newPath = import_path9.default.join(newDir, `${id}.sqlite`); + const newWalPath = import_path9.default.join(newDir, `${id}.sqlite-wal`); + if ((0, import_fs7.existsSync)(newPath)) { + log.debug( + `Not migrating ${previousPath} to ${newPath} as it already exists` + ); + return; + } + log.debug(`Migrating ${previousPath} to ${newPath}...`); + await import_promises2.default.mkdir(newDir, { recursive: true }); + try { + await import_promises2.default.copyFile(previousPath, newPath); + if ((0, import_fs7.existsSync)(previousWalPath)) { + await import_promises2.default.copyFile(previousWalPath, newWalPath); + } + await import_promises2.default.unlink(previousPath); + await import_promises2.default.unlink(previousWalPath); + } catch (e) { + log.warn(`Error migrating ${previousPath} to ${newPath}: ${e}`); + } +} + +// packages/miniflare/src/plugins/cache/index.ts +var CacheOptionsSchema = import_zod5.z.object({ + cache: import_zod5.z.boolean().optional(), + cacheWarnUsage: import_zod5.z.boolean().optional() +}); +var CacheSharedOptionsSchema = import_zod5.z.object({ + cachePersist: PersistenceSchema +}); +var CACHE_PLUGIN_NAME = "cache"; +var CACHE_STORAGE_SERVICE_NAME = `${CACHE_PLUGIN_NAME}:storage`; +var CACHE_SERVICE_PREFIX = `${CACHE_PLUGIN_NAME}:cache`; +var CACHE_OBJECT_CLASS_NAME = "CacheObject"; +var CACHE_OBJECT = { + serviceName: CACHE_SERVICE_PREFIX, + className: CACHE_OBJECT_CLASS_NAME +}; +function getCacheServiceName(workerIndex) { + return `${CACHE_PLUGIN_NAME}:${workerIndex}`; +} +var CACHE_PLUGIN = { + options: CacheOptionsSchema, + sharedOptions: CacheSharedOptionsSchema, + getBindings() { + return []; + }, + getNodeBindings() { + return {}; + }, + async getServices({ sharedOptions, options, workerIndex, tmpPath }) { + const cache = options.cache ?? true; + const cacheWarnUsage = options.cacheWarnUsage ?? false; + let entryWorker; + if (cache) { + entryWorker = { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { name: "cache-entry.worker.js", esModule: cache_entry_worker_default() } + ], + bindings: [ + { + name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT, + durableObjectNamespace: CACHE_OBJECT + }, + { + name: CacheBindings.MAYBE_JSON_CACHE_WARN_USAGE, + json: JSON.stringify(cacheWarnUsage) + } + ] + }; + } else { + entryWorker = { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "cache-entry-noop.worker.js", + esModule: cache_entry_noop_worker_default() + } + ] + }; + } + const uniqueKey = `miniflare-${CACHE_OBJECT_CLASS_NAME}`; + const persist = sharedOptions.cachePersist; + const persistPath = getPersistPath(CACHE_PLUGIN_NAME, tmpPath, persist); + await import_promises3.default.mkdir(persistPath, { recursive: true }); + const storageService = { + name: CACHE_STORAGE_SERVICE_NAME, + disk: { path: persistPath, writable: true } + }; + const objectService = { + name: CACHE_SERVICE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "cache.worker.js", + esModule: cache_worker_default() + } + ], + durableObjectNamespaces: [ + { + className: CACHE_OBJECT_CLASS_NAME, + uniqueKey + } + ], + // Store Durable Object SQL databases in persist path + durableObjectStorage: { localDisk: CACHE_STORAGE_SERVICE_NAME }, + // Bind blob disk directory service to object + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: CACHE_STORAGE_SERVICE_NAME } + }, + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + } + ] + } + }; + const services = [ + { name: getCacheServiceName(workerIndex), worker: entryWorker }, + storageService, + objectService + ]; + return services; + } +}; + +// packages/miniflare/src/plugins/core/index.ts +var import_assert8 = __toESM(require("assert")); +var import_fs11 = require("fs"); +var import_promises5 = __toESM(require("fs/promises")); +var import_path13 = __toESM(require("path")); +var import_tls = __toESM(require("tls")); +var import_util3 = require("util"); +var import_undici7 = require("undici"); + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/core/entry.worker.ts +var import_fs8 = __toESM(require("fs")); +var import_path10 = __toESM(require("path")); +var import_url9 = __toESM(require("url")); +var contents7; +function entry_worker_default() { + if (contents7 !== void 0) + return contents7; + const filePath = import_path10.default.join(__dirname, "workers", "core/entry.worker.js"); + contents7 = import_fs8.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url9.default.pathToFileURL(filePath); + return contents7; +} + +// packages/miniflare/src/plugins/core/index.ts +var import_zod11 = require("zod"); + +// packages/miniflare/src/runtime/index.ts +var import_assert3 = __toESM(require("assert")); +var import_child_process = __toESM(require("child_process")); +var import_readline = __toESM(require("readline")); +var import_stream = require("stream"); +var import_workerd2 = __toESM(require("workerd")); +var import_zod6 = require("zod"); + +// packages/miniflare/src/runtime/config/index.ts +var import_capnp_ts = require("capnp-ts"); + +// packages/miniflare/src/runtime/config/workerd.ts +var import_workerd_capnp = __toESM(require_workerd_capnp()); +var kVoid = Symbol("kVoid"); + +// packages/miniflare/src/runtime/config/index.ts +var import_workerd_capnp2 = __toESM(require_workerd_capnp()); +function capitalize(str) { + return str.length > 0 ? str[0].toUpperCase() + str.substring(1) : str; +} +function encodeCapnpStruct(obj, struct) { + const anyStruct = struct; + for (const [key, value] of Object.entries(obj)) { + const capitalized = capitalize(key); + if (value instanceof Uint8Array) { + const newData = anyStruct[`init${capitalized}`](value.byteLength); + newData.copyBuffer(value); + } else if (Array.isArray(value)) { + const newList = anyStruct[`init${capitalized}`](value.length); + for (let i = 0; i < value.length; i++) { + if (typeof value[i] === "object") { + encodeCapnpStruct(value[i], newList.get(i)); + } else { + newList.set(i, value[i]); + } + } + } else if (typeof value === "object") { + const newStruct = anyStruct[`init${capitalized}`](); + encodeCapnpStruct(value, newStruct); + } else if (value === kVoid) { + anyStruct[`set${capitalized}`](); + } else if (value !== void 0) { + anyStruct[`set${capitalized}`](value); + } + } +} +function serializeConfig(config) { + const message = new import_capnp_ts.Message(); + const struct = message.initRoot(import_workerd_capnp2.Config); + encodeCapnpStruct(config, struct); + return Buffer.from(message.toArrayBuffer()); +} + +// packages/miniflare/src/runtime/index.ts +var ControlMessageSchema = import_zod6.z.object({ + event: import_zod6.z.literal("listen"), + socket: import_zod6.z.string(), + port: import_zod6.z.number() +}); +async function waitForPort(socket, stream, options) { + if (options?.signal?.aborted) + return; + const lines = import_readline.default.createInterface(stream); + const abortListener = () => lines.close(); + options?.signal?.addEventListener("abort", abortListener, { once: true }); + try { + for await (const line of lines) { + const message = ControlMessageSchema.safeParse(JSON.parse(line)); + if (message.success && message.data.socket === socket) { + return message.data.port; + } + } + } finally { + options?.signal?.removeEventListener("abort", abortListener); + } +} +function waitForExit(process2) { + return new Promise((resolve) => { + process2.once("exit", () => resolve()); + }); +} +function pipeOutput(runtime) { + const stdout = import_readline.default.createInterface(runtime.stdout); + const stderr = import_readline.default.createInterface(runtime.stderr); + stdout.on("line", (data) => console.log(data)); + stderr.on("line", (data) => console.error(red(data))); +} +var Runtime = class { + constructor(opts) { + this.opts = opts; + this.#command = process.env.MINIFLARE_WORKERD_PATH ?? import_workerd2.default; + } + #command; + #process; + #processExitPromise; + get #args() { + const args = [ + "serve", + // Required to use binary capnp config + "--binary", + // Required to use compatibility flags without a default-on date, + // (e.g. "streams_enable_constructors"), see https://github.com/cloudflare/workerd/pull/21 + "--experimental", + `--socket-addr=${SOCKET_ENTRY}=${this.opts.entryHost}:${this.opts.entryPort}`, + `--external-addr=${SERVICE_LOOPBACK}=localhost:${this.opts.loopbackPort}`, + // Configure extra pipe for receiving control messages (e.g. when ready) + "--control-fd=3", + // Read config from stdin + "-" + ]; + if (this.opts.inspectorPort !== void 0) { + args.push(`--inspector-addr=localhost:${this.opts.inspectorPort}`); + } + if (this.opts.verbose) { + args.push("--verbose"); + } + return args; + } + async updateConfig(configBuffer, options) { + await this.dispose(); + if (options?.entryPort !== void 0) { + this.opts.entryPort = options.entryPort; + } + const runtimeProcess = import_child_process.default.spawn(this.#command, this.#args, { + stdio: ["pipe", "pipe", "pipe", "pipe"], + env: process.env + }); + this.#process = runtimeProcess; + this.#processExitPromise = waitForExit(runtimeProcess); + pipeOutput(runtimeProcess); + const controlPipe = runtimeProcess.stdio[3]; + (0, import_assert3.default)(controlPipe instanceof import_stream.Readable); + runtimeProcess.stdin.write(configBuffer); + runtimeProcess.stdin.end(); + return waitForPort(SOCKET_ENTRY, controlPipe, options); + } + dispose() { + this.#process?.kill("SIGKILL"); + return this.#processExitPromise; + } +}; + +// packages/miniflare/src/plugins/do/index.ts +var import_promises4 = __toESM(require("fs/promises")); +var import_zod7 = require("zod"); +var DurableObjectsOptionsSchema = import_zod7.z.object({ + durableObjects: import_zod7.z.record( + import_zod7.z.union([ + import_zod7.z.string(), + import_zod7.z.object({ + className: import_zod7.z.string(), + scriptName: import_zod7.z.string().optional(), + // Allow `uniqueKey` to be customised. We use in Wrangler when setting + // up stub Durable Objects that proxy requests to Durable Objects in + // another `workerd` process, to ensure the IDs created by the stub + // object can be used by the real object too. + unsafeUniqueKey: import_zod7.z.string().optional() + }) + ]) + ).optional() +}); +var DurableObjectsSharedOptionsSchema = import_zod7.z.object({ + durableObjectsPersist: PersistenceSchema +}); +function normaliseDurableObject(designator) { + const isObject = typeof designator === "object"; + const className = isObject ? designator.className : designator; + const serviceName = isObject && designator.scriptName !== void 0 ? getUserServiceName(designator.scriptName) : void 0; + const unsafeUniqueKey = isObject ? designator.unsafeUniqueKey : void 0; + return { className, serviceName, unsafeUniqueKey }; +} +var DURABLE_OBJECTS_PLUGIN_NAME = "do"; +var DURABLE_OBJECTS_STORAGE_SERVICE_NAME = `${DURABLE_OBJECTS_PLUGIN_NAME}:storage`; +var DURABLE_OBJECTS_PLUGIN = { + options: DurableObjectsOptionsSchema, + sharedOptions: DurableObjectsSharedOptionsSchema, + getBindings(options) { + return Object.entries(options.durableObjects ?? {}).map( + ([name, klass]) => { + const { className, serviceName } = normaliseDurableObject(klass); + return { + name, + durableObjectNamespace: { className, serviceName } + }; + } + ); + }, + getNodeBindings(options) { + const objects = Object.keys(options.durableObjects ?? {}); + return Object.fromEntries(objects.map((name) => [name, kProxyNodeBinding])); + }, + async getServices({ sharedOptions, tmpPath, durableObjectClassNames }) { + let hasDurableObjects = false; + for (const classNames of durableObjectClassNames.values()) { + if (classNames.size > 0) { + hasDurableObjects = true; + break; + } + } + if (!hasDurableObjects) + return; + const storagePath = getPersistPath( + DURABLE_OBJECTS_PLUGIN_NAME, + tmpPath, + sharedOptions.durableObjectsPersist + ); + await import_promises4.default.mkdir(storagePath, { recursive: true }); + return [ + { + // Note this service will be de-duped by name if multiple Workers create + // it. Each Worker will have the same `sharedOptions` though, so this + // isn't a problem. + name: DURABLE_OBJECTS_STORAGE_SERVICE_NAME, + disk: { path: storagePath, writable: true } + } + ]; + } +}; + +// packages/miniflare/src/plugins/core/constants.ts +var CORE_PLUGIN_NAME = "core"; +var SERVICE_ENTRY = `${CORE_PLUGIN_NAME}:entry`; +var SERVICE_USER_PREFIX = `${CORE_PLUGIN_NAME}:user`; +var SERVICE_BUILTIN_PREFIX = `${CORE_PLUGIN_NAME}:builtin`; +var SERVICE_CUSTOM_PREFIX = `${CORE_PLUGIN_NAME}:custom`; +function getUserServiceName(workerName = "") { + return `${SERVICE_USER_PREFIX}:${workerName}`; +} +var CUSTOM_SERVICE_KNOWN_OUTBOUND = "outbound"; +function getBuiltinServiceName(workerIndex, kind, bindingName) { + return `${SERVICE_BUILTIN_PREFIX}:${workerIndex}:${kind}${bindingName}`; +} +function getCustomServiceName(workerIndex, kind, bindingName) { + return `${SERVICE_CUSTOM_PREFIX}:${workerIndex}:${kind}${bindingName}`; +} + +// packages/miniflare/src/plugins/core/modules.ts +var import_assert4 = __toESM(require("assert")); +var import_fs9 = require("fs"); +var import_module = require("module"); +var import_path11 = __toESM(require("path")); +var import_url10 = require("url"); +var import_util = require("util"); +var import_acorn = require("acorn"); +var import_acorn_walk = require("acorn-walk"); +var import_zod8 = require("zod"); +var SUGGEST_BUNDLE = "If you're trying to import an npm package, you'll need to bundle your Worker first."; +var SUGGEST_NODE = "If you're trying to import a Node.js built-in module, or an npm package that uses Node.js built-ins, you'll either need to:\n- Bundle your Worker, configuring your bundler to polyfill Node.js built-ins\n- Configure your bundler to load Workers-compatible builds by changing the main fields/conditions\n- Enable the `nodejs_compat` compatibility flag and use the `NodeJsCompatModule` module type\n- Find an alternative package that doesn't require Node.js built-ins"; +var builtinModulesWithPrefix = import_module.builtinModules.concat( + import_module.builtinModules.map((module2) => `node:${module2}`) +); +function buildStringScriptPath(workerIndex) { + return `script:${workerIndex}`; +} +var stringScriptRegexp = /^script:(\d+)$/; +function maybeGetStringScriptPathIndex(scriptPath) { + const match = stringScriptRegexp.exec(scriptPath); + return match === null ? void 0 : parseInt(match[1]); +} +var ModuleRuleTypeSchema = import_zod8.z.enum([ + "ESModule", + "CommonJS", + "NodeJsCompatModule", + "Text", + "Data", + "CompiledWasm" +]); +var ModuleRuleSchema = import_zod8.z.object({ + type: ModuleRuleTypeSchema, + include: import_zod8.z.string().array(), + fallthrough: import_zod8.z.boolean().optional() +}); +var ModuleDefinitionSchema = import_zod8.z.object({ + type: ModuleRuleTypeSchema, + path: import_zod8.z.string(), + contents: import_zod8.z.string().or(import_zod8.z.instanceof(Uint8Array)).optional() +}); +var SourceOptionsSchema = import_zod8.z.union([ + import_zod8.z.object({ + // Manually defined modules + // (used by Wrangler which has its own module collection code) + modules: import_zod8.z.array(ModuleDefinitionSchema), + // `modules` "name"s will be their paths relative to this value. + // This ensures file paths in stack traces are correct. + modulesRoot: import_zod8.z.string().optional() + }), + import_zod8.z.object({ + script: import_zod8.z.string(), + // Optional script path for resolving modules, and stack traces file names + scriptPath: import_zod8.z.string().optional(), + // Automatically collect modules by parsing `script` if `true`, or treat as + // service-worker if `false` + modules: import_zod8.z.boolean().optional(), + // How to interpret automatically collected modules + modulesRules: import_zod8.z.array(ModuleRuleSchema).optional(), + // `modules` "name"s will be their paths relative to this value. + // This ensures file paths in stack traces are correct. + modulesRoot: import_zod8.z.string().optional() + }), + import_zod8.z.object({ + scriptPath: import_zod8.z.string(), + // Automatically collect modules by parsing `scriptPath` if `true`, or treat + // as service-worker if `false` + modules: import_zod8.z.boolean().optional(), + // How to interpret automatically collected modules + modulesRules: import_zod8.z.array(ModuleRuleSchema).optional(), + // `modules` "name"s will be their paths relative to this value. + // This ensures file paths in stack traces are correct. + modulesRoot: import_zod8.z.string().optional() + }) +]); +var DEFAULT_MODULE_RULES = [ + { type: "ESModule", include: ["**/*.mjs"] }, + { type: "CommonJS", include: ["**/*.js", "**/*.cjs"] } +]; +function compileModuleRules(rules) { + const compiledRules = []; + const finalisedTypes = /* @__PURE__ */ new Set(); + for (const rule of [...rules ?? [], ...DEFAULT_MODULE_RULES]) { + if (finalisedTypes.has(rule.type)) + continue; + compiledRules.push({ + type: rule.type, + include: globsToRegExps(rule.include) + }); + if (!rule.fallthrough) + finalisedTypes.add(rule.type); + } + return compiledRules; +} +function moduleName(modulesRoot, modulePath) { + const name = import_path11.default.relative(modulesRoot, modulePath); + return import_path11.default.sep === "\\" ? name.replaceAll("\\", "/") : name; +} +function withSourceURL(script, scriptPath) { + let scriptURL = scriptPath; + if (maybeGetStringScriptPathIndex(scriptPath) === void 0) { + scriptURL = (0, import_url10.pathToFileURL)(scriptPath); + } + const sourceURL = ` +//# sourceURL=${scriptURL} +`; + return script + sourceURL; +} +function getResolveErrorPrefix(referencingPath) { + const relative = import_path11.default.relative("", referencingPath); + return `Unable to resolve "${relative}" dependency`; +} +var ModuleLocator = class { + constructor(modulesRoot, additionalModuleNames, rules, compatibilityFlags) { + this.modulesRoot = modulesRoot; + this.additionalModuleNames = additionalModuleNames; + this.#compiledRules = compileModuleRules(rules); + this.#nodejsCompat = compatibilityFlags?.includes("nodejs_compat") ?? false; + } + #compiledRules; + #nodejsCompat; + #visitedPaths = /* @__PURE__ */ new Set(); + modules = []; + visitEntrypoint(code, modulePath) { + modulePath = import_path11.default.resolve(this.modulesRoot, modulePath); + if (this.#visitedPaths.has(modulePath)) + return; + this.#visitedPaths.add(modulePath); + this.#visitJavaScriptModule(code, modulePath, "ESModule"); + } + #visitJavaScriptModule(code, modulePath, type) { + const name = moduleName(this.modulesRoot, modulePath); + const module2 = createJavaScriptModule(code, name, modulePath, type); + this.modules.push(module2); + const isESM = type === "ESModule"; + let root; + try { + root = (0, import_acorn.parse)(code, { + ecmaVersion: "latest", + sourceType: isESM ? "module" : "script", + locations: true + }); + } catch (e) { + let loc = ""; + if (e.loc?.line !== void 0) { + loc += `:${e.loc.line}`; + if (e.loc.column !== void 0) + loc += `:${e.loc.column}`; + } + throw new MiniflareCoreError( + "ERR_MODULE_PARSE", + `Unable to parse "${name}": ${e.message ?? e} + at ${modulePath}${loc}` + ); + } + const visitors = { + ImportDeclaration: (node) => { + this.#visitModule(modulePath, name, type, node.source); + }, + ExportNamedDeclaration: (node) => { + if (node.source != null) { + this.#visitModule(modulePath, name, type, node.source); + } + }, + ExportAllDeclaration: (node) => { + this.#visitModule(modulePath, name, type, node.source); + }, + ImportExpression: (node) => { + this.#visitModule(modulePath, name, type, node.source); + }, + CallExpression: isESM ? void 0 : (node) => { + const argument = node.arguments[0]; + if (node.callee.type === "Identifier" && node.callee.name === "require" && argument !== void 0) { + this.#visitModule(modulePath, name, type, argument); + } + } + }; + (0, import_acorn_walk.simple)(root, visitors); + } + #visitModule(referencingPath, referencingName, referencingType, specExpression) { + if (maybeGetStringScriptPathIndex(referencingName) !== void 0) { + const prefix = getResolveErrorPrefix(referencingPath); + throw new MiniflareCoreError( + "ERR_MODULE_STRING_SCRIPT", + `${prefix}: imports are unsupported in string \`script\` without defined \`scriptPath\`` + ); + } + if (specExpression.type !== "Literal" || typeof specExpression.value !== "string") { + const modules = this.modules.map((mod) => { + const def = convertWorkerModule(mod); + return ` { type: "${def.type}", path: "${def.path}" }`; + }); + const modulesConfig = ` new Miniflare({ + ..., + modules: [ +${modules.join(",\n")}, + ... + ] + })`; + const prefix = getResolveErrorPrefix(referencingPath); + let message = `${prefix}: dynamic module specifiers are unsupported. +You must manually define your modules when constructing Miniflare: +${dim(modulesConfig)}`; + if (specExpression.loc != null) { + const { line, column } = specExpression.loc.start; + message += ` + at ${referencingPath}:${line}:${column}`; + } + throw new MiniflareCoreError("ERR_MODULE_DYNAMIC_SPEC", message); + } + const spec = specExpression.value; + const isNodeJsCompatModule = referencingType === "NodeJsCompatModule"; + if (this.#nodejsCompat && spec.startsWith("node:") || spec.startsWith("cloudflare:") || spec.startsWith("workerd:") || isNodeJsCompatModule && builtinModulesWithPrefix.includes(spec) || this.additionalModuleNames.includes(spec)) { + return; + } + const identifier = import_path11.default.resolve(import_path11.default.dirname(referencingPath), spec); + const name = moduleName(this.modulesRoot, identifier); + if (this.#visitedPaths.has(identifier)) + return; + this.#visitedPaths.add(identifier); + const rule = this.#compiledRules.find( + (rule2) => testRegExps(rule2.include, identifier) + ); + if (rule === void 0) { + const prefix = getResolveErrorPrefix(referencingPath); + const isBuiltin = builtinModulesWithPrefix.includes(spec); + const suggestion = isBuiltin ? SUGGEST_NODE : SUGGEST_BUNDLE; + throw new MiniflareCoreError( + "ERR_MODULE_RULE", + `${prefix} "${spec}": no matching module rules. +${suggestion}` + ); + } + const data = (0, import_fs9.readFileSync)(identifier); + switch (rule.type) { + case "ESModule": + case "CommonJS": + case "NodeJsCompatModule": + const code = data.toString("utf8"); + this.#visitJavaScriptModule(code, identifier, rule.type); + break; + case "Text": + this.modules.push({ name, text: data.toString("utf8") }); + break; + case "Data": + this.modules.push({ name, data }); + break; + case "CompiledWasm": + this.modules.push({ name, wasm: data }); + break; + default: + const exhaustive = rule.type; + import_assert4.default.fail(`Unreachable: ${exhaustive} modules are unsupported`); + } + } +}; +function createJavaScriptModule(code, name, modulePath, type) { + code = withSourceURL(code, modulePath); + if (type === "ESModule") { + return { name, esModule: code }; + } else if (type === "CommonJS") { + return { name, commonJsModule: code }; + } else if (type === "NodeJsCompatModule") { + return { name, nodeJsCompatModule: code }; + } + const exhaustive = type; + import_assert4.default.fail(`Unreachable: ${exhaustive} JavaScript modules are unsupported`); +} +var encoder = new import_util.TextEncoder(); +var decoder = new import_util.TextDecoder(); +function contentsToString(contents13) { + return typeof contents13 === "string" ? contents13 : decoder.decode(contents13); +} +function contentsToArray(contents13) { + return typeof contents13 === "string" ? encoder.encode(contents13) : contents13; +} +function convertModuleDefinition(modulesRoot, def) { + const name = moduleName(modulesRoot, def.path); + const contents13 = def.contents ?? (0, import_fs9.readFileSync)(def.path); + switch (def.type) { + case "ESModule": + case "CommonJS": + case "NodeJsCompatModule": + return createJavaScriptModule( + contentsToString(contents13), + name, + import_path11.default.resolve(modulesRoot, def.path), + def.type + ); + case "Text": + return { name, text: contentsToString(contents13) }; + case "Data": + return { name, data: contentsToArray(contents13) }; + case "CompiledWasm": + return { name, wasm: contentsToArray(contents13) }; + default: + const exhaustive = def.type; + import_assert4.default.fail(`Unreachable: ${exhaustive} modules are unsupported`); + } +} +function convertWorkerModule(mod) { + const path21 = mod.name; + (0, import_assert4.default)(path21 !== void 0); + const m = mod; + if ("esModule" in m) + return { path: path21, type: "ESModule" }; + else if ("commonJsModule" in m) + return { path: path21, type: "CommonJS" }; + else if ("nodeJsCompatModule" in m) + return { path: path21, type: "NodeJsCompatModule" }; + else if ("text" in m) + return { path: path21, type: "Text" }; + else if ("data" in m) + return { path: path21, type: "Data" }; + else if ("wasm" in m) + return { path: path21, type: "CompiledWasm" }; + (0, import_assert4.default)(!("json" in m), "Unreachable: json modules aren't generated"); + const exhaustive = m; + import_assert4.default.fail( + `Unreachable: [${Object.keys(exhaustive).join( + ", " + )}] modules are unsupported` + ); +} + +// packages/miniflare/src/plugins/core/services.ts +var import_zod9 = require("zod"); +var HttpOptionsHeaderSchema = import_zod9.z.object({ + name: import_zod9.z.string(), + // name should be required + value: import_zod9.z.ostring() + // If omitted, the header will be removed +}); +var HttpOptionsSchema = import_zod9.z.object({ + style: import_zod9.z.nativeEnum(import_workerd_capnp.HttpOptions_Style).optional(), + forwardedProtoHeader: import_zod9.z.ostring(), + cfBlobHeader: import_zod9.z.ostring(), + injectRequestHeaders: HttpOptionsHeaderSchema.array().optional(), + injectResponseHeaders: HttpOptionsHeaderSchema.array().optional() +}); +var TlsOptionsKeypairSchema = import_zod9.z.object({ + privateKey: import_zod9.z.ostring(), + certificateChain: import_zod9.z.ostring() +}); +var TlsOptionsSchema = import_zod9.z.object({ + keypair: TlsOptionsKeypairSchema.optional(), + requireClientCerts: import_zod9.z.oboolean(), + trustBrowserCas: import_zod9.z.oboolean(), + trustedCertificates: import_zod9.z.string().array().optional(), + minVersion: import_zod9.z.nativeEnum(import_workerd_capnp.TlsOptions_Version).optional(), + cipherList: import_zod9.z.ostring() +}); +var NetworkSchema = import_zod9.z.object({ + allow: import_zod9.z.string().array().optional(), + deny: import_zod9.z.string().array().optional(), + tlsOptions: TlsOptionsSchema.optional() +}); +var ExternalServerSchema = import_zod9.z.intersection( + import_zod9.z.object({ address: import_zod9.z.string() }), + // address should be required + import_zod9.z.union([ + import_zod9.z.object({ http: import_zod9.z.optional(HttpOptionsSchema) }), + import_zod9.z.object({ + https: import_zod9.z.optional( + import_zod9.z.object({ + options: HttpOptionsSchema.optional(), + tlsOptions: TlsOptionsSchema.optional(), + certificateHost: import_zod9.z.ostring() + }) + ) + }) + ]) +); +var DiskDirectorySchema = import_zod9.z.object({ + path: import_zod9.z.string(), + // path should be required + writable: import_zod9.z.oboolean() +}); +var ServiceFetchSchema = import_zod9.z.function().args(import_zod9.z.instanceof(Request)).returns(zAwaitable(import_zod9.z.instanceof(Response))); +var ServiceDesignatorSchema = import_zod9.z.union([ + import_zod9.z.string(), + import_zod9.z.object({ network: NetworkSchema }), + import_zod9.z.object({ external: ExternalServerSchema }), + import_zod9.z.object({ disk: DiskDirectorySchema }), + ServiceFetchSchema +]); + +// packages/miniflare/src/plugins/core/errors/index.ts +var import_fs10 = __toESM(require("fs")); +var import_path12 = __toESM(require("path")); +var import_url11 = require("url"); +var import_zod10 = require("zod"); + +// packages/miniflare/src/plugins/core/errors/sourcemap.ts +var import_assert5 = __toESM(require("assert")); + +// packages/miniflare/src/plugins/core/errors/callsite.ts +function parseStack(stack) { + return stack.split("\n").slice(1).map(parseCallSite).filter((site) => site !== void 0); +} +function parseCallSite(line) { + const lineMatch = line.match( + /at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/ + ); + if (!lineMatch) { + return; + } + let object = null; + let method = null; + let functionName = null; + let typeName = null; + let methodName = null; + const isNative = lineMatch[5] === "native"; + if (lineMatch[1]) { + functionName = lineMatch[1]; + let methodStart = functionName.lastIndexOf("."); + if (functionName[methodStart - 1] == ".") + methodStart--; + if (methodStart > 0) { + object = functionName.substring(0, methodStart); + method = functionName.substring(methodStart + 1); + const objectEnd = object.indexOf(".Module"); + if (objectEnd > 0) { + functionName = functionName.substring(objectEnd + 1); + object = object.substring(0, objectEnd); + } + } + } + if (method) { + typeName = object; + methodName = method; + } + if (method === "") { + methodName = null; + functionName = null; + } + return new CallSite({ + typeName, + functionName, + methodName, + fileName: lineMatch[2] || null, + lineNumber: parseInt(lineMatch[3]) || null, + columnNumber: parseInt(lineMatch[4]) || null, + native: isNative + }); +} +var CallSite = class { + constructor(opts) { + this.opts = opts; + } + getThis() { + return null; + } + getTypeName() { + return this.opts.typeName; + } + // eslint-disable-next-line @typescript-eslint/ban-types + getFunction() { + return void 0; + } + getFunctionName() { + return this.opts.functionName; + } + getMethodName() { + return this.opts.methodName; + } + getFileName() { + return this.opts.fileName; + } + getScriptNameOrSourceURL() { + return this.opts.fileName; + } + getLineNumber() { + return this.opts.lineNumber; + } + getColumnNumber() { + return this.opts.columnNumber; + } + getEvalOrigin() { + return void 0; + } + isToplevel() { + return false; + } + isEval() { + return false; + } + isNative() { + return this.opts.native; + } + isConstructor() { + return false; + } + isAsync() { + return false; + } + isPromiseAll() { + return false; + } + isPromiseAny() { + return false; + } + getPromiseIndex() { + return null; + } +}; + +// packages/miniflare/src/plugins/core/errors/sourcemap.ts +var sourceMapInstallBaseOptions = { + environment: "node", + // Don't add Node `uncaughtException` handler + handleUncaughtExceptions: false, + // Don't hook Node `require` function + hookRequire: false, + // Make sure we're using fresh copies of files (i.e. between `setOptions()`) + emptyCacheBetweenOperations: true, + // Always remove existing retrievers when calling `install()`, we should be + // specifying them each time we want to source map + overrideRetrieveFile: true, + overrideRetrieveSourceMap: true +}; +var sourceMapper; +function getSourceMapper() { + if (sourceMapper !== void 0) + return sourceMapper; + const originalSupport = require.cache["source-map-support"]; + delete require.cache["source-map-support"]; + const support = require("source-map-support"); + require.cache["source-map-support"] = originalSupport; + const originalPrepareStackTrace = Error.prepareStackTrace; + support.install(sourceMapInstallBaseOptions); + const prepareStackTrace = Error.prepareStackTrace; + (0, import_assert5.default)(prepareStackTrace !== void 0); + Error.prepareStackTrace = originalPrepareStackTrace; + sourceMapper = (retrieveSourceMap, error) => { + support.install({ + ...sourceMapInstallBaseOptions, + retrieveFile(file) { + import_assert5.default.fail(`Unexpected retrieveFile(${JSON.stringify(file)}) call`); + }, + retrieveSourceMap + }); + const callSites = parseStack(error.stack ?? ""); + return prepareStackTrace(error, callSites); + }; + return sourceMapper; +} + +// packages/miniflare/src/plugins/core/errors/index.ts +function maybeGetDiskFile(filePath) { + try { + const contents13 = import_fs10.default.readFileSync(filePath, "utf8"); + return { path: filePath, contents: contents13 }; + } catch (e) { + if (e.code !== "ENOENT") + throw e; + } +} +function maybeGetFile(workerSrcOpts, fileSpecifier) { + const maybeUrl = maybeParseURL(fileSpecifier); + if (maybeUrl !== void 0 && maybeUrl.protocol === "file:") { + const filePath = (0, import_url11.fileURLToPath)(maybeUrl); + for (const srcOpts of workerSrcOpts) { + if (Array.isArray(srcOpts.modules)) { + const modulesRoot = srcOpts.modulesRoot ?? ""; + for (const module2 of srcOpts.modules) { + if (module2.contents !== void 0 && import_path12.default.resolve(modulesRoot, module2.path) === filePath) { + const contents13 = contentsToString(module2.contents); + return { path: filePath, contents: contents13 }; + } + } + } else if ("script" in srcOpts && "scriptPath" in srcOpts && srcOpts.script !== void 0 && srcOpts.scriptPath !== void 0) { + const modulesRoot = srcOpts.modules && srcOpts.modulesRoot || ""; + if (import_path12.default.resolve(modulesRoot, srcOpts.scriptPath) === filePath) { + return { path: filePath, contents: srcOpts.script }; + } + } + } + return maybeGetDiskFile(filePath); + } + const workerIndex = maybeGetStringScriptPathIndex(fileSpecifier); + if (workerIndex !== void 0) { + const srcOpts = workerSrcOpts[workerIndex]; + if ("script" in srcOpts && srcOpts.script !== void 0) { + return { contents: srcOpts.script }; + } + } +} +function getSourceMappedStack(workerSrcOpts, error) { + function retrieveSourceMap(fileSpecifier) { + const sourceFile = maybeGetFile(workerSrcOpts, fileSpecifier); + if (sourceFile?.path === void 0) + return null; + const sourceMapRegexp = /# sourceMappingURL=(.+)/g; + const matches = [...sourceFile.contents.matchAll(sourceMapRegexp)]; + if (matches.length === 0) + return null; + const sourceMapMatch = matches[matches.length - 1]; + const root = import_path12.default.dirname(sourceFile.path); + const sourceMapPath = import_path12.default.resolve(root, sourceMapMatch[1]); + const sourceMapFile = maybeGetDiskFile(sourceMapPath); + if (sourceMapFile === void 0) + return null; + return { map: sourceMapFile.contents, url: sourceMapFile.path }; + } + return getSourceMapper()(retrieveSourceMap, error); +} +var JsonErrorSchema = import_zod10.z.lazy( + () => import_zod10.z.object({ + message: import_zod10.z.string().optional(), + name: import_zod10.z.string().optional(), + stack: import_zod10.z.string().optional(), + cause: JsonErrorSchema.optional() + }) +); +var ALLOWED_ERROR_SUBCLASS_CONSTRUCTORS = [ + EvalError, + RangeError, + ReferenceError, + SyntaxError, + TypeError, + URIError +]; +function reviveError(workerSrcOpts, jsonError) { + let cause; + if (jsonError.cause !== void 0) { + cause = reviveError(workerSrcOpts, jsonError.cause); + } + let ctor = Error; + if (jsonError.name !== void 0 && jsonError.name in globalThis) { + const maybeCtor = globalThis[jsonError.name]; + if (ALLOWED_ERROR_SUBCLASS_CONSTRUCTORS.includes(maybeCtor)) { + ctor = maybeCtor; + } + } + const error = new ctor(jsonError.message, { cause }); + if (jsonError.name !== void 0) + error.name = jsonError.name; + error.stack = jsonError.stack; + error.stack = getSourceMappedStack(workerSrcOpts, error); + return error; +} +async function handlePrettyErrorRequest(log, workerSrcOpts, request) { + const caught = JsonErrorSchema.parse(await request.json()); + const error = reviveError(workerSrcOpts, caught); + log.error(error); + const accept = request.headers.get("Accept")?.toLowerCase() ?? ""; + const userAgent = request.headers.get("User-Agent")?.toLowerCase() ?? ""; + const acceptsPrettyError = !userAgent.includes("curl/") && (accept.includes("text/html") || accept.includes("*/*") || accept.includes("text/*")); + if (!acceptsPrettyError) { + return new Response(error.stack, { status: 500 }); + } + const Youch = require("youch"); + const youch = new Youch(error.cause ?? error, { + url: request.url, + method: request.method, + headers: Object.fromEntries(request.headers) + }); + youch.addLink(() => { + return [ + '\u{1F4DA} Workers Docs', + '\u{1F4AC} Workers Discord' + ].join(""); + }); + return new Response(await youch.toHTML(), { + status: 500, + headers: { "Content-Type": "text/html;charset=utf-8" } + }); +} + +// packages/miniflare/src/plugins/core/proxy/client.ts +var import_assert7 = __toESM(require("assert")); +var import_web4 = require("stream/web"); +var import_util2 = __toESM(require("util")); +var import_undici6 = require("undici"); + +// packages/miniflare/src/plugins/core/proxy/fetch-sync.ts +var import_assert6 = __toESM(require("assert")); +var import_web2 = require("stream/web"); +var import_worker_threads = require("worker_threads"); +var DECODER = new TextDecoder(); +var WORKER_SCRIPT = ( + /* javascript */ + ` +const { createRequire } = require("module"); +const { workerData } = require("worker_threads"); + +// Not using parentPort here so we can call receiveMessageOnPort() in host +const { notifyHandle, port, filename } = workerData; + +// When running Miniflare from Jest, regular 'require("undici")' will fail here +// with "Error: Cannot find module 'undici'". Instead we need to create a +// 'require' using the '__filename' of the host... :( +const actualRequire = createRequire(filename); +const { Client, fetch } = actualRequire("undici"); + +let clientUrl; +let client; + +port.addEventListener("message", async (event) => { + const { id, method, url, headers, body } = event.data; + if (clientUrl !== url) { + clientUrl = url; + client = new Client(url, { + connect: { rejectUnauthorized: false }, + }); + } + headers["${CoreHeaders.OP_SYNC}"] = "true"; + try { + // body cannot be a ReadableStream, so no need to specify duplex + const response = await fetch(url, { method, headers, body, dispatcher: client }); + const responseBody = response.headers.get("${CoreHeaders.OP_RESULT_TYPE}") === "ReadableStream" + ? response.body + : await response.arrayBuffer(); + const transferList = responseBody === null ? undefined : [responseBody]; + port.postMessage( + { + id, + response: { + status: response.status, + headers: Object.fromEntries(response.headers), + body: responseBody, + } + }, + transferList + ); + } catch (error) { + try { + port.postMessage({ id, error }); + } catch { + // If error failed to serialise, post simplified version + port.postMessage({ id, error: new Error(String(error)) }); + } + } + Atomics.store(notifyHandle, /* index */ 0, /* value */ 1); + Atomics.notify(notifyHandle, /* index */ 0); +}); +` +); +var SynchronousFetcher = class { + #channel; + #notifyHandle; + #worker; + #nextId = 0; + constructor() { + this.#channel = new import_worker_threads.MessageChannel(); + this.#notifyHandle = new Int32Array(new SharedArrayBuffer(4)); + } + #ensureWorker() { + if (this.#worker !== void 0) + return; + this.#worker = new import_worker_threads.Worker(WORKER_SCRIPT, { + eval: true, + workerData: { + notifyHandle: this.#notifyHandle, + port: this.#channel.port2, + filename: __filename + }, + transferList: [this.#channel.port2] + }); + } + fetch(url13, init2) { + this.#ensureWorker(); + Atomics.store( + this.#notifyHandle, + /* index */ + 0, + /* value */ + 0 + ); + const id = this.#nextId++; + this.#channel.port1.postMessage({ + id, + method: init2.method, + url: url13.toString(), + headers: init2.headers, + body: init2.body + }); + Atomics.wait( + this.#notifyHandle, + /* index */ + 0, + /* value */ + 0 + ); + const message = (0, import_worker_threads.receiveMessageOnPort)( + this.#channel.port1 + )?.message; + (0, import_assert6.default)(message?.id === id); + if ("response" in message) { + const { status, headers: rawHeaders, body } = message.response; + const headers = new import_undici8.Headers(rawHeaders); + const stack = headers.get(CoreHeaders.ERROR_STACK); + if (status === 500 && stack !== null && body !== null) { + (0, import_assert6.default)(!(body instanceof import_web2.ReadableStream)); + const caught = JsonErrorSchema.parse(JSON.parse(DECODER.decode(body))); + throw reviveError([], caught); + } + return { status, headers, body }; + } else { + throw message.error; + } + } + async dispose() { + await this.#worker?.terminate(); + } +}; + +// packages/miniflare/src/plugins/core/proxy/types.ts +var import_buffer = require("buffer"); +var import_consumers = require("stream/consumers"); +var import_web3 = require("stream/web"); +var import_undici5 = require("undici"); +var NODE_PLATFORM_IMPL = { + // Node's implementation of these classes don't quite match Workers', + // but they're close enough for us + Blob: import_buffer.Blob, + File: import_undici5.File, + Headers: import_undici5.Headers, + Request, + Response, + isReadableStream(value) { + return value instanceof import_web3.ReadableStream; + }, + bufferReadableStream(stream) { + return (0, import_consumers.arrayBuffer)(stream); + }, + unbufferReadableStream(buffer) { + return new import_buffer.Blob([new Uint8Array(buffer)]).stream(); + } +}; + +// packages/miniflare/src/plugins/core/proxy/client.ts +var kAddress = Symbol("kAddress"); +var kName = Symbol("kName"); +function isNativeTarget(value) { + return typeof value === "object" && value !== null && kAddress in value; +} +var TARGET_GLOBAL = { + [kAddress]: ProxyAddresses.GLOBAL, + [kName]: "global" +}; +var TARGET_ENV = { + [kAddress]: ProxyAddresses.ENV, + [kName]: "env" +}; +var reducers = { + ...structuredSerializableReducers, + ...createHTTPReducers(NODE_PLATFORM_IMPL), + Native(value) { + if (isNativeTarget(value)) + return [value[kAddress], value[kName]]; + } +}; +var revivers = { + ...structuredSerializableRevivers, + ...createHTTPRevivers(NODE_PLATFORM_IMPL) + // `Native` reviver depends on `ProxyStubHandler` methods +}; +var ProxyClient = class { + #bridge; + constructor(runtimeEntryURL, dispatchFetch) { + this.#bridge = new ProxyClientBridge(runtimeEntryURL, dispatchFetch); + } + // Lazily initialise proxies as required + #globalProxy; + #envProxy; + get global() { + return this.#globalProxy ??= this.#bridge.getProxy(TARGET_GLOBAL); + } + get env() { + return this.#envProxy ??= this.#bridge.getProxy(TARGET_ENV); + } + poisonProxies(runtimeEntryURL) { + this.#bridge.poisonProxies(runtimeEntryURL); + this.#globalProxy = void 0; + this.#envProxy = void 0; + } + dispose() { + return this.#bridge.dispose(); + } +}; +var ProxyClientBridge = class { + constructor(url13, dispatchFetch) { + this.url = url13; + this.dispatchFetch = dispatchFetch; + this.#finalizationRegistry = new FinalizationRegistry(this.#finalizeProxy); + } + // Each proxy stub is initialised with the version stored here. Whenever + // `poisonProxies()` is called, this version is incremented. Before the + // proxy makes any request to `workerd`, it checks the version number here + // matches its own internal version, and throws if not. + #version = 0; + // Whenever the `ProxyServer` returns a native target, it adds a strong + // reference to the "heap" in the singleton object. This prevents the object + // being garbage collected. To solve this, we register the native target + // proxies on the client in a `FinalizationRegistry`. When the proxies get + // garbage collected, we let the `ProxyServer` know it can release the strong + // "heap" reference, as we'll never be able to access it again. Importantly, + // we need to unregister all proxies from the registry when we poison them, + // as the references will be invalid, and a new object with the same address + // may be added to the "heap". + #finalizationRegistry; + sync = new SynchronousFetcher(); + get version() { + return this.#version; + } + #finalizeProxy = async (held) => { + if (held.version !== this.#version) + return; + try { + await this.dispatchFetch(this.url, { + method: "DELETE", + headers: { + [CoreHeaders.OP]: ProxyOps.FREE, + [CoreHeaders.OP_TARGET]: held.address.toString() + } + }); + } catch { + } + }; + getProxy(target) { + const handler = new ProxyStubHandler(this, target); + const proxy = new Proxy( + { [import_util2.default.inspect.custom]: handler.inspect }, + handler + ); + const held = { + address: target[kAddress], + version: this.#version + }; + this.#finalizationRegistry.register(proxy, held, this); + return proxy; + } + poisonProxies(url13) { + this.#version++; + if (url13 !== void 0) + this.url = url13; + this.#finalizationRegistry.unregister(this); + } + dispose() { + this.poisonProxies(); + return this.sync.dispose(); + } +}; +var ProxyStubHandler = class { + constructor(bridge, target) { + this.bridge = bridge; + this.target = target; + this.#version = bridge.version; + this.#stringifiedTarget = stringify(this.target, reducers); + } + #version; + #stringifiedTarget; + #known = /* @__PURE__ */ new Map(); + revivers = { + ...revivers, + Native: (value) => { + (0, import_assert7.default)(Array.isArray(value)); + const [address, name] = value; + (0, import_assert7.default)(typeof address === "number"); + (0, import_assert7.default)(typeof name === "string"); + const target = { [kAddress]: address, [kName]: name }; + if (name === "Promise") { + const resPromise = this.bridge.dispatchFetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP]: ProxyOps.GET, + // GET without key just gets target + [CoreHeaders.OP_TARGET]: stringify(target, reducers) + } + }); + return this.#parseAsyncResponse(resPromise); + } else { + return this.bridge.getProxy(target); + } + } + }; + get #poisoned() { + return this.#version !== this.bridge.version; + } + #assertSafe() { + if (this.#poisoned) { + throw new Error( + "Attempted to use poisoned stub. Stubs to runtime objects must be re-created after calling `Miniflare#setOptions()` or `Miniflare#dispose()`." + ); + } + } + inspect = (depth, options) => { + const details = { name: this.target[kName], poisoned: this.#poisoned }; + return `ProxyStub ${import_util2.default.inspect(details, options)}`; + }; + #maybeThrow(res, result, caller) { + if (res.status === 500) { + if (typeof result === "object" && result !== null) { + Error.captureStackTrace(result, caller); + } + throw result; + } else { + (0, import_assert7.default)(res.status === 200); + return result; + } + } + async #parseAsyncResponse(resPromise) { + const res = await resPromise; + const typeHeader = res.headers.get(CoreHeaders.OP_RESULT_TYPE); + if (typeHeader === "Promise, ReadableStream") + return res.body; + (0, import_assert7.default)(typeHeader === "Promise"); + let stringifiedResult; + let unbufferedStream; + const stringifiedSizeHeader = res.headers.get( + CoreHeaders.OP_STRINGIFIED_SIZE + ); + if (stringifiedSizeHeader === null) { + stringifiedResult = await res.text(); + } else { + const stringifiedSize = parseInt(stringifiedSizeHeader); + (0, import_assert7.default)(!Number.isNaN(stringifiedSize)); + (0, import_assert7.default)(res.body !== null); + const [buffer, rest] = await readPrefix(res.body, stringifiedSize); + stringifiedResult = buffer.toString(); + unbufferedStream = rest.pipeThrough(new import_web4.TransformStream()); + } + const result = parseWithReadableStreams( + NODE_PLATFORM_IMPL, + { value: stringifiedResult, unbufferedStream }, + this.revivers + ); + return this.#maybeThrow(res, result, this.#parseAsyncResponse); + } + #parseSyncResponse(syncRes, caller) { + (0, import_assert7.default)(syncRes.body !== null); + (0, import_assert7.default)(syncRes.headers.get(CoreHeaders.OP_STRINGIFIED_SIZE) === null); + if (syncRes.body instanceof import_web4.ReadableStream) + return syncRes.body; + const stringifiedResult = DECODER.decode(syncRes.body); + const result = parseWithReadableStreams( + NODE_PLATFORM_IMPL, + { value: stringifiedResult }, + this.revivers + ); + return this.#maybeThrow(syncRes, result, caller); + } + get(_target, key, _receiver) { + this.#assertSafe(); + if (key === kAddress) + return this.target[kAddress]; + if (key === kName) + return this.target[kName]; + if (typeof key === "symbol" || key === "then") + return void 0; + const maybeKnown = this.#known.get(key); + if (maybeKnown !== void 0) + return maybeKnown; + const syncRes = this.bridge.sync.fetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP]: ProxyOps.GET, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget, + [CoreHeaders.OP_KEY]: key + } + }); + let result; + if (syncRes.headers.get(CoreHeaders.OP_RESULT_TYPE) === "Function") { + result = this.#createFunction(key); + } else { + result = this.#parseSyncResponse(syncRes, this.get); + } + if ( + // Optimisation: if this property is a function, we assume constant + // prototypes of proxied objects, so it's never going to change + typeof result === "function" || // Optimisation: if this property is a reference, we assume it's never + // going to change. This allows us to reuse the known cache of nested + // objects on multiple access (e.g. reusing `env["..."]` proxy if + // `getR2Bucket()` is called on the same bucket multiple times). + isNativeTarget(result) || // Once a `ReadableStream` sent across proxy, we won't be able to read it + // again in the server, so reuse the same stream for future accesses + // (e.g. accessing `R2ObjectBody#body` multiple times) + result instanceof import_web4.ReadableStream + ) { + this.#known.set(key, result); + } + return result; + } + has(target, key) { + return this.get(target, key, void 0) !== void 0; + } + #createFunction(key) { + let knownAsync = false; + const func = { + [key]: (...args) => { + const result = this.#call(key, knownAsync, args, func); + if (!knownAsync && result instanceof Promise) + knownAsync = true; + return result; + } + }[key]; + return func; + } + #call(key, knownAsync, args, caller) { + this.#assertSafe(); + const targetName = this.target[kName]; + if (isFetcherFetch(targetName, key)) + return this.#fetcherFetchCall(args); + const stringified = stringifyWithStreams( + NODE_PLATFORM_IMPL, + args, + reducers, + /* allowUnbufferedStream */ + true + ); + if (knownAsync || // We assume every call with `ReadableStream`/`Blob` arguments is async. + // Note that you can't consume `ReadableStream`/`Blob` synchronously: if + // you tried a similar trick to `SynchronousFetcher`, blocking the main + // thread with `Atomics.wait()` would prevent chunks being read. This + // assumption doesn't hold for `Blob`s and `FormData#{append,set}()`, but + // we should never expose proxies for those APIs to users. + stringified instanceof Promise || // (instanceof Promise if buffered `ReadableStream`/`Blob`s) + stringified.unbufferedStream !== void 0) { + return this.#asyncCall(key, stringified); + } else { + const result = this.#syncCall(key, stringified.value, caller); + if (isR2ObjectWriteHttpMetadata(targetName, key)) { + const arg = args[0]; + (0, import_assert7.default)(arg instanceof import_undici6.Headers); + (0, import_assert7.default)(result instanceof import_undici6.Headers); + for (const [key2, value] of result) + arg.set(key2, value); + return; + } + return result; + } + } + #syncCall(key, stringifiedValue, caller) { + const argsSize = Buffer.byteLength(stringifiedValue).toString(); + const syncRes = this.bridge.sync.fetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP]: ProxyOps.CALL, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget, + [CoreHeaders.OP_KEY]: key, + [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize, + "Content-Length": argsSize + }, + body: stringifiedValue + }); + return this.#parseSyncResponse(syncRes, caller); + } + async #asyncCall(key, stringifiedAwaitable) { + const stringified = await stringifiedAwaitable; + let resPromise; + if (stringified.unbufferedStream === void 0) { + const argsSize = Buffer.byteLength(stringified.value).toString(); + resPromise = this.bridge.dispatchFetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP]: ProxyOps.CALL, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget, + [CoreHeaders.OP_KEY]: key, + [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize, + "Content-Length": argsSize + }, + body: stringified.value + }); + } else { + const encodedArgs = Buffer.from(stringified.value); + const argsSize = encodedArgs.byteLength.toString(); + const body = prefixStream(encodedArgs, stringified.unbufferedStream); + resPromise = this.bridge.dispatchFetch(this.bridge.url, { + method: "POST", + headers: { + [CoreHeaders.OP]: ProxyOps.CALL, + [CoreHeaders.OP_TARGET]: this.#stringifiedTarget, + [CoreHeaders.OP_KEY]: key, + [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize + }, + duplex: "half", + body + }); + } + return this.#parseAsyncResponse(resPromise); + } + #fetcherFetchCall(args) { + const request = new Request(...args); + request.headers.set(CoreHeaders.OP, ProxyOps.CALL); + request.headers.set(CoreHeaders.OP_TARGET, this.#stringifiedTarget); + request.headers.set(CoreHeaders.OP_KEY, "fetch"); + return this.bridge.dispatchFetch(request); + } +}; + +// packages/miniflare/src/plugins/core/index.ts +var trustedCertificates = process.platform === "win32" ? Array.from(import_tls.default.rootCertificates) : []; +if (process.env.NODE_EXTRA_CA_CERTS !== void 0) { + try { + const extra = (0, import_fs11.readFileSync)(process.env.NODE_EXTRA_CA_CERTS, "utf8"); + const pemBegin = "-----BEGIN"; + for (const cert of extra.split(pemBegin)) { + if (cert.trim() !== "") + trustedCertificates.push(pemBegin + cert); + } + } catch { + } +} +var encoder2 = new import_util3.TextEncoder(); +var numericCompare = new Intl.Collator(void 0, { numeric: true }).compare; +function createFetchMock() { + return new import_undici7.MockAgent(); +} +var CoreOptionsSchemaInput = import_zod11.z.intersection( + SourceOptionsSchema, + import_zod11.z.object({ + name: import_zod11.z.string().optional(), + compatibilityDate: import_zod11.z.string().optional(), + compatibilityFlags: import_zod11.z.string().array().optional(), + routes: import_zod11.z.string().array().optional(), + bindings: import_zod11.z.record(JsonSchema).optional(), + wasmBindings: import_zod11.z.record(import_zod11.z.string()).optional(), + textBlobBindings: import_zod11.z.record(import_zod11.z.string()).optional(), + dataBlobBindings: import_zod11.z.record(import_zod11.z.string()).optional(), + serviceBindings: import_zod11.z.record(ServiceDesignatorSchema).optional(), + outboundService: ServiceDesignatorSchema.optional(), + fetchMock: import_zod11.z.instanceof(import_undici7.MockAgent).optional(), + unsafeEphemeralDurableObjects: import_zod11.z.boolean().optional() + }) +); +var CoreOptionsSchema = CoreOptionsSchemaInput.transform((value) => { + const fetchMock = value.fetchMock; + if (fetchMock !== void 0) { + if (value.outboundService !== void 0) { + throw new MiniflareCoreError( + "ERR_MULTIPLE_OUTBOUNDS", + "Only one of `outboundService` or `fetchMock` may be specified per worker" + ); + } + value.outboundService = (req) => fetch2(req, { dispatcher: fetchMock }); + } + return value; +}); +var CoreSharedOptionsSchema = import_zod11.z.object({ + host: import_zod11.z.string().optional(), + port: import_zod11.z.number().optional(), + https: import_zod11.z.boolean().optional(), + httpsKey: import_zod11.z.string().optional(), + httpsKeyPath: import_zod11.z.string().optional(), + httpsCert: import_zod11.z.string().optional(), + httpsCertPath: import_zod11.z.string().optional(), + inspectorPort: import_zod11.z.number().optional(), + verbose: import_zod11.z.boolean().optional(), + log: import_zod11.z.instanceof(Log).optional(), + upstream: import_zod11.z.string().optional(), + // TODO: add back validation of cf object + cf: import_zod11.z.union([import_zod11.z.boolean(), import_zod11.z.string(), import_zod11.z.record(import_zod11.z.any())]).optional(), + liveReload: import_zod11.z.boolean().optional() +}); +var CORE_PLUGIN_NAME2 = "core"; +var LIVE_RELOAD_SCRIPT_TEMPLATE = (port) => ``; +var SCRIPT_CUSTOM_SERVICE = `addEventListener("fetch", (event) => { + const request = new Request(event.request); + request.headers.set("${CoreHeaders.CUSTOM_SERVICE}", ${CoreBindings.TEXT_CUSTOM_SERVICE}); + request.headers.set("${CoreHeaders.ORIGINAL_URL}", request.url); + event.respondWith(${CoreBindings.SERVICE_LOOPBACK}.fetch(request)); +})`; +function getCustomServiceDesignator(workerIndex, kind, name, service) { + let serviceName; + if (typeof service === "function") { + serviceName = getCustomServiceName(workerIndex, kind, name); + } else if (typeof service === "object") { + serviceName = getBuiltinServiceName(workerIndex, kind, name); + } else { + serviceName = getUserServiceName(service); + } + return { name: serviceName }; +} +function maybeGetCustomServiceService(workerIndex, kind, name, service) { + if (typeof service === "function") { + return { + name: getCustomServiceName(workerIndex, kind, name), + worker: { + serviceWorkerScript: SCRIPT_CUSTOM_SERVICE, + compatibilityDate: "2022-09-01", + bindings: [ + { + name: CoreBindings.TEXT_CUSTOM_SERVICE, + text: `${workerIndex}/${kind}${name}` + }, + WORKER_BINDING_SERVICE_LOOPBACK + ] + } + }; + } else if (typeof service === "object") { + return { + name: getBuiltinServiceName(workerIndex, kind, name), + ...service + }; + } +} +var FALLBACK_COMPATIBILITY_DATE = "2000-01-01"; +function getCurrentCompatibilityDate() { + const now = new Date().toISOString(); + return now.substring(0, now.indexOf("T")); +} +function validateCompatibilityDate(log, compatibilityDate) { + if (numericCompare(compatibilityDate, getCurrentCompatibilityDate()) > 0) { + throw new MiniflareCoreError( + "ERR_FUTURE_COMPATIBILITY_DATE", + `Compatibility date "${compatibilityDate}" is in the future and unsupported` + ); + } else if (numericCompare(compatibilityDate, import_workerd2.compatibilityDate) > 0) { + log.warn( + [ + "The latest compatibility date supported by the installed Cloudflare Workers Runtime is ", + bold(`"${import_workerd2.compatibilityDate}"`), + ",\nbut you've requested ", + bold(`"${compatibilityDate}"`), + ". Falling back to ", + bold(`"${import_workerd2.compatibilityDate}"`), + "..." + ].join("") + ); + return import_workerd2.compatibilityDate; + } + return compatibilityDate; +} +var CORE_PLUGIN = { + options: CoreOptionsSchema, + sharedOptions: CoreSharedOptionsSchema, + getBindings(options, workerIndex) { + const bindings = []; + if (options.bindings !== void 0) { + bindings.push( + ...Object.entries(options.bindings).map(([name, value]) => ({ + name, + json: JSON.stringify(value) + })) + ); + } + if (options.wasmBindings !== void 0) { + bindings.push( + ...Object.entries(options.wasmBindings).map( + ([name, path21]) => import_promises5.default.readFile(path21).then((wasmModule) => ({ name, wasmModule })) + ) + ); + } + if (options.textBlobBindings !== void 0) { + bindings.push( + ...Object.entries(options.textBlobBindings).map( + ([name, path21]) => import_promises5.default.readFile(path21, "utf8").then((text) => ({ name, text })) + ) + ); + } + if (options.dataBlobBindings !== void 0) { + bindings.push( + ...Object.entries(options.dataBlobBindings).map( + ([name, path21]) => import_promises5.default.readFile(path21).then((data) => ({ name, data })) + ) + ); + } + if (options.serviceBindings !== void 0) { + bindings.push( + ...Object.entries(options.serviceBindings).map(([name, service]) => { + return { + name, + service: getCustomServiceDesignator( + workerIndex, + "#" /* UNKNOWN */, + name, + service + ) + }; + }) + ); + } + return Promise.all(bindings); + }, + async getNodeBindings(options) { + const bindingEntries = []; + if (options.bindings !== void 0) { + bindingEntries.push( + ...Object.entries(options.bindings).map(([name, value]) => [ + name, + JSON.parse(JSON.stringify(value)) + ]) + ); + } + if (options.wasmBindings !== void 0) { + bindingEntries.push( + ...Object.entries(options.wasmBindings).map( + ([name, path21]) => import_promises5.default.readFile(path21).then((buffer) => [name, new WebAssembly.Module(buffer)]) + ) + ); + } + if (options.textBlobBindings !== void 0) { + bindingEntries.push( + ...Object.entries(options.textBlobBindings).map( + ([name, path21]) => import_promises5.default.readFile(path21, "utf8").then((text) => [name, text]) + ) + ); + } + if (options.dataBlobBindings !== void 0) { + bindingEntries.push( + ...Object.entries(options.dataBlobBindings).map( + ([name, path21]) => import_promises5.default.readFile(path21).then((buffer) => [name, viewToBuffer(buffer)]) + ) + ); + } + if (options.serviceBindings !== void 0) { + bindingEntries.push( + ...Object.keys(options.serviceBindings).map((name) => [ + name, + kProxyNodeBinding + ]) + ); + } + return Object.fromEntries(await Promise.all(bindingEntries)); + }, + async getServices({ + log, + options, + workerBindings, + workerIndex, + durableObjectClassNames, + additionalModules + }) { + const additionalModuleNames = additionalModules.map(({ name: name2 }) => name2); + const workerScript = getWorkerScript( + options, + workerIndex, + additionalModuleNames + ); + if ("modules" in workerScript) { + const subDirs = new Set( + workerScript.modules.map(({ name: name2 }) => import_path13.default.posix.dirname(name2)) + ); + subDirs.delete("."); + for (const module2 of additionalModules) { + workerScript.modules.push(module2); + for (const subDir of subDirs) { + const relativePath = import_path13.default.posix.relative(subDir, module2.name); + const relativePathString = JSON.stringify(relativePath); + workerScript.modules.push({ + name: import_path13.default.posix.join(subDir, module2.name), + // TODO(someday): if we ever have additional modules without + // default exports, this may be a problem. For now, our only + // additional module is `__STATIC_CONTENT_MANIFEST` so it's fine. + // If needed, we could look for instances of `export default` or + // `as default` in the module's code as a heuristic. + esModule: `export * from ${relativePathString}; export { default } from ${relativePathString};` + }); + } + } + } + const name = getUserServiceName(options.name); + const classNames = durableObjectClassNames.get(name); + const classNamesEntries = Array.from(classNames ?? []); + const compatibilityDate = validateCompatibilityDate( + log, + options.compatibilityDate ?? FALLBACK_COMPATIBILITY_DATE + ); + const services = [ + { + name, + worker: { + ...workerScript, + compatibilityDate, + compatibilityFlags: options.compatibilityFlags, + bindings: workerBindings, + durableObjectNamespaces: classNamesEntries.map( + ([className, unsafeUniqueKey]) => { + return { + className, + // This `uniqueKey` will (among other things) be used as part of the + // path when persisting to the file-system. `-` is invalid in + // JavaScript class names, but safe on filesystems (incl. Windows). + uniqueKey: unsafeUniqueKey ?? `${options.name ?? ""}-${className}` + }; + } + ), + durableObjectStorage: classNamesEntries.length === 0 ? void 0 : options.unsafeEphemeralDurableObjects ? { inMemory: kVoid } : { localDisk: DURABLE_OBJECTS_STORAGE_SERVICE_NAME }, + globalOutbound: options.outboundService === void 0 ? void 0 : getCustomServiceDesignator( + workerIndex, + "$" /* KNOWN */, + CUSTOM_SERVICE_KNOWN_OUTBOUND, + options.outboundService + ), + cacheApiOutbound: { name: getCacheServiceName(workerIndex) } + } + } + ]; + if (options.serviceBindings !== void 0) { + for (const [name2, service] of Object.entries(options.serviceBindings)) { + const maybeService = maybeGetCustomServiceService( + workerIndex, + "#" /* UNKNOWN */, + name2, + service + ); + if (maybeService !== void 0) + services.push(maybeService); + } + } + if (options.outboundService !== void 0) { + const maybeService = maybeGetCustomServiceService( + workerIndex, + "$" /* KNOWN */, + CUSTOM_SERVICE_KNOWN_OUTBOUND, + options.outboundService + ); + if (maybeService !== void 0) + services.push(maybeService); + } + return services; + } +}; +function getGlobalServices({ + sharedOptions, + allWorkerRoutes, + fallbackWorkerName, + loopbackPort, + log, + proxyBindings +}) { + const workerNames = [...allWorkerRoutes.keys()]; + const routes = parseRoutes(allWorkerRoutes); + const serviceEntryBindings = [ + WORKER_BINDING_SERVICE_LOOPBACK, + // For converting stack-traces to pretty-error pages + { name: CoreBindings.JSON_ROUTES, json: JSON.stringify(routes) }, + { name: CoreBindings.JSON_CF_BLOB, json: JSON.stringify(sharedOptions.cf) }, + { name: CoreBindings.JSON_LOG_LEVEL, json: JSON.stringify(log.level) }, + { + name: CoreBindings.SERVICE_USER_FALLBACK, + service: { name: getUserServiceName(fallbackWorkerName) } + }, + ...workerNames.map((name) => ({ + name: CoreBindings.SERVICE_USER_ROUTE_PREFIX + name, + service: { name: getUserServiceName(name) } + })), + { + name: CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY, + durableObjectNamespace: { className: "ProxyServer" } + }, + // Add `proxyBindings` here, they'll be added to the `ProxyServer` `env`. + // TODO(someday): consider making the proxy server a separate worker + ...proxyBindings + ]; + if (sharedOptions.upstream !== void 0) { + serviceEntryBindings.push({ + name: CoreBindings.TEXT_UPSTREAM_URL, + text: sharedOptions.upstream + }); + } + if (sharedOptions.liveReload) { + const liveReloadScript = LIVE_RELOAD_SCRIPT_TEMPLATE(loopbackPort); + serviceEntryBindings.push({ + name: CoreBindings.DATA_LIVE_RELOAD_SCRIPT, + data: encoder2.encode(liveReloadScript) + }); + } + return [ + { + name: SERVICE_LOOPBACK, + external: { http: { cfBlobHeader: HEADER_CF_BLOB } } + }, + { + name: SERVICE_ENTRY, + worker: { + modules: [{ name: "entry.worker.js", esModule: entry_worker_default() }], + compatibilityDate: "2023-04-04", + compatibilityFlags: ["nodejs_compat", "service_binding_extra_handlers"], + bindings: serviceEntryBindings, + durableObjectNamespaces: [ + { + className: "ProxyServer", + uniqueKey: `${SERVICE_ENTRY}-ProxyServer` + } + ], + // `ProxyServer` doesn't make use of Durable Object storage + durableObjectStorage: { inMemory: kVoid }, + // Always use the entrypoints cache implementation for proxying. This + // means if the entrypoint disables caching, proxied cache operations + // will be no-ops. Note we always require at least one worker to be set. + cacheApiOutbound: { name: "cache:0" } + } + }, + { + name: "internet", + network: { + // Allow access to private/public addresses: + // https://github.com/cloudflare/miniflare/issues/412 + allow: ["public", "private"], + deny: [], + tlsOptions: { + trustBrowserCas: true, + trustedCertificates + } + } + } + ]; +} +function getWorkerScript(options, workerIndex, additionalModuleNames) { + const modulesRoot = ("modulesRoot" in options ? options.modulesRoot : void 0) ?? ""; + if (Array.isArray(options.modules)) { + return { + modules: options.modules.map( + (module2) => convertModuleDefinition(modulesRoot, module2) + ) + }; + } + let code; + if ("script" in options && options.script !== void 0) { + code = options.script; + } else if ("scriptPath" in options && options.scriptPath !== void 0) { + code = (0, import_fs11.readFileSync)(options.scriptPath, "utf8"); + } else { + import_assert8.default.fail("Unreachable: Workers must have code"); + } + const scriptPath = options.scriptPath ?? buildStringScriptPath(workerIndex); + if (options.modules) { + const locator = new ModuleLocator( + modulesRoot, + additionalModuleNames, + options.modulesRules, + options.compatibilityFlags + ); + locator.visitEntrypoint(code, scriptPath); + return { modules: locator.modules }; + } else { + code = withSourceURL(code, scriptPath); + return { serviceWorkerScript: code }; + } +} + +// packages/miniflare/src/plugins/d1/index.ts +var import_promises6 = __toESM(require("fs/promises")); + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/d1/database.worker.ts +var import_fs12 = __toESM(require("fs")); +var import_path14 = __toESM(require("path")); +var import_url12 = __toESM(require("url")); +var contents8; +function database_worker_default() { + if (contents8 !== void 0) + return contents8; + const filePath = import_path14.default.join(__dirname, "workers", "d1/database.worker.js"); + contents8 = import_fs12.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url12.default.pathToFileURL(filePath); + return contents8; +} + +// packages/miniflare/src/plugins/d1/index.ts +var import_zod12 = require("zod"); +var D1OptionsSchema = import_zod12.z.object({ + d1Databases: import_zod12.z.union([import_zod12.z.record(import_zod12.z.string()), import_zod12.z.string().array()]).optional() +}); +var D1SharedOptionsSchema = import_zod12.z.object({ + d1Persist: PersistenceSchema +}); +var D1_PLUGIN_NAME = "d1"; +var D1_STORAGE_SERVICE_NAME = `${D1_PLUGIN_NAME}:storage`; +var D1_DATABASE_SERVICE_PREFIX = `${D1_PLUGIN_NAME}:db`; +var D1_DATABASE_OBJECT_CLASS_NAME = "D1DatabaseObject"; +var D1_DATABASE_OBJECT = { + serviceName: D1_DATABASE_SERVICE_PREFIX, + className: D1_DATABASE_OBJECT_CLASS_NAME +}; +var D1_PLUGIN = { + options: D1OptionsSchema, + sharedOptions: D1SharedOptionsSchema, + getBindings(options) { + const databases = namespaceEntries(options.d1Databases); + return databases.map(([name, id]) => { + const binding = name.startsWith("__D1_BETA__") ? ( + // Used before Wrangler 3.3 + { + service: { name: `${D1_DATABASE_SERVICE_PREFIX}:${id}` } + } + ) : ( + // Used after Wrangler 3.3 + { + wrapped: { + moduleName: "cloudflare-internal:d1-api", + innerBindings: [ + { + name: "fetcher", + service: { name: `${D1_DATABASE_SERVICE_PREFIX}:${id}` } + } + ] + } + } + ); + return { name, ...binding }; + }); + }, + getNodeBindings(options) { + const databases = namespaceKeys(options.d1Databases); + return Object.fromEntries( + databases.map((name) => [name, kProxyNodeBinding]) + ); + }, + async getServices({ options, sharedOptions, tmpPath, log }) { + const persist = sharedOptions.d1Persist; + const databases = namespaceEntries(options.d1Databases); + const services = databases.map(([_, id]) => ({ + name: `${D1_DATABASE_SERVICE_PREFIX}:${id}`, + worker: objectEntryWorker(D1_DATABASE_OBJECT, id) + })); + if (databases.length > 0) { + const uniqueKey = `miniflare-${D1_DATABASE_OBJECT_CLASS_NAME}`; + const persistPath = getPersistPath(D1_PLUGIN_NAME, tmpPath, persist); + await import_promises6.default.mkdir(persistPath, { recursive: true }); + const storageService = { + name: D1_STORAGE_SERVICE_NAME, + disk: { path: persistPath, writable: true } + }; + const objectService = { + name: D1_DATABASE_SERVICE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "database.worker.js", + esModule: database_worker_default() + } + ], + durableObjectNamespaces: [ + { + className: D1_DATABASE_OBJECT_CLASS_NAME, + uniqueKey + } + ], + // Store Durable Object SQL databases in persist path + durableObjectStorage: { localDisk: D1_STORAGE_SERVICE_NAME }, + // Bind blob disk directory service to object + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: D1_STORAGE_SERVICE_NAME } + }, + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + } + ] + } + }; + services.push(storageService, objectService); + for (const database of databases) { + await migrateDatabase(log, uniqueKey, persistPath, database[1]); + } + } + return services; + } +}; + +// packages/miniflare/src/plugins/kv/index.ts +var import_promises8 = __toESM(require("fs/promises")); + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/kv/namespace.worker.ts +var import_fs13 = __toESM(require("fs")); +var import_path15 = __toESM(require("path")); +var import_url13 = __toESM(require("url")); +var contents9; +function namespace_worker_default() { + if (contents9 !== void 0) + return contents9; + const filePath = import_path15.default.join(__dirname, "workers", "kv/namespace.worker.js"); + contents9 = import_fs13.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url13.default.pathToFileURL(filePath); + return contents9; +} + +// packages/miniflare/src/plugins/kv/index.ts +var import_zod13 = require("zod"); + +// packages/miniflare/src/plugins/kv/constants.ts +var KV_PLUGIN_NAME = "kv"; + +// packages/miniflare/src/plugins/kv/sites.ts +var import_assert9 = __toESM(require("assert")); +var import_promises7 = __toESM(require("fs/promises")); +var import_path17 = __toESM(require("path")); + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/kv/sites.worker.ts +var import_fs14 = __toESM(require("fs")); +var import_path16 = __toESM(require("path")); +var import_url14 = __toESM(require("url")); +var contents10; +function sites_worker_default() { + if (contents10 !== void 0) + return contents10; + const filePath = import_path16.default.join(__dirname, "workers", "kv/sites.worker.js"); + contents10 = import_fs14.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url14.default.pathToFileURL(filePath); + return contents10; +} + +// packages/miniflare/src/plugins/kv/sites.ts +async function* listKeysInDirectoryInner(rootPath, currentPath) { + const fileEntries = await import_promises7.default.readdir(currentPath, { withFileTypes: true }); + for (const fileEntry of fileEntries) { + const filePath = import_path17.default.posix.join(currentPath, fileEntry.name); + if (fileEntry.isDirectory()) { + yield* listKeysInDirectoryInner(rootPath, filePath); + } else { + yield filePath.substring(rootPath.length + 1); + } + } +} +function listKeysInDirectory(rootPath) { + rootPath = import_path17.default.resolve(rootPath); + return listKeysInDirectoryInner(rootPath, rootPath); +} +var sitesRegExpsCache = /* @__PURE__ */ new WeakMap(); +var SERVICE_NAMESPACE_SITE = `${KV_PLUGIN_NAME}:site`; +async function buildStaticContentManifest(sitePath, siteRegExps) { + const staticContentManifest = {}; + for await (const key of listKeysInDirectory(sitePath)) { + if (testSiteRegExps(siteRegExps, key)) { + staticContentManifest[key] = encodeSitesKey(key); + } + } + return staticContentManifest; +} +async function getSitesBindings(options) { + const siteRegExps = { + include: options.siteInclude && globsToRegExps(options.siteInclude), + exclude: options.siteExclude && globsToRegExps(options.siteExclude) + }; + sitesRegExpsCache.set(options, siteRegExps); + const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest( + options.sitePath, + siteRegExps + ); + return [ + { + name: SiteBindings.KV_NAMESPACE_SITE, + kvNamespace: { name: SERVICE_NAMESPACE_SITE } + }, + { + name: SiteBindings.JSON_SITE_MANIFEST, + json: JSON.stringify(__STATIC_CONTENT_MANIFEST) + } + ]; +} +async function getSitesNodeBindings(options) { + const siteRegExps = sitesRegExpsCache.get(options); + (0, import_assert9.default)(siteRegExps !== void 0); + const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest( + options.sitePath, + siteRegExps + ); + return { + [SiteBindings.KV_NAMESPACE_SITE]: kProxyNodeBinding, + [SiteBindings.JSON_SITE_MANIFEST]: __STATIC_CONTENT_MANIFEST + }; +} +function maybeGetSitesManifestModule(bindings) { + for (const binding of bindings) { + if (binding.name === SiteBindings.JSON_SITE_MANIFEST) { + (0, import_assert9.default)("json" in binding && binding.json !== void 0); + return { name: SiteBindings.JSON_SITE_MANIFEST, text: binding.json }; + } + } +} +function getSitesServices(options) { + const siteRegExps = sitesRegExpsCache.get(options); + (0, import_assert9.default)(siteRegExps !== void 0); + const serialisedSiteRegExps = serialiseSiteRegExps(siteRegExps); + const persist = import_path17.default.resolve(options.sitePath); + const storageServiceName = `${SERVICE_NAMESPACE_SITE}:storage`; + const storageService = { + name: storageServiceName, + disk: { path: persist, writable: true } + }; + const namespaceService = { + name: SERVICE_NAMESPACE_SITE, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat"], + modules: [ + { + name: "site.worker.js", + esModule: sites_worker_default() + } + ], + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: storageServiceName } + }, + { + name: SiteBindings.JSON_SITE_FILTER, + json: JSON.stringify(serialisedSiteRegExps) + } + ] + } + }; + return [storageService, namespaceService]; +} + +// packages/miniflare/src/plugins/kv/index.ts +var KVOptionsSchema = import_zod13.z.object({ + kvNamespaces: import_zod13.z.union([import_zod13.z.record(import_zod13.z.string()), import_zod13.z.string().array()]).optional(), + // Workers Sites + sitePath: import_zod13.z.string().optional(), + siteInclude: import_zod13.z.string().array().optional(), + siteExclude: import_zod13.z.string().array().optional() +}); +var KVSharedOptionsSchema = import_zod13.z.object({ + kvPersist: PersistenceSchema +}); +var SERVICE_NAMESPACE_PREFIX = `${KV_PLUGIN_NAME}:ns`; +var KV_STORAGE_SERVICE_NAME = `${KV_PLUGIN_NAME}:storage`; +var KV_NAMESPACE_OBJECT_CLASS_NAME = "KVNamespaceObject"; +var KV_NAMESPACE_OBJECT = { + serviceName: SERVICE_NAMESPACE_PREFIX, + className: KV_NAMESPACE_OBJECT_CLASS_NAME +}; +function isWorkersSitesEnabled(options) { + return options.sitePath !== void 0; +} +var KV_PLUGIN = { + options: KVOptionsSchema, + sharedOptions: KVSharedOptionsSchema, + async getBindings(options) { + const namespaces = namespaceEntries(options.kvNamespaces); + const bindings = namespaces.map(([name, id]) => ({ + name, + kvNamespace: { name: `${SERVICE_NAMESPACE_PREFIX}:${id}` } + })); + if (isWorkersSitesEnabled(options)) { + bindings.push(...await getSitesBindings(options)); + } + return bindings; + }, + async getNodeBindings(options) { + const namespaces = namespaceKeys(options.kvNamespaces); + const bindings = Object.fromEntries( + namespaces.map((name) => [name, kProxyNodeBinding]) + ); + if (isWorkersSitesEnabled(options)) { + Object.assign(bindings, await getSitesNodeBindings(options)); + } + return bindings; + }, + async getServices({ options, sharedOptions, tmpPath, log }) { + const persist = sharedOptions.kvPersist; + const namespaces = namespaceEntries(options.kvNamespaces); + const services = namespaces.map(([_, id]) => ({ + name: `${SERVICE_NAMESPACE_PREFIX}:${id}`, + worker: objectEntryWorker(KV_NAMESPACE_OBJECT, id) + })); + if (services.length > 0) { + const uniqueKey = `miniflare-${KV_NAMESPACE_OBJECT_CLASS_NAME}`; + const persistPath = getPersistPath(KV_PLUGIN_NAME, tmpPath, persist); + await import_promises8.default.mkdir(persistPath, { recursive: true }); + const storageService = { + name: KV_STORAGE_SERVICE_NAME, + disk: { path: persistPath, writable: true } + }; + const objectService = { + name: SERVICE_NAMESPACE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "namespace.worker.js", + esModule: namespace_worker_default() + } + ], + durableObjectNamespaces: [ + { className: KV_NAMESPACE_OBJECT_CLASS_NAME, uniqueKey } + ], + // Store Durable Object SQL databases in persist path + durableObjectStorage: { localDisk: KV_STORAGE_SERVICE_NAME }, + // Bind blob disk directory service to object + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: KV_STORAGE_SERVICE_NAME } + }, + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + } + ] + } + }; + services.push(storageService, objectService); + for (const namespace of namespaces) { + await migrateDatabase(log, uniqueKey, persistPath, namespace[1]); + } + } + if (isWorkersSitesEnabled(options)) { + services.push(...getSitesServices(options)); + } + return services; + } +}; + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/queues/broker.worker.ts +var import_fs15 = __toESM(require("fs")); +var import_path18 = __toESM(require("path")); +var import_url15 = __toESM(require("url")); +var contents11; +function broker_worker_default() { + if (contents11 !== void 0) + return contents11; + const filePath = import_path18.default.join(__dirname, "workers", "queues/broker.worker.js"); + contents11 = import_fs15.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url15.default.pathToFileURL(filePath); + return contents11; +} + +// packages/miniflare/src/plugins/queues/index.ts +var import_zod14 = require("zod"); + +// packages/miniflare/src/plugins/queues/errors.ts +var QueuesError = class extends MiniflareError { +}; + +// packages/miniflare/src/plugins/queues/index.ts +var QueuesOptionsSchema = import_zod14.z.object({ + queueProducers: import_zod14.z.union([import_zod14.z.record(import_zod14.z.string()), import_zod14.z.string().array()]).optional(), + queueConsumers: import_zod14.z.union([import_zod14.z.record(QueueConsumerOptionsSchema), import_zod14.z.string().array()]).optional() +}); +var QUEUES_PLUGIN_NAME = "queues"; +var SERVICE_QUEUE_PREFIX = `${QUEUES_PLUGIN_NAME}:queue`; +var QUEUE_BROKER_OBJECT_CLASS_NAME = "QueueBrokerObject"; +var QUEUE_BROKER_OBJECT = { + serviceName: SERVICE_QUEUE_PREFIX, + className: QUEUE_BROKER_OBJECT_CLASS_NAME +}; +var QUEUES_PLUGIN = { + options: QueuesOptionsSchema, + getBindings(options) { + const queues = namespaceEntries(options.queueProducers); + return queues.map(([name, id]) => ({ + name, + queue: { name: `${SERVICE_QUEUE_PREFIX}:${id}` } + })); + }, + getNodeBindings(options) { + const queues = namespaceKeys(options.queueProducers); + return Object.fromEntries(queues.map((name) => [name, kProxyNodeBinding])); + }, + async getServices({ + options, + workerNames, + queueConsumers: allQueueConsumers + }) { + const queues = namespaceEntries(options.queueProducers); + if (queues.length === 0) + return []; + const services = queues.map(([_, id]) => ({ + name: `${SERVICE_QUEUE_PREFIX}:${id}`, + worker: objectEntryWorker(QUEUE_BROKER_OBJECT, id) + })); + const uniqueKey = `miniflare-${QUEUE_BROKER_OBJECT_CLASS_NAME}`; + const objectService = { + name: SERVICE_QUEUE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: [ + "nodejs_compat", + "experimental", + "service_binding_extra_handlers" + ], + modules: [ + { name: "broker.worker.js", esModule: broker_worker_default() } + ], + durableObjectNamespaces: [ + { className: QUEUE_BROKER_OBJECT_CLASS_NAME, uniqueKey } + ], + // Miniflare's Queue broker is in-memory only at the moment + durableObjectStorage: { inMemory: kVoid }, + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + }, + { + name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT, + durableObjectNamespace: { + className: QUEUE_BROKER_OBJECT_CLASS_NAME + } + }, + { + name: QueueBindings.MAYBE_JSON_QUEUE_CONSUMERS, + json: JSON.stringify(Object.fromEntries(allQueueConsumers)) + }, + ...workerNames.map((name) => ({ + name: QueueBindings.SERVICE_WORKER_PREFIX + name, + service: { name: getUserServiceName(name) } + })) + ] + } + }; + services.push(objectService); + return services; + } +}; + +// packages/miniflare/src/plugins/r2/index.ts +var import_promises9 = __toESM(require("fs/promises")); + +// embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/r2/bucket.worker.ts +var import_fs16 = __toESM(require("fs")); +var import_path19 = __toESM(require("path")); +var import_url16 = __toESM(require("url")); +var contents12; +function bucket_worker_default() { + if (contents12 !== void 0) + return contents12; + const filePath = import_path19.default.join(__dirname, "workers", "r2/bucket.worker.js"); + contents12 = import_fs16.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url16.default.pathToFileURL(filePath); + return contents12; +} + +// packages/miniflare/src/plugins/r2/index.ts +var import_zod15 = require("zod"); +var R2OptionsSchema = import_zod15.z.object({ + r2Buckets: import_zod15.z.union([import_zod15.z.record(import_zod15.z.string()), import_zod15.z.string().array()]).optional() +}); +var R2SharedOptionsSchema = import_zod15.z.object({ + r2Persist: PersistenceSchema +}); +var R2_PLUGIN_NAME = "r2"; +var R2_STORAGE_SERVICE_NAME = `${R2_PLUGIN_NAME}:storage`; +var R2_BUCKET_SERVICE_PREFIX = `${R2_PLUGIN_NAME}:bucket`; +var R2_BUCKET_OBJECT_CLASS_NAME = "R2BucketObject"; +var R2_BUCKET_OBJECT = { + serviceName: R2_BUCKET_SERVICE_PREFIX, + className: R2_BUCKET_OBJECT_CLASS_NAME +}; +var R2_PLUGIN = { + options: R2OptionsSchema, + sharedOptions: R2SharedOptionsSchema, + getBindings(options) { + const buckets = namespaceEntries(options.r2Buckets); + return buckets.map(([name, id]) => ({ + name, + r2Bucket: { name: `${R2_BUCKET_SERVICE_PREFIX}:${id}` } + })); + }, + getNodeBindings(options) { + const buckets = namespaceKeys(options.r2Buckets); + return Object.fromEntries(buckets.map((name) => [name, kProxyNodeBinding])); + }, + async getServices({ options, sharedOptions, tmpPath, log }) { + const persist = sharedOptions.r2Persist; + const buckets = namespaceEntries(options.r2Buckets); + const services = buckets.map(([_, id]) => ({ + name: `${R2_BUCKET_SERVICE_PREFIX}:${id}`, + worker: objectEntryWorker(R2_BUCKET_OBJECT, id) + })); + if (buckets.length > 0) { + const uniqueKey = `miniflare-${R2_BUCKET_OBJECT_CLASS_NAME}`; + const persistPath = getPersistPath(R2_PLUGIN_NAME, tmpPath, persist); + await import_promises9.default.mkdir(persistPath, { recursive: true }); + const storageService = { + name: R2_STORAGE_SERVICE_NAME, + disk: { path: persistPath, writable: true } + }; + const objectService = { + name: R2_BUCKET_SERVICE_PREFIX, + worker: { + compatibilityDate: "2023-07-24", + compatibilityFlags: ["nodejs_compat", "experimental"], + modules: [ + { + name: "bucket.worker.js", + esModule: bucket_worker_default() + } + ], + durableObjectNamespaces: [ + { + className: R2_BUCKET_OBJECT_CLASS_NAME, + uniqueKey + } + ], + // Store Durable Object SQL databases in persist path + durableObjectStorage: { localDisk: R2_STORAGE_SERVICE_NAME }, + // Bind blob disk directory service to object + bindings: [ + { + name: SharedBindings.MAYBE_SERVICE_BLOBS, + service: { name: R2_STORAGE_SERVICE_NAME } + }, + { + name: SharedBindings.MAYBE_SERVICE_LOOPBACK, + service: { name: SERVICE_LOOPBACK } + } + ] + } + }; + services.push(storageService, objectService); + for (const bucket of buckets) { + await migrateDatabase(log, uniqueKey, persistPath, bucket[1]); + } + } + return services; + } +}; + +// packages/miniflare/src/plugins/index.ts +var PLUGINS = { + [CORE_PLUGIN_NAME2]: CORE_PLUGIN, + [CACHE_PLUGIN_NAME]: CACHE_PLUGIN, + [D1_PLUGIN_NAME]: D1_PLUGIN, + [DURABLE_OBJECTS_PLUGIN_NAME]: DURABLE_OBJECTS_PLUGIN, + [KV_PLUGIN_NAME]: KV_PLUGIN, + [QUEUES_PLUGIN_NAME]: QUEUES_PLUGIN, + [R2_PLUGIN_NAME]: R2_PLUGIN +}; +var PLUGIN_ENTRIES = Object.entries(PLUGINS); + +// packages/miniflare/src/http/cert.ts +var KEY = ` +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIC+umAaVUbEfPqGA9M7b5zAP7tN2eLT1bu8U8gpbaKbsoAoGCCqGSM49 +AwEHoUQDQgAEtrIEgzogjrUHIvB4qgjg/cT7blhWuLUfSUp6H62NCo21NrVWgPtC +mCWw+vbGTBwIr/9X1S4UL1/f3zDICC7YSA== +-----END EC PRIVATE KEY----- +`; +var CERT = ` +-----BEGIN CERTIFICATE----- +MIICcDCCAhegAwIBAgIUE97EcbEWw3YZMN/ucGBSzJ/5qA4wCgYIKoZIzj0EAwIw +VTELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMQ8wDQYDVQQHDAZBdXN0aW4x +EzARBgNVBAoMCkNsb3VkZmxhcmUxEDAOBgNVBAsMB1dvcmtlcnMwIBcNMjMwNjIy +MTg1ODQ3WhgPMjEyMzA1MjkxODU4NDdaMFUxCzAJBgNVBAYTAlVTMQ4wDAYDVQQI +DAVUZXhhczEPMA0GA1UEBwwGQXVzdGluMRMwEQYDVQQKDApDbG91ZGZsYXJlMRAw +DgYDVQQLDAdXb3JrZXJzMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEtrIEgzog +jrUHIvB4qgjg/cT7blhWuLUfSUp6H62NCo21NrVWgPtCmCWw+vbGTBwIr/9X1S4U +L1/f3zDICC7YSKOBwjCBvzAdBgNVHQ4EFgQUSXahTksi00c6KhUECHIY4FLW7Sow +HwYDVR0jBBgwFoAUSXahTksi00c6KhUECHIY4FLW7SowDwYDVR0TAQH/BAUwAwEB +/zAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUw +CwYDVR0PBAQDAgL0MDEGA1UdJQQqMCgGCCsGAQUFBwMBBggrBgEFBQcDAgYIKwYB +BQUHAwMGCCsGAQUFBwMIMAoGCCqGSM49BAMCA0cAMEQCIE2qnXbKTHQ8wtwI+9XR +h4ivDyz7w7iGxn3+ccmj/CQqAiApdX/Iz/jGRzi04xFlE4GoPVG/zaMi64ckmIpE +ez/dHA== +-----END CERTIFICATE----- +`; + +// packages/miniflare/src/http/server.ts +async function configureEntrySocket(coreOpts) { + const httpOptions = { + // Even though we inject a `cf` object in the entry worker, allow it to + // be customised via `dispatchFetch` + cfBlobHeader: HEADER_CF_BLOB + }; + let privateKey = void 0; + let certificateChain = void 0; + if ((coreOpts.httpsKey || coreOpts.httpsKeyPath) && (coreOpts.httpsCert || coreOpts.httpsCertPath)) { + privateKey = await valueOrFile(coreOpts.httpsKey, coreOpts.httpsKeyPath); + certificateChain = await valueOrFile( + coreOpts.httpsCert, + coreOpts.httpsCertPath + ); + } else if (coreOpts.https) { + privateKey = KEY; + certificateChain = CERT; + } + let options; + if (privateKey && certificateChain) { + options = { + https: { + options: httpOptions, + tlsOptions: { + keypair: { + privateKey, + certificateChain + } + } + } + }; + } else { + options = { + http: httpOptions + }; + } + return { + name: SOCKET_ENTRY, + service: { name: SERVICE_ENTRY }, + ...options + }; +} +function valueOrFile(value, filePath) { + return value ?? (filePath && import_promises10.default.readFile(filePath, "utf8")); +} + +// packages/miniflare/src/http/helpers.ts +var import_os = require("os"); +function getAccessibleHosts(ipv4Only = false) { + const hosts = []; + Object.values((0, import_os.networkInterfaces)()).forEach((net2) => { + net2?.forEach(({ family, address }) => { + if (family === "IPv4" || family === 4) { + hosts.push(address); + } else if (!ipv4Only && (family === "IPv6" || family === 6)) { + hosts.push(`[${address}]`); + } + }); + }); + return hosts; +} + +// packages/miniflare/src/http/index.ts +var import_undici8 = require("undici"); + +// packages/miniflare/src/zod-format.ts +var import_assert10 = __toESM(require("assert")); +var import_util4 = __toESM(require("util")); +var kMessages = Symbol("kMessages"); +var kActual = Symbol("kActual"); +var kGroupId = Symbol("kGroupId"); +var groupColours = [ + yellow, + /* (green) */ + cyan, + blue, + magenta, + green +]; +var GroupCountsMap = Map; +function isAnnotation(value) { + return typeof value === "object" && value !== null && kMessages in value && kActual in value; +} +function isRecord(value) { + return typeof value === "object" && value !== null; +} +function arrayShallowEqual(a, b) { + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) + if (a[i] !== b[i]) + return false; + return true; +} +function issueEqual(a, b) { + return a.message === b.message && arrayShallowEqual(a.path, b.path); +} +function hasMultipleDistinctMessages(issues, atDepth) { + let firstIssue; + for (const issue of issues) { + if (issue.path.length < atDepth) + continue; + if (firstIssue === void 0) + firstIssue = issue; + else if (!issueEqual(firstIssue, issue)) + return true; + } + return false; +} +function annotate(groupCounts, annotated, input, issue, path21, groupId) { + if (path21.length === 0) { + if (issue.code === "invalid_union") { + const unionIssues = issue.unionErrors.flatMap(({ issues }) => issues); + let newGroupId; + const multipleDistinct = hasMultipleDistinctMessages( + unionIssues, + // For this check, we only include messages that are deeper than our + // current level, so we don't include messages we'd ignore if we grouped + issue.path.length + 1 + ); + if (isRecord(input) && multipleDistinct) { + newGroupId = groupCounts.size; + groupCounts.set(newGroupId, 0); + } + for (const unionIssue of unionIssues) { + const unionPath = unionIssue.path.slice(issue.path.length); + if (multipleDistinct && unionPath.length === 0) + continue; + annotated = annotate( + groupCounts, + annotated, + input, + unionIssue, + unionPath, + newGroupId + ); + } + return annotated; + } + const message = issue.message; + if (annotated !== void 0) { + if (isAnnotation(annotated) && !annotated[kMessages].includes(message)) { + annotated[kMessages].push(message); + } + return annotated; + } + if (groupId !== void 0) { + const current = groupCounts.get(groupId); + (0, import_assert10.default)(current !== void 0); + groupCounts.set(groupId, current + 1); + } + return { + [kMessages]: [message], + [kActual]: input, + [kGroupId]: groupId + }; + } + const [head, ...tail] = path21; + (0, import_assert10.default)(isRecord(input), "Expected object/array input for nested issue"); + if (annotated === void 0) { + if (Array.isArray(input)) { + annotated = new Array(input.length); + } else { + const entries = Object.keys(input).map((key) => [key, void 0]); + annotated = Object.fromEntries(entries); + } + } + (0, import_assert10.default)(isRecord(annotated), "Expected object/array for nested issue"); + annotated[head] = annotate( + groupCounts, + annotated[head], + input[head], + issue, + tail, + groupId + ); + return annotated; +} +function print(inspectOptions, groupCounts, annotated, indent = "", extras) { + const prefix = extras?.prefix ?? ""; + const suffix = extras?.suffix ?? ""; + if (isAnnotation(annotated)) { + const prefixIndent = indent + " ".repeat(prefix.length); + const actual = import_util4.default.inspect(annotated[kActual], inspectOptions); + const actualIndented = actual.split("\n").map((line, i) => i > 0 ? prefixIndent + line : line).join("\n"); + let messageColour = red; + let messagePrefix = prefixIndent + "^"; + let groupOr = ""; + if (annotated[kGroupId] !== void 0) { + messageColour = groupColours[annotated[kGroupId] % groupColours.length]; + messagePrefix += annotated[kGroupId] + 1; + const remaining = groupCounts.get(annotated[kGroupId]); + (0, import_assert10.default)(remaining !== void 0); + if (remaining > 1) + groupOr = " *or*"; + groupCounts.set(annotated[kGroupId], remaining - 1); + } + messagePrefix += " "; + const messageIndent = " ".repeat(messagePrefix.length); + const messageIndented = annotated[kMessages].flatMap((m) => m.split("\n")).map((line, i) => i > 0 ? messageIndent + line : line).join("\n"); + const error = messageColour(`${messagePrefix}${messageIndented}${groupOr}`); + return `${indent}${dim(prefix)}${actualIndented}${dim(suffix)} +${error}`; + } else if (Array.isArray(annotated)) { + let result = `${indent}${dim(`${prefix}[`)} +`; + const arrayIndent = indent + " "; + for (let i = 0; i < annotated.length; i++) { + const value = annotated[i]; + if (value === void 0 && (i === 0 || annotated[i - 1] !== void 0)) { + result += `${arrayIndent}${dim("...,")} +`; + } + if (value !== void 0) { + result += print(inspectOptions, groupCounts, value, arrayIndent, { + prefix: `/* [${i}] */ `, + suffix: "," + }); + result += "\n"; + } + } + result += `${indent}${dim(`]${suffix}`)}`; + return result; + } else if (isRecord(annotated)) { + let result = `${indent}${dim(`${prefix}{`)} +`; + const objectIndent = indent + " "; + const entries = Object.entries(annotated); + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + if (value === void 0 && (i === 0 || entries[i - 1][1] !== void 0)) { + result += `${objectIndent}${dim("...,")} +`; + } + if (value !== void 0) { + result += print(inspectOptions, groupCounts, value, objectIndent, { + prefix: `${key}: `, + suffix: "," + }); + result += "\n"; + } + } + result += `${indent}${dim(`}${suffix}`)}`; + return result; + } + return ""; +} +function _formatZodError(error, input) { + const sortedIssues = Array.from(error.issues).sort((a, b) => { + if (a.code !== b.code) { + if (a.code === "invalid_union") + return -1; + if (b.code === "invalid_union") + return 1; + } + return 0; + }); + let annotated; + const groupCounts = new GroupCountsMap(); + for (const issue of sortedIssues) { + annotated = annotate(groupCounts, annotated, input, issue, issue.path); + } + const inspectOptions = { + depth: 0, + colors: $.enabled + }; + return print(inspectOptions, groupCounts, annotated); +} + +// packages/miniflare/src/index.ts +function hasMultipleWorkers(opts) { + return typeof opts === "object" && opts !== null && "workers" in opts && Array.isArray(opts.workers); +} +function validateOptions(opts) { + const sharedOpts = opts; + const multipleWorkers = hasMultipleWorkers(opts); + const workerOpts = multipleWorkers ? opts.workers : [opts]; + if (workerOpts.length === 0) { + throw new MiniflareCoreError("ERR_NO_WORKERS", "No workers defined"); + } + const pluginSharedOpts = {}; + const pluginWorkerOpts = Array.from(Array(workerOpts.length)).map( + () => ({}) + ); + try { + for (const [key, plugin] of PLUGIN_ENTRIES) { + pluginSharedOpts[key] = plugin.sharedOptions?.parse(sharedOpts); + for (let i = 0; i < workerOpts.length; i++) { + const path21 = multipleWorkers ? ["workers", i] : void 0; + pluginWorkerOpts[i][key] = plugin.options.parse(workerOpts[i], { + path: path21 + }); + } + } + } catch (e) { + if (e instanceof import_zod17.z.ZodError) { + let formatted; + try { + formatted = _formatZodError(e, opts); + } catch (formatError) { + const title = "[Miniflare] Validation Error Format Failure"; + const message = [ + "### Input", + "```", + import_util5.default.inspect(opts, { depth: null }), + "```", + "", + "### Validation Error", + "```", + e.stack, + "```", + "", + "### Format Error", + "```", + typeof formatError === "object" && formatError !== null && "stack" in formatError && typeof formatError.stack === "string" ? formatError.stack : String(formatError), + "```" + ].join("\n"); + const githubIssueUrl = new URL( + "https://github.com/cloudflare/miniflare/issues/new" + ); + githubIssueUrl.searchParams.set("title", title); + githubIssueUrl.searchParams.set("body", message); + formatted = [ + "Unable to format validation error.", + "Please open the following URL in your browser to create a GitHub issue:", + githubIssueUrl, + "", + message, + "" + ].join("\n"); + } + const error = new MiniflareCoreError( + "ERR_VALIDATION", + `Unexpected options passed to \`new Miniflare()\` constructor: +${formatted}` + ); + Object.defineProperty(error, "cause", { get: () => e }); + throw error; + } + throw e; + } + const names = /* @__PURE__ */ new Set(); + for (const opts2 of pluginWorkerOpts) { + const name = opts2.core.name ?? ""; + if (names.has(name)) { + throw new MiniflareCoreError( + "ERR_DUPLICATE_NAME", + name === "" ? "Multiple workers defined without a `name`" : `Multiple workers defined with the same \`name\`: "${name}"` + ); + } + names.add(name); + } + return [pluginSharedOpts, pluginWorkerOpts]; +} +function getDurableObjectClassNames(allWorkerOpts) { + const serviceClassNames = /* @__PURE__ */ new Map(); + for (const workerOpts of allWorkerOpts) { + const workerServiceName = getUserServiceName(workerOpts.core.name); + for (const designator of Object.values( + workerOpts.do.durableObjects ?? {} + )) { + const { + className, + // Fallback to current worker service if name not defined + serviceName = workerServiceName, + unsafeUniqueKey + } = normaliseDurableObject(designator); + let classNames = serviceClassNames.get(serviceName); + if (classNames === void 0) { + classNames = /* @__PURE__ */ new Map(); + serviceClassNames.set(serviceName, classNames); + } + if (classNames.has(className)) { + const existingUnsafeUniqueKey = classNames.get(className); + if (existingUnsafeUniqueKey !== unsafeUniqueKey) { + throw new MiniflareCoreError( + "ERR_DIFFERENT_UNIQUE_KEYS", + `Multiple unsafe unique keys defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify( + unsafeUniqueKey + )} and ${JSON.stringify(existingUnsafeUniqueKey)}` + ); + } + } else { + classNames.set(className, unsafeUniqueKey); + } + } + } + return serviceClassNames; +} +function getQueueConsumers(allWorkerOpts) { + const queueConsumers = /* @__PURE__ */ new Map(); + for (const workerOpts of allWorkerOpts) { + const workerName = workerOpts.core.name ?? ""; + let workerConsumers = workerOpts.queues.queueConsumers; + if (workerConsumers !== void 0) { + if (Array.isArray(workerConsumers)) { + workerConsumers = Object.fromEntries( + workerConsumers.map((queueName) => [queueName, {}]) + ); + } + for (const [queueName, opts] of Object.entries(workerConsumers)) { + const existingConsumer = queueConsumers.get(queueName); + if (existingConsumer !== void 0) { + throw new QueuesError( + "ERR_MULTIPLE_CONSUMERS", + `Multiple consumers defined for queue "${queueName}": "${existingConsumer.workerName}" and "${workerName}"` + ); + } + queueConsumers.set(queueName, { workerName, ...opts }); + } + } + } + for (const [queueName, consumer] of queueConsumers) { + if (consumer.deadLetterQueue === queueName) { + throw new QueuesError( + "ERR_DEAD_LETTER_QUEUE_CYCLE", + `Dead letter queue for queue "${queueName}" cannot be itself` + ); + } + } + return queueConsumers; +} +function getWorkerRoutes(allWorkerOpts) { + const allRoutes = /* @__PURE__ */ new Map(); + for (const workerOpts of allWorkerOpts) { + const name = workerOpts.core.name ?? ""; + (0, import_assert11.default)(!allRoutes.has(name)); + allRoutes.set(name, workerOpts.core.routes ?? []); + } + return allRoutes; +} +function getProxyBindingName(plugin, worker, binding) { + return [ + CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY, + plugin, + worker, + binding + ].join(":"); +} +function isNativeTargetBinding(binding) { + return !("json" in binding || "wasmModule" in binding || "text" in binding || "data" in binding); +} +function buildProxyBinding(plugin, worker, binding) { + (0, import_assert11.default)(binding.name !== void 0); + const name = getProxyBindingName(plugin, worker, binding.name); + const proxyBinding = { ...binding, name }; + if ("durableObjectNamespace" in proxyBinding && proxyBinding.durableObjectNamespace !== void 0) { + proxyBinding.durableObjectNamespace.serviceName ??= getUserServiceName(worker); + } + return proxyBinding; +} +function getInternalDurableObjectProxyBindings(plugin, service) { + if (!("worker" in service)) + return; + (0, import_assert11.default)(service.worker !== void 0); + const serviceName = service.name; + (0, import_assert11.default)(serviceName !== void 0); + return service.worker.durableObjectNamespaces?.map(({ className }) => { + (0, import_assert11.default)(className !== void 0); + return { + name: getProxyBindingName(`${plugin}-internal`, serviceName, className), + durableObjectNamespace: { serviceName, className } + }; + }); +} +var restrictedUndiciHeaders = [ + // From Miniflare 2: + // https://github.com/cloudflare/miniflare/blob/9c135599dc21fe69080ada17fce6153692793bf1/packages/core/src/standards/http.ts#L129-L132 + "transfer-encoding", + "connection", + "keep-alive", + "expect" +]; +var restrictedWebSocketUpgradeHeaders = [ + "upgrade", + "connection", + "sec-websocket-accept" +]; +function _transformsForContentEncoding(encoding) { + const encoders = []; + if (!encoding) + return encoders; + const codings = encoding.toLowerCase().split(",").map((x) => x.trim()); + for (const coding of codings) { + if (/(x-)?gzip/.test(coding)) { + encoders.push(import_zlib.default.createGzip()); + } else if (/(x-)?deflate/.test(coding)) { + encoders.push(import_zlib.default.createDeflate()); + } else if (coding === "br") { + encoders.push(import_zlib.default.createBrotliCompress()); + } else { + encoders.length = 0; + break; + } + } + return encoders; +} +async function writeResponse(response, res) { + const headers = {}; + for (const entry of response.headers) { + const key = entry[0].toLowerCase(); + const value = entry[1]; + if (key === "set-cookie") { + headers[key] = response.headers.getSetCookie(); + } else { + headers[key] = value; + } + } + const encoding = headers["content-encoding"]?.toString(); + const encoders = _transformsForContentEncoding(encoding); + if (encoders.length > 0) { + delete headers["content-length"]; + } + res.writeHead(response.status, response.statusText, headers); + let initialStream = res; + for (let i = encoders.length - 1; i >= 0; i--) { + encoders[i].pipe(initialStream); + initialStream = encoders[i]; + } + if (response.body) { + for await (const chunk of response.body) { + if (chunk) + initialStream.write(chunk); + } + } + initialStream.end(); +} +function safeReadableStreamFrom(iterable) { + let iterator; + return new import_web5.ReadableStream( + { + async start() { + iterator = iterable[Symbol.asyncIterator](); + }, + // @ts-expect-error `pull` may return anything + async pull(controller) { + try { + const { done, value } = await iterator.next(); + if (done) { + queueMicrotask(() => controller.close()); + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value); + controller.enqueue(new Uint8Array(buf)); + } + } catch { + queueMicrotask(() => controller.close()); + } + return controller.desiredSize > 0; + }, + async cancel() { + await iterator.return?.(); + } + }, + 0 + ); +} +var maybeInstanceRegistry; +function _initialiseInstanceRegistry() { + return maybeInstanceRegistry = /* @__PURE__ */ new Map(); +} +var Miniflare = class { + #sharedOpts; + #workerOpts; + #log; + #host; + #accessibleHost; + #runtime; + #removeRuntimeExitHook; + #runtimeEntryURL; + #runtimeClient; + #proxyClient; + // Path to temporary directory for use as scratch space/"in-memory" Durable + // Object storage. Note this may not exist, it's up to the consumers to + // create this if needed. Deleted on `dispose()`. + #tmpPath; + #removeTmpPathExitHook; + // Mutual exclusion lock for runtime operations (i.e. initialisation and + // updating config). This essentially puts initialisation and future updates + // in a queue, ensuring they're performed in calling order. + #runtimeMutex; + // Store `#init()` `Promise`, so we can propagate initialisation errors in + // `ready`. We would have no way of catching these otherwise. + #initPromise; + // Aborted when dispose() is called + #disposeController; + #loopbackServer; + #loopbackPort; + #liveReloadServer; + #webSocketServer; + #webSocketExtraHeaders; + constructor(opts) { + const [sharedOpts, workerOpts] = validateOptions(opts); + this.#sharedOpts = sharedOpts; + this.#workerOpts = workerOpts; + if (maybeInstanceRegistry !== void 0) { + const object = { name: "Miniflare", stack: "" }; + Error.captureStackTrace(object, Miniflare); + maybeInstanceRegistry.set(this, object.stack); + } + this.#log = this.#sharedOpts.core.log ?? new NoOpLog(); + this.#host = this.#sharedOpts.core.host ?? "127.0.0.1"; + this.#accessibleHost = this.#host === "*" || this.#host === "0.0.0.0" || this.#host === "::" ? "127.0.0.1" : this.#host; + if (import_net.default.isIPv6(this.#accessibleHost)) { + this.#accessibleHost = `[${this.#accessibleHost}]`; + } + this.#liveReloadServer = new import_ws3.WebSocketServer({ noServer: true }); + this.#webSocketServer = new import_ws3.WebSocketServer({ + noServer: true, + // Disable automatic handling of `Sec-WebSocket-Protocol` header, + // Cloudflare Workers require users to include this header themselves in + // `Response`s: https://github.com/cloudflare/miniflare/issues/179 + handleProtocols: () => false + }); + this.#webSocketExtraHeaders = /* @__PURE__ */ new WeakMap(); + this.#webSocketServer.on("headers", (headers, req) => { + const extra = this.#webSocketExtraHeaders.get(req); + this.#webSocketExtraHeaders.delete(req); + if (extra) { + for (const [key, value] of extra) { + if (!restrictedWebSocketUpgradeHeaders.includes(key.toLowerCase())) { + headers.push(`${key}: ${value}`); + } + } + } + }); + this.#tmpPath = import_path20.default.join( + import_os2.default.tmpdir(), + `miniflare-${import_crypto2.default.randomBytes(16).toString("hex")}` + ); + this.#removeTmpPathExitHook = (0, import_exit_hook.default)(() => { + import_fs17.default.rmSync(this.#tmpPath, { force: true, recursive: true }); + }); + this.#disposeController = new AbortController(); + this.#runtimeMutex = new Mutex(); + this.#initPromise = this.#runtimeMutex.runWith(() => this.#init()).catch((e) => { + maybeInstanceRegistry?.delete(this); + throw e; + }); + } + #handleReload() { + for (const ws of this.#liveReloadServer.clients) { + ws.close(1012, "Service Restart"); + } + for (const ws of this.#webSocketServer.clients) { + ws.close(1012, "Service Restart"); + } + } + async #init() { + this.#loopbackServer = await this.#startLoopbackServer(0, this.#host); + const address = this.#loopbackServer.address(); + (0, import_assert11.default)(address !== null && typeof address === "object"); + this.#loopbackPort = address.port; + const port = this.#sharedOpts.core.port ?? 0; + const opts = { + entryHost: import_net.default.isIPv6(this.#host) ? `[${this.#host}]` : this.#host, + entryPort: port, + loopbackPort: this.#loopbackPort, + inspectorPort: this.#sharedOpts.core.inspectorPort, + verbose: this.#sharedOpts.core.verbose + }; + this.#runtime = new Runtime(opts); + this.#removeRuntimeExitHook = (0, import_exit_hook.default)(() => void this.#runtime?.dispose()); + await this.#assembleAndUpdateConfig(); + } + async #handleLoopbackCustomService(request, customService) { + const slashIndex = customService.indexOf("/"); + const workerIndex = parseInt(customService.substring(0, slashIndex)); + const serviceKind = customService[slashIndex + 1]; + const serviceName = customService.substring(slashIndex + 2); + let service; + if (serviceKind === "#" /* UNKNOWN */) { + service = this.#workerOpts[workerIndex]?.core.serviceBindings?.[serviceName]; + } else if (serviceName === CUSTOM_SERVICE_KNOWN_OUTBOUND) { + service = this.#workerOpts[workerIndex]?.core.outboundService; + } + (0, import_assert11.default)(typeof service === "function"); + try { + const response = await service(request); + return import_zod17.z.instanceof(Response).parse(response); + } catch (e) { + return new Response(e?.stack ?? e, { status: 500 }); + } + } + get #workerSrcOpts() { + return this.#workerOpts.map(({ core }) => core); + } + #handleLoopback = async (req, res) => { + const headers = new import_undici8.Headers(); + for (const [name, values] of Object.entries(req.headers)) { + if (restrictedUndiciHeaders.includes(name)) + continue; + if (Array.isArray(values)) { + for (const value of values) + headers.append(name, value); + } else if (values !== void 0) { + headers.append(name, values); + } + } + const cfBlob = headers.get(HEADER_CF_BLOB); + headers.delete(HEADER_CF_BLOB); + (0, import_assert11.default)(!Array.isArray(cfBlob)); + const cf = cfBlob ? JSON.parse(cfBlob) : void 0; + const url13 = new URL( + headers.get(CoreHeaders.ORIGINAL_URL) ?? req.url ?? "", + "http://localhost" + ); + headers.delete(CoreHeaders.ORIGINAL_URL); + const noBody = req.method === "GET" || req.method === "HEAD"; + const body = noBody ? void 0 : safeReadableStreamFrom(req); + const request = new Request(url13, { + method: req.method, + headers, + body, + duplex: "half", + cf + }); + let response; + try { + const customService = request.headers.get(CoreHeaders.CUSTOM_SERVICE); + if (customService !== null) { + request.headers.delete(CoreHeaders.CUSTOM_SERVICE); + response = await this.#handleLoopbackCustomService( + request, + customService + ); + } else if (url13.pathname === "/core/error") { + response = await handlePrettyErrorRequest( + this.#log, + this.#workerSrcOpts, + request + ); + } else if (url13.pathname === "/core/log") { + const level = parseInt(request.headers.get(SharedHeaders.LOG_LEVEL)); + (0, import_assert11.default)( + 0 /* NONE */ <= level && level <= 5 /* VERBOSE */, + `Expected ${SharedHeaders.LOG_LEVEL} header to be log level, got ${level}` + ); + const logLevel = level; + let message = await request.text(); + if (!$.enabled) + message = stripAnsi(message); + this.#log.logWithLevel(logLevel, message); + response = new Response(null, { status: 204 }); + } + } catch (e) { + this.#log.error(e); + res?.writeHead(500); + res?.end(e?.stack ?? String(e)); + return; + } + if (res !== void 0) { + if (response === void 0) { + res.writeHead(404); + res.end(); + } else { + await writeResponse(response, res); + } + } + return response; + }; + #handleLoopbackUpgrade = async (req, socket, head) => { + const { pathname } = new URL(req.url ?? "", "http://localhost"); + if (pathname === "/cdn-cgi/mf/reload") { + this.#liveReloadServer.handleUpgrade(req, socket, head, (ws) => { + this.#liveReloadServer.emit("connection", ws, req); + }); + return; + } + const response = await this.#handleLoopback(req); + const webSocket = response?.webSocket; + if (response?.status === 101 && webSocket) { + this.#webSocketExtraHeaders.set(req, response.headers); + this.#webSocketServer.handleUpgrade(req, socket, head, (ws) => { + void coupleWebSocket(ws, webSocket); + this.#webSocketServer.emit("connection", ws, req); + }); + return; + } + const res = new import_http7.default.ServerResponse(req); + (0, import_assert11.default)(socket instanceof import_net.default.Socket); + res.assignSocket(socket); + if (!response || response.ok) { + res.writeHead(500); + res.end(); + this.#log.error( + new TypeError( + "Web Socket request did not return status 101 Switching Protocols response with Web Socket" + ) + ); + return; + } + await writeResponse(response, res); + }; + #startLoopbackServer(port, hostname) { + if (hostname === "*") { + hostname = "::"; + } + return new Promise((resolve) => { + const server = (0, import_stoppable.default)( + import_http7.default.createServer(this.#handleLoopback), + /* grace */ + 0 + ); + server.on("upgrade", this.#handleLoopbackUpgrade); + server.listen(port, hostname, () => resolve(server)); + }); + } + #stopLoopbackServer() { + return new Promise((resolve, reject) => { + (0, import_assert11.default)(this.#loopbackServer !== void 0); + this.#loopbackServer.stop((err) => err ? reject(err) : resolve()); + }); + } + async #assembleConfig() { + const allWorkerOpts = this.#workerOpts; + const sharedOpts = this.#sharedOpts; + const loopbackPort = this.#loopbackPort; + (0, import_assert11.default)(loopbackPort !== void 0); + sharedOpts.core.cf = await setupCf(this.#log, sharedOpts.core.cf); + const durableObjectClassNames = getDurableObjectClassNames(allWorkerOpts); + const queueConsumers = getQueueConsumers(allWorkerOpts); + const allWorkerRoutes = getWorkerRoutes(allWorkerOpts); + const workerNames = [...allWorkerRoutes.keys()]; + const services = /* @__PURE__ */ new Map(); + const sockets = [await configureEntrySocket(sharedOpts.core)]; + const proxyBindings = []; + for (let i = 0; i < allWorkerOpts.length; i++) { + const workerOpts = allWorkerOpts[i]; + const workerName = workerOpts.core.name ?? ""; + const workerBindings = []; + const additionalModules = []; + for (const [key, plugin] of PLUGIN_ENTRIES) { + const pluginBindings = await plugin.getBindings(workerOpts[key], i); + if (pluginBindings !== void 0) { + for (const binding of pluginBindings) { + workerBindings.push(binding); + if (isNativeTargetBinding(binding)) { + proxyBindings.push(buildProxyBinding(key, workerName, binding)); + } + } + if (key === "kv") { + const module2 = maybeGetSitesManifestModule(pluginBindings); + if (module2 !== void 0) + additionalModules.push(module2); + } + } + } + const pluginServicesOptionsBase = { + log: this.#log, + workerBindings, + workerIndex: i, + additionalModules, + tmpPath: this.#tmpPath, + workerNames, + durableObjectClassNames, + queueConsumers + }; + for (const [key, plugin] of PLUGIN_ENTRIES) { + const pluginServices = await plugin.getServices({ + ...pluginServicesOptionsBase, + // @ts-expect-error `CoreOptionsSchema` has required options which are + // missing in other plugins' options. + options: workerOpts[key], + // @ts-expect-error `QueuesPlugin` doesn't define shared options + sharedOptions: sharedOpts[key] + }); + if (pluginServices !== void 0) { + for (const service of pluginServices) { + if (service.name !== void 0 && !services.has(service.name)) { + services.set(service.name, service); + if (key !== DURABLE_OBJECTS_PLUGIN_NAME) { + const maybeBindings = getInternalDurableObjectProxyBindings( + key, + service + ); + if (maybeBindings !== void 0) { + proxyBindings.push(...maybeBindings); + } + } + } + } + } + } + } + const extensions = [ + { + modules: [ + { name: "miniflare:shared", esModule: index_worker_default() }, + { name: "miniflare:zod", esModule: zod_worker_default() } + ] + }, + { + modules: [ + { + name: "miniflare-internal:identity", + internal: true, + // Not accessible to user code + esModule: ` + class Identity { + async asyncIdentity(...args) { + const i = args.findIndex((arg) => arg instanceof ReadableStream); + if (i !== -1) args[i] = args[i].pipeThrough(new TransformStream()); + return args; + } + } + export default function() { return new Identity(); } + ` + } + ] + } + ]; + proxyBindings.push({ + name: "IDENTITY", + wrapped: { moduleName: "miniflare-internal:identity" } + }); + const globalServices = getGlobalServices({ + sharedOptions: sharedOpts.core, + allWorkerRoutes, + fallbackWorkerName: this.#workerOpts[0].core.name, + loopbackPort, + log: this.#log, + proxyBindings + }); + for (const service of globalServices) { + (0, import_assert11.default)(service.name !== void 0 && !services.has(service.name)); + services.set(service.name, service); + } + return { services: Array.from(services.values()), sockets, extensions }; + } + async #assembleAndUpdateConfig() { + const initial = !this.#runtimeEntryURL; + (0, import_assert11.default)(this.#runtime !== void 0); + const config = await this.#assembleConfig(); + const configBuffer = serializeConfig(config); + const maybePort = await this.#runtime.updateConfig(configBuffer, { + signal: this.#disposeController.signal, + entryPort: maybeApply(parseInt, this.#runtimeEntryURL?.port) + }); + if (this.#disposeController.signal.aborted) + return; + if (maybePort === void 0) { + throw new MiniflareCoreError( + "ERR_RUNTIME_FAILURE", + "The Workers runtime failed to start. There is likely additional logging output above." + ); + } + const entrySocket = config.sockets?.[0]; + const secure = entrySocket !== void 0 && "https" in entrySocket; + const previousEntry = this.#runtimeEntryURL; + this.#runtimeEntryURL = new URL( + `${secure ? "https" : "http"}://${this.#accessibleHost}:${maybePort}` + ); + if (previousEntry?.toString() !== this.#runtimeEntryURL.toString()) { + this.#runtimeClient = new import_undici9.Client(this.#runtimeEntryURL, { + connect: { rejectUnauthorized: false } + }); + registerAllowUnauthorizedDispatcher(this.#runtimeClient); + } + if (this.#proxyClient === void 0) { + this.#proxyClient = new ProxyClient( + this.#runtimeEntryURL, + this.dispatchFetch + ); + } else { + this.#proxyClient.poisonProxies(this.#runtimeEntryURL); + } + if (!this.#runtimeMutex.hasWaiting) { + const ready = initial ? "Ready" : "Updated and ready"; + const host = import_net.default.isIPv6(this.#host) ? `[${this.#host}]` : this.#host; + this.#log.info( + `${ready} on ${secure ? "https" : "http"}://${host}:${maybePort} ` + ); + if (initial) { + let hosts; + if (this.#host === "::" || this.#host === "*") { + hosts = getAccessibleHosts(false); + } else if (this.#host === "0.0.0.0") { + hosts = getAccessibleHosts(true); + } else { + hosts = []; + } + for (const h of hosts) { + this.#log.info(`- ${secure ? "https" : "http"}://${h}:${maybePort}`); + } + } + this.#handleReload(); + } + } + async #waitForReady() { + await this.#initPromise; + await this.#runtimeMutex.drained(); + (0, import_assert11.default)(this.#runtimeEntryURL !== void 0); + return new URL(this.#runtimeEntryURL.toString()); + } + get ready() { + return this.#waitForReady(); + } + #checkDisposed() { + if (this.#disposeController.signal.aborted) { + throw new MiniflareCoreError( + "ERR_DISPOSED", + "Cannot use disposed instance" + ); + } + } + async #setOptions(opts) { + const [sharedOpts, workerOpts] = validateOptions(opts); + this.#sharedOpts = sharedOpts; + this.#workerOpts = workerOpts; + this.#log = this.#sharedOpts.core.log ?? this.#log; + await this.#assembleAndUpdateConfig(); + } + setOptions(opts) { + this.#checkDisposed(); + return this.#runtimeMutex.runWith(() => this.#setOptions(opts)); + } + dispatchFetch = async (input, init2) => { + this.#checkDisposed(); + await this.ready; + (0, import_assert11.default)(this.#runtimeEntryURL !== void 0); + (0, import_assert11.default)(this.#runtimeClient !== void 0); + const forward = new Request(input, init2); + const url13 = new URL(forward.url); + forward.headers.set(CoreHeaders.ORIGINAL_URL, url13.toString()); + url13.protocol = this.#runtimeEntryURL.protocol; + url13.host = this.#runtimeEntryURL.host; + if (forward.cf) { + const cf = { ...fallbackCf, ...forward.cf }; + forward.headers.set(HEADER_CF_BLOB, JSON.stringify(cf)); + } + if (forward.body !== null && forward.headers.get("Content-Length") === "0") { + forward.headers.delete("Content-Length"); + } + const forwardInit = forward; + forwardInit.dispatcher = this.#runtimeClient; + const response = await fetch2(url13, forwardInit); + const stack = response.headers.get(CoreHeaders.ERROR_STACK); + if (response.status === 500 && stack !== null) { + const caught = JsonErrorSchema.parse(await response.json()); + throw reviveError(this.#workerSrcOpts, caught); + } + if (process.env.MINIFLARE_ASSERT_BODIES_CONSUMED === "true" && response.body !== null) { + const originalLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Infinity; + const error = new Error( + "`body` returned from `Miniflare#dispatchFetch()` not consumed immediately" + ); + Error.stackTraceLimit = originalLimit; + setImmediate(() => { + if (!response.bodyUsed) + throw error; + }); + } + return response; + }; + /** @internal */ + async _getProxyClient() { + this.#checkDisposed(); + await this.ready; + (0, import_assert11.default)(this.#proxyClient !== void 0); + return this.#proxyClient; + } + async getBindings(workerName) { + const bindings = {}; + const proxyClient = await this._getProxyClient(); + let workerOpts; + if (workerName === void 0) { + workerOpts = this.#workerOpts[0]; + } else { + workerOpts = this.#workerOpts.find( + ({ core }) => (core.name ?? "") === workerName + ); + if (workerOpts === void 0) { + throw new TypeError(`${JSON.stringify(workerName)} worker not found`); + } + } + workerName = workerOpts.core.name ?? ""; + for (const [key, plugin] of PLUGIN_ENTRIES) { + const pluginBindings = await plugin.getNodeBindings(workerOpts[key]); + for (const [name, binding] of Object.entries(pluginBindings)) { + if (binding === kProxyNodeBinding) { + const proxyBindingName = getProxyBindingName(key, workerName, name); + const proxy = proxyClient.env[proxyBindingName]; + (0, import_assert11.default)( + proxy !== void 0, + `Expected ${proxyBindingName} to be bound` + ); + bindings[name] = proxy; + } else { + bindings[name] = binding; + } + } + } + return bindings; + } + async #getProxy(pluginName, bindingName, workerName) { + const proxyClient = await this._getProxyClient(); + const proxyBindingName = getProxyBindingName( + pluginName, + // Default to entrypoint worker if none specified + workerName ?? this.#workerOpts[0].core.name ?? "", + bindingName + ); + const proxy = proxyClient.env[proxyBindingName]; + if (proxy === void 0) { + const friendlyWorkerName = workerName === void 0 ? "entrypoint" : JSON.stringify(workerName); + throw new TypeError( + `${JSON.stringify(bindingName)} unbound in ${friendlyWorkerName} worker` + ); + } + return proxy; + } + // TODO(someday): would be nice to define these in plugins + async getCaches() { + const proxyClient = await this._getProxyClient(); + return proxyClient.global.caches; + } + getD1Database(bindingName, workerName) { + return this.#getProxy(D1_PLUGIN_NAME, bindingName, workerName); + } + getDurableObjectNamespace(bindingName, workerName) { + return this.#getProxy(DURABLE_OBJECTS_PLUGIN_NAME, bindingName, workerName); + } + getKVNamespace(bindingName, workerName) { + return this.#getProxy(KV_PLUGIN_NAME, bindingName, workerName); + } + getQueueProducer(bindingName, workerName) { + return this.#getProxy(QUEUES_PLUGIN_NAME, bindingName, workerName); + } + getR2Bucket(bindingName, workerName) { + return this.#getProxy(R2_PLUGIN_NAME, bindingName, workerName); + } + /** @internal */ + _getInternalDurableObjectNamespace(pluginName, serviceName, className) { + return this.#getProxy(`${pluginName}-internal`, className, serviceName); + } + async dispose() { + this.#disposeController.abort(); + try { + await this.ready; + } finally { + this.#removeTmpPathExitHook(); + this.#removeRuntimeExitHook?.(); + await this.#proxyClient?.dispose(); + await this.#runtime?.dispose(); + await this.#stopLoopbackServer(); + await import_fs17.default.promises.rm(this.#tmpPath, { force: true, recursive: true }); + maybeInstanceRegistry?.delete(this); + } + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + CACHE_PLUGIN, + CACHE_PLUGIN_NAME, + CORE_PLUGIN, + CORE_PLUGIN_NAME, + CacheBindings, + CacheHeaders, + CacheOptionsSchema, + CacheSharedOptionsSchema, + CloseEvent, + CoreBindings, + CoreHeaders, + CoreOptionsSchema, + CoreSharedOptionsSchema, + D1OptionsSchema, + D1SharedOptionsSchema, + D1_PLUGIN, + D1_PLUGIN_NAME, + DEFAULT_PERSIST_ROOT, + DURABLE_OBJECTS_PLUGIN, + DURABLE_OBJECTS_PLUGIN_NAME, + DURABLE_OBJECTS_STORAGE_SERVICE_NAME, + DeferredPromise, + DurableObjectsOptionsSchema, + DurableObjectsSharedOptionsSchema, + ErrorEvent, + File, + FormData, + HEADER_CF_BLOB, + Headers, + HttpOptions_Style, + JsonSchema, + KVHeaders, + KVLimits, + KVOptionsSchema, + KVParams, + KVSharedOptionsSchema, + KV_PLUGIN, + KV_PLUGIN_NAME, + LiteralSchema, + Log, + LogLevel, + MessageEvent, + Miniflare, + MiniflareCoreError, + MiniflareError, + ModuleDefinitionSchema, + ModuleRuleSchema, + ModuleRuleTypeSchema, + Mutex, + NoOpLog, + PLUGINS, + PLUGIN_ENTRIES, + PersistenceSchema, + ProxyAddresses, + ProxyClient, + ProxyOps, + QUEUES_PLUGIN, + QUEUES_PLUGIN_NAME, + QueueBindings, + QueueConsumerOptionsSchema, + QueueConsumerSchema, + QueueConsumersSchema, + QueueContentTypeSchema, + QueueIncomingMessageSchema, + QueuesBatchRequestSchema, + QueuesError, + QueuesOptionsSchema, + R2OptionsSchema, + R2SharedOptionsSchema, + R2_PLUGIN, + R2_PLUGIN_NAME, + Request, + Response, + RouterError, + Runtime, + SERVICE_ENTRY, + SERVICE_LOOPBACK, + SITES_NO_CACHE_PREFIX, + SOCKET_ENTRY, + SharedBindings, + SharedHeaders, + SiteBindings, + SourceOptionsSchema, + TlsOptions_Version, + TypedEventTarget, + WORKER_BINDING_SERVICE_LOOPBACK, + WaitGroup, + WebSocket, + WebSocketPair, + Worker_Binding_CryptoKey_Usage, + _forceColour, + _formatZodError, + _initialiseInstanceRegistry, + _transformsForContentEncoding, + base64Decode, + base64Encode, + configureEntrySocket, + coupleWebSocket, + createFetchMock, + createHTTPReducers, + createHTTPRevivers, + decodeSitesKey, + deserialiseRegExps, + deserialiseSiteRegExps, + encodeSitesKey, + fetch, + getAccessibleHosts, + getCacheServiceName, + getGlobalServices, + getPersistPath, + globsToRegExps, + isFetcherFetch, + isR2ObjectWriteHttpMetadata, + isSitesRequest, + kProxyNodeBinding, + kVoid, + matchRoutes, + maybeApply, + maybeGetSitesManifestModule, + maybeParseURL, + migrateDatabase, + namespaceEntries, + namespaceKeys, + normaliseDurableObject, + objectEntryWorker, + parseRanges, + parseRoutes, + parseWithReadableStreams, + prefixError, + prefixStream, + readPrefix, + reduceError, + registerAllowUnauthorizedDispatcher, + sanitisePath, + serialiseRegExps, + serialiseSiteRegExps, + serializeConfig, + stringifyWithStreams, + stripAnsi, + structuredSerializableReducers, + structuredSerializableRevivers, + supportedCompatibilityDate, + testRegExps, + testSiteRegExps, + viewToBuffer, + zAwaitable +}); +/*! Path sanitisation regexps adapted from node-sanitize-filename: + * https://github.com/parshap/node-sanitize-filename/blob/209c39b914c8eb48ee27bcbde64b2c7822fdf3de/index.js#L4-L37 + * + * Licensed under the ISC license: + * + * Copyright Parsha Pourkhomami + * + * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the + * above copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ +/*! + * MIT License + * + * Copyright (c) Sindre Sorhus (https://sindresorhus.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +/*! + * Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +//# sourceMappingURL=index.js.map diff --git a/node_modules/miniflare/dist/src/index.js.map b/node_modules/miniflare/dist/src/index.js.map new file mode 100644 index 0000000..ecd19b6 --- /dev/null +++ b/node_modules/miniflare/dist/src/index.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../src/runtime/config/workerd.capnp.js", "../../src/index.ts", "../../../../node_modules/kleur/colors.mjs", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/shared/index.worker.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/shared/zod.worker.ts", "../../src/cf.ts", "../../src/http/fetch.ts", "../../src/workers/cache/constants.ts", "../../src/workers/core/constants.ts", "../../src/workers/core/devalue.ts", "../../../../node_modules/devalue/src/utils.js", "../../../../node_modules/devalue/src/constants.js", "../../../../node_modules/devalue/src/parse.js", "../../../../node_modules/devalue/src/stringify.js", "../../src/workers/core/routing.ts", "../../src/workers/shared/constants.ts", "../../src/workers/shared/data.ts", "../../src/workers/shared/matcher.ts", "../../src/workers/shared/range.ts", "../../src/workers/shared/sync.ts", "../../src/workers/shared/types.ts", "../../src/workers/kv/constants.ts", "../../src/workers/queues/constants.ts", "../../src/workers/shared/zod.worker.ts", "../../src/workers/queues/schemas.ts", "../../src/http/request.ts", "../../src/http/response.ts", "../../src/http/websocket.ts", "../../src/shared/colour.ts", "../../src/shared/error.ts", "../../src/shared/event.ts", "../../src/shared/log.ts", "../../src/shared/matcher.ts", "../../src/shared/streams.ts", "../../src/shared/types.ts", "../../src/http/server.ts", "../../src/plugins/cache/index.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/cache/cache.worker.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/cache/cache-entry.worker.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/cache/cache-entry-noop.worker.ts", "../../src/plugins/shared/index.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/shared/object-entry.worker.ts", "../../src/plugins/shared/constants.ts", "../../src/plugins/shared/routing.ts", "../../src/plugins/core/index.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/core/entry.worker.ts", "../../src/runtime/index.ts", "../../src/runtime/config/index.ts", "../../src/runtime/config/workerd.ts", "../../src/plugins/do/index.ts", "../../src/plugins/core/constants.ts", "../../src/plugins/core/modules.ts", "../../src/plugins/core/services.ts", "../../src/plugins/core/errors/index.ts", "../../src/plugins/core/errors/sourcemap.ts", "../../src/plugins/core/errors/callsite.ts", "../../src/plugins/core/proxy/client.ts", "../../src/plugins/core/proxy/fetch-sync.ts", "../../src/plugins/core/proxy/types.ts", "../../src/plugins/d1/index.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/d1/database.worker.ts", "../../src/plugins/kv/index.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/kv/namespace.worker.ts", "../../src/plugins/kv/constants.ts", "../../src/plugins/kv/sites.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/kv/sites.worker.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/queues/broker.worker.ts", "../../src/plugins/queues/index.ts", "../../src/plugins/queues/errors.ts", "../../src/plugins/r2/index.ts", "embed-worker:/home/jspspike/Projects/miniflare/packages/miniflare/src/workers/r2/bucket.worker.ts", "../../src/plugins/index.ts", "../../src/http/cert.ts", "../../src/http/helpers.ts", "../../src/http/index.ts", "../../src/zod-format.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,WAAO,eAAe,SAAS,cAAc,EAAE,OAAO,KAAK,CAAC;AAC5D,YAAQ,YAAY,QAAQ,mBAAmB,QAAQ,aAAa,QAAQ,qBAAqB,QAAQ,qBAAqB,QAAQ,cAAc,QAAQ,qBAAqB,QAAQ,oBAAoB,QAAQ,gBAAgB,QAAQ,UAAU,QAAQ,iBAAiB,QAAQ,uBAAuB,QAAQ,uBAAuB,QAAQ,SAAS,QAAQ,eAAe,QAAQ,8BAA8B,QAAQ,oCAAoC,QAAQ,gCAAgC,QAAQ,sCAAsC,QAAQ,iBAAiB,QAAQ,uBAAuB,QAAQ,2BAA2B,QAAQ,gCAAgC,QAAQ,2BAA2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BAAuB,OAAO,IAAI;AAAA,IACpC;AAAA,EACF;AACF;", + "names": ["Config", "Socket_Which", "Socket", "ServiceDesignator", "Service_Which", "Service", "Worker", "ExternalServer", "Worker_Module_Which", "Worker_Module", "Worker_Binding_Type_Which", "Worker_Binding_DurableObjectNamespaceDesignator", "Worker_Binding_CryptoKey_Usage", "Worker_Binding_CryptoKey_Algorithm_Which", "Worker_Binding_CryptoKey_Which", "Worker_Binding_Which", "Worker_Binding", "Worker_DurableObjectNamespace_Which", "Worker_DurableObjectStorage_Which", "Worker_Which", "ExternalServer_Which", "HttpOptions_Style", "TlsOptions_Version", "Extension", "CORE_PLUGIN_NAME", "fetch", "supportedCompatibilityDate", "import_assert", "import_crypto", "import_fs", "import_http", "import_os", "import_path", "import_web", "import_util", "import_undici", "path", "fs", "url", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_ws", "import_zod", "import_path", "path", "assert", "import_undici", "import_ws", "revivers", "reducers", "index", "value", "assert", "url", "reducers", "value", "stringifiedValue", "revivers", "url", "path", "LogLevel", "import_node_buffer", "import_node_assert", "assert", "url", "import_node_buffer", "import_zod", "import_undici", "BaseRequest", "init", "import_undici", "BaseResponse", "url", "init", "import_assert", "import_path", "path", "globToRegexp", "import_zod", "init", "assert", "NodeWebSocket", "fetch", "init", "url", "NodeWebSocket", "baseFetch", "import_promises", "import_promises", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "import_fs", "import_promises", "import_path", "import_url", "import_zod", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_url", "url", "url", "path", "crypto", "fs", "fs", "import_assert", "import_fs", "import_promises", "import_path", "import_util", "import_undici", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "import_assert", "import_workerd", "import_zod", "import_workerd_capnp", "CapnpConfig", "rl", "process", "workerdPath", "childProcess", "assert", "import_promises", "import_zod", "fs", "import_assert", "import_fs", "import_path", "import_url", "import_zod", "module", "path", "rule", "assert", "contents", "import_zod", "import_fs", "import_path", "import_url", "import_zod", "import_assert", "assert", "contents", "fs", "module", "path", "import_assert", "import_web", "import_util", "import_undici", "import_assert", "import_web", "url", "init", "assert", "import_web", "import_undici", "url", "util", "assert", "key", "tls", "encoder", "fetch", "CORE_PLUGIN_NAME", "supportedCompatibilityDate", "path", "fs", "name", "module", "assert", "import_promises", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "fs", "import_promises", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "import_assert", "import_promises", "import_path", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "fs", "path", "assert", "fs", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "import_promises", "import_fs", "import_path", "import_url", "contents", "path", "fs", "url", "import_zod", "fs", "CORE_PLUGIN_NAME", "fs", "net", "import_undici", "import_assert", "import_util", "path", "assert", "util", "path", "util", "opts", "assert", "zlib", "net", "os", "crypto", "exitHook", "fs", "url", "http", "stoppable", "module", "init", "fetch"] +} diff --git a/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js b/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js new file mode 100644 index 0000000..46b3f7e --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js @@ -0,0 +1,19 @@ +// packages/miniflare/src/workers/cache/constants.ts +var CacheHeaders = { + NAMESPACE: "cf-cache-namespace", + STATUS: "cf-cache-status" +}; + +// packages/miniflare/src/workers/cache/cache-entry-noop.worker.ts +var cache_entry_noop_worker_default = { + async fetch(request) { + return request.method === "GET" ? new Response(null, { + status: 504, + headers: { [CacheHeaders.STATUS]: "MISS" } + }) : request.method === "PUT" ? (await request.body?.pipeTo(new WritableStream()), new Response(null, { status: 204 })) : request.method === "PURGE" ? new Response(null, { status: 404 }) : new Response(null, { status: 405 }); + } +}; +export { + cache_entry_noop_worker_default as default +}; +//# sourceMappingURL=cache-entry-noop.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js.map b/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js.map new file mode 100644 index 0000000..ad9e74e --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/cache/constants.ts", "../../../../src/workers/cache/cache-entry-noop.worker.ts"], + "mappings": ";AAAO,IAAM,eAAe;AAAA,EAC1B,WAAW;AAAA,EACX,QAAQ;AACV;;;ACDA,IAAO,kCAAyB;AAAA,EAC9B,MAAM,MAAM,SAAS;AACnB,WAAI,QAAQ,WAAW,QACd,IAAI,SAAS,MAAM;AAAA,MACxB,QAAQ;AAAA,MACR,SAAS,EAAE,CAAC,aAAa,MAAM,GAAG,OAAO;AAAA,IAC3C,CAAC,IACQ,QAAQ,WAAW,SAE5B,MAAM,QAAQ,MAAM,OAAO,IAAI,eAAe,CAAC,GACxC,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,KAChC,QAAQ,WAAW,UACrB,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,IAElC,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,EAE7C;AACF;", + "names": [] +} diff --git a/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js b/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js new file mode 100644 index 0000000..3fcefe7 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js @@ -0,0 +1,28 @@ +// packages/miniflare/src/workers/cache/cache-entry.worker.ts +import { SharedBindings } from "miniflare:shared"; + +// packages/miniflare/src/workers/cache/constants.ts +var CacheHeaders = { + NAMESPACE: "cf-cache-namespace", + STATUS: "cf-cache-status" +}, CacheBindings = { + MAYBE_JSON_CACHE_WARN_USAGE: "MINIFLARE_CACHE_WARN_USAGE" +}; + +// packages/miniflare/src/workers/cache/cache-entry.worker.ts +var cache_entry_worker_default = { + async fetch(request, env) { + let namespace = request.headers.get(CacheHeaders.NAMESPACE), name = namespace === null ? "default" : `named:${namespace}`, objectNamespace = env[SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT], id = objectNamespace.idFromName(name), stub = objectNamespace.get(id), cf = { + ...request.cf, + miniflare: { + name, + cacheWarnUsage: env[CacheBindings.MAYBE_JSON_CACHE_WARN_USAGE] + } + }; + return await stub.fetch(request, { cf }); + } +}; +export { + cache_entry_worker_default as default +}; +//# sourceMappingURL=cache-entry.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js.map b/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js.map new file mode 100644 index 0000000..49e5e4b --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache-entry.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/cache/cache-entry.worker.ts", "../../../../src/workers/cache/constants.ts"], + "mappings": ";AAAA,SAAmC,sBAAsB;;;ACAlD,IAAM,eAAe;AAAA,EAC1B,WAAW;AAAA,EACX,QAAQ;AACV,GAEa,gBAAgB;AAAA,EAC3B,6BAA6B;AAC/B;;;ADCA,IAAO,6BAA8B;AAAA,EACnC,MAAM,MAAM,SAAS,KAAK;AACxB,QAAM,YAAY,QAAQ,QAAQ,IAAI,aAAa,SAAS,GACtD,OAAO,cAAc,OAAO,YAAY,SAAS,aAEjD,kBAAkB,IAAI,eAAe,+BAA+B,GACpE,KAAK,gBAAgB,WAAW,IAAI,GACpC,OAAO,gBAAgB,IAAI,EAAE,GAC7B,KAA+C;AAAA,MACnD,GAAG,QAAQ;AAAA,MACX,WAAW;AAAA,QACT;AAAA,QACA,gBAAgB,IAAI,cAAc,2BAA2B;AAAA,MAC/D;AAAA,IACF;AACA,WAAO,MAAM,KAAK,MAAM,SAAS,EAAE,GAAkC,CAAC;AAAA,EACxE;AACF;", + "names": [] +} diff --git a/node_modules/miniflare/dist/src/workers/cache/cache.worker.js b/node_modules/miniflare/dist/src/workers/cache/cache.worker.js new file mode 100644 index 0000000..bdd258a --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache.worker.js @@ -0,0 +1,655 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from == "object" || typeof from == "function") + for (let key of __getOwnPropNames(from)) + !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + return to; +}; +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: !0 }) : target, + mod +)); +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// node_modules/http-cache-semantics/index.js +var require_http_cache_semantics = __commonJS({ + "node_modules/http-cache-semantics/index.js"(exports, module) { + "use strict"; + var statusCodeCacheableByDefault = /* @__PURE__ */ new Set([ + 200, + 203, + 204, + 206, + 300, + 301, + 404, + 405, + 410, + 414, + 501 + ]), understoodStatuses = /* @__PURE__ */ new Set([ + 200, + 203, + 204, + 300, + 301, + 302, + 303, + 307, + 308, + 404, + 405, + 410, + 414, + 501 + ]), errorStatusCodes = /* @__PURE__ */ new Set([ + 500, + 502, + 503, + 504 + ]), hopByHopHeaders = { + date: !0, + // included, because we add Age update Date + connection: !0, + "keep-alive": !0, + "proxy-authenticate": !0, + "proxy-authorization": !0, + te: !0, + trailer: !0, + "transfer-encoding": !0, + upgrade: !0 + }, excludedFromRevalidationUpdate = { + // Since the old body is reused, it doesn't make sense to change properties of the body + "content-length": !0, + "content-encoding": !0, + "transfer-encoding": !0, + "content-range": !0 + }; + function toNumberOrZero(s) { + let n = parseInt(s, 10); + return isFinite(n) ? n : 0; + } + function isErrorResponse(response) { + return response ? errorStatusCodes.has(response.status) : !0; + } + function parseCacheControl(header) { + let cc = {}; + if (!header) + return cc; + let parts = header.trim().split(/\s*,\s*/); + for (let part of parts) { + let [k, v] = part.split(/\s*=\s*/, 2); + cc[k] = v === void 0 ? !0 : v.replace(/^"|"$/g, ""); + } + return cc; + } + function formatCacheControl(cc) { + let parts = []; + for (let k in cc) { + let v = cc[k]; + parts.push(v === !0 ? k : k + "=" + v); + } + if (parts.length) + return parts.join(", "); + } + module.exports = class { + constructor(req, res, { + shared, + cacheHeuristic, + immutableMinTimeToLive, + ignoreCargoCult, + _fromObject + } = {}) { + if (_fromObject) { + this._fromObject(_fromObject); + return; + } + if (!res || !res.headers) + throw Error("Response headers missing"); + this._assertRequestHasHeaders(req), this._responseTime = this.now(), this._isShared = shared !== !1, this._cacheHeuristic = cacheHeuristic !== void 0 ? cacheHeuristic : 0.1, this._immutableMinTtl = immutableMinTimeToLive !== void 0 ? immutableMinTimeToLive : 24 * 3600 * 1e3, this._status = "status" in res ? res.status : 200, this._resHeaders = res.headers, this._rescc = parseCacheControl(res.headers["cache-control"]), this._method = "method" in req ? req.method : "GET", this._url = req.url, this._host = req.headers.host, this._noAuthorization = !req.headers.authorization, this._reqHeaders = res.headers.vary ? req.headers : null, this._reqcc = parseCacheControl(req.headers["cache-control"]), ignoreCargoCult && "pre-check" in this._rescc && "post-check" in this._rescc && (delete this._rescc["pre-check"], delete this._rescc["post-check"], delete this._rescc["no-cache"], delete this._rescc["no-store"], delete this._rescc["must-revalidate"], this._resHeaders = Object.assign({}, this._resHeaders, { + "cache-control": formatCacheControl(this._rescc) + }), delete this._resHeaders.expires, delete this._resHeaders.pragma), res.headers["cache-control"] == null && /no-cache/.test(res.headers.pragma) && (this._rescc["no-cache"] = !0); + } + now() { + return Date.now(); + } + storable() { + return !!(!this._reqcc["no-store"] && // A cache MUST NOT store a response to any request, unless: + // The request method is understood by the cache and defined as being cacheable, and + (this._method === "GET" || this._method === "HEAD" || this._method === "POST" && this._hasExplicitExpiration()) && // the response status code is understood by the cache, and + understoodStatuses.has(this._status) && // the "no-store" cache directive does not appear in request or response header fields, and + !this._rescc["no-store"] && // the "private" response directive does not appear in the response, if the cache is shared, and + (!this._isShared || !this._rescc.private) && // the Authorization header field does not appear in the request, if the cache is shared, + (!this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) && // the response either: + // contains an Expires header field, or + (this._resHeaders.expires || // contains a max-age response directive, or + // contains a s-maxage response directive and the cache is shared, or + // contains a public response directive. + this._rescc["max-age"] || this._isShared && this._rescc["s-maxage"] || this._rescc.public || // has a status code that is defined as cacheable by default + statusCodeCacheableByDefault.has(this._status))); + } + _hasExplicitExpiration() { + return this._isShared && this._rescc["s-maxage"] || this._rescc["max-age"] || this._resHeaders.expires; + } + _assertRequestHasHeaders(req) { + if (!req || !req.headers) + throw Error("Request headers missing"); + } + satisfiesWithoutRevalidation(req) { + this._assertRequestHasHeaders(req); + let requestCC = parseCacheControl(req.headers["cache-control"]); + return requestCC["no-cache"] || /no-cache/.test(req.headers.pragma) || requestCC["max-age"] && this.age() > requestCC["max-age"] || requestCC["min-fresh"] && this.timeToLive() < 1e3 * requestCC["min-fresh"] || this.stale() && !(requestCC["max-stale"] && !this._rescc["must-revalidate"] && (requestCC["max-stale"] === !0 || requestCC["max-stale"] > this.age() - this.maxAge())) ? !1 : this._requestMatches(req, !1); + } + _requestMatches(req, allowHeadMethod) { + return (!this._url || this._url === req.url) && this._host === req.headers.host && // the request method associated with the stored response allows it to be used for the presented request, and + (!req.method || this._method === req.method || allowHeadMethod && req.method === "HEAD") && // selecting header fields nominated by the stored response (if any) match those presented, and + this._varyMatches(req); + } + _allowsStoringAuthenticated() { + return this._rescc["must-revalidate"] || this._rescc.public || this._rescc["s-maxage"]; + } + _varyMatches(req) { + if (!this._resHeaders.vary) + return !0; + if (this._resHeaders.vary === "*") + return !1; + let fields = this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/); + for (let name of fields) + if (req.headers[name] !== this._reqHeaders[name]) + return !1; + return !0; + } + _copyWithoutHopByHopHeaders(inHeaders) { + let headers = {}; + for (let name in inHeaders) + hopByHopHeaders[name] || (headers[name] = inHeaders[name]); + if (inHeaders.connection) { + let tokens = inHeaders.connection.trim().split(/\s*,\s*/); + for (let name of tokens) + delete headers[name]; + } + if (headers.warning) { + let warnings = headers.warning.split(/,/).filter((warning) => !/^\s*1[0-9][0-9]/.test(warning)); + warnings.length ? headers.warning = warnings.join(",").trim() : delete headers.warning; + } + return headers; + } + responseHeaders() { + let headers = this._copyWithoutHopByHopHeaders(this._resHeaders), age = this.age(); + return age > 3600 * 24 && !this._hasExplicitExpiration() && this.maxAge() > 3600 * 24 && (headers.warning = (headers.warning ? `${headers.warning}, ` : "") + '113 - "rfc7234 5.5.4"'), headers.age = `${Math.round(age)}`, headers.date = new Date(this.now()).toUTCString(), headers; + } + /** + * Value of the Date response header or current time if Date was invalid + * @return timestamp + */ + date() { + let serverDate = Date.parse(this._resHeaders.date); + return isFinite(serverDate) ? serverDate : this._responseTime; + } + /** + * Value of the Age header, in seconds, updated for the current time. + * May be fractional. + * + * @return Number + */ + age() { + let age = this._ageValue(), residentTime = (this.now() - this._responseTime) / 1e3; + return age + residentTime; + } + _ageValue() { + return toNumberOrZero(this._resHeaders.age); + } + /** + * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. + * + * For an up-to-date value, see `timeToLive()`. + * + * @return Number + */ + maxAge() { + if (!this.storable() || this._rescc["no-cache"] || this._isShared && this._resHeaders["set-cookie"] && !this._rescc.public && !this._rescc.immutable || this._resHeaders.vary === "*") + return 0; + if (this._isShared) { + if (this._rescc["proxy-revalidate"]) + return 0; + if (this._rescc["s-maxage"]) + return toNumberOrZero(this._rescc["s-maxage"]); + } + if (this._rescc["max-age"]) + return toNumberOrZero(this._rescc["max-age"]); + let defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0, serverDate = this.date(); + if (this._resHeaders.expires) { + let expires = Date.parse(this._resHeaders.expires); + return Number.isNaN(expires) || expires < serverDate ? 0 : Math.max(defaultMinTtl, (expires - serverDate) / 1e3); + } + if (this._resHeaders["last-modified"]) { + let lastModified = Date.parse(this._resHeaders["last-modified"]); + if (isFinite(lastModified) && serverDate > lastModified) + return Math.max( + defaultMinTtl, + (serverDate - lastModified) / 1e3 * this._cacheHeuristic + ); + } + return defaultMinTtl; + } + timeToLive() { + let age = this.maxAge() - this.age(), staleIfErrorAge = age + toNumberOrZero(this._rescc["stale-if-error"]), staleWhileRevalidateAge = age + toNumberOrZero(this._rescc["stale-while-revalidate"]); + return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1e3; + } + stale() { + return this.maxAge() <= this.age(); + } + _useStaleIfError() { + return this.maxAge() + toNumberOrZero(this._rescc["stale-if-error"]) > this.age(); + } + useStaleWhileRevalidate() { + return this.maxAge() + toNumberOrZero(this._rescc["stale-while-revalidate"]) > this.age(); + } + static fromObject(obj) { + return new this(void 0, void 0, { _fromObject: obj }); + } + _fromObject(obj) { + if (this._responseTime) + throw Error("Reinitialized"); + if (!obj || obj.v !== 1) + throw Error("Invalid serialization"); + this._responseTime = obj.t, this._isShared = obj.sh, this._cacheHeuristic = obj.ch, this._immutableMinTtl = obj.imm !== void 0 ? obj.imm : 24 * 3600 * 1e3, this._status = obj.st, this._resHeaders = obj.resh, this._rescc = obj.rescc, this._method = obj.m, this._url = obj.u, this._host = obj.h, this._noAuthorization = obj.a, this._reqHeaders = obj.reqh, this._reqcc = obj.reqcc; + } + toObject() { + return { + v: 1, + t: this._responseTime, + sh: this._isShared, + ch: this._cacheHeuristic, + imm: this._immutableMinTtl, + st: this._status, + resh: this._resHeaders, + rescc: this._rescc, + m: this._method, + u: this._url, + h: this._host, + a: this._noAuthorization, + reqh: this._reqHeaders, + reqcc: this._reqcc + }; + } + /** + * Headers for sending to the origin server to revalidate stale response. + * Allows server to return 304 to allow reuse of the previous response. + * + * Hop by hop headers are always stripped. + * Revalidation headers may be added or removed, depending on request. + */ + revalidationHeaders(incomingReq) { + this._assertRequestHasHeaders(incomingReq); + let headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); + if (delete headers["if-range"], !this._requestMatches(incomingReq, !0) || !this.storable()) + return delete headers["if-none-match"], delete headers["if-modified-since"], headers; + if (this._resHeaders.etag && (headers["if-none-match"] = headers["if-none-match"] ? `${headers["if-none-match"]}, ${this._resHeaders.etag}` : this._resHeaders.etag), headers["accept-ranges"] || headers["if-match"] || headers["if-unmodified-since"] || this._method && this._method != "GET") { + if (delete headers["if-modified-since"], headers["if-none-match"]) { + let etags = headers["if-none-match"].split(/,/).filter((etag) => !/^\s*W\//.test(etag)); + etags.length ? headers["if-none-match"] = etags.join(",").trim() : delete headers["if-none-match"]; + } + } else + this._resHeaders["last-modified"] && !headers["if-modified-since"] && (headers["if-modified-since"] = this._resHeaders["last-modified"]); + return headers; + } + /** + * Creates new CachePolicy with information combined from the previews response, + * and the new revalidation response. + * + * Returns {policy, modified} where modified is a boolean indicating + * whether the response body has been modified, and old cached body can't be used. + * + * @return {Object} {policy: CachePolicy, modified: Boolean} + */ + revalidatedPolicy(request, response) { + if (this._assertRequestHasHeaders(request), this._useStaleIfError() && isErrorResponse(response)) + return { + modified: !1, + matches: !1, + policy: this + }; + if (!response || !response.headers) + throw Error("Response headers missing"); + let matches = !1; + if (response.status !== void 0 && response.status != 304 ? matches = !1 : response.headers.etag && !/^\s*W\//.test(response.headers.etag) ? matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//, "") === response.headers.etag : this._resHeaders.etag && response.headers.etag ? matches = this._resHeaders.etag.replace(/^\s*W\//, "") === response.headers.etag.replace(/^\s*W\//, "") : this._resHeaders["last-modified"] ? matches = this._resHeaders["last-modified"] === response.headers["last-modified"] : !this._resHeaders.etag && !this._resHeaders["last-modified"] && !response.headers.etag && !response.headers["last-modified"] && (matches = !0), !matches) + return { + policy: new this.constructor(request, response), + // Client receiving 304 without body, even if it's invalid/mismatched has no option + // but to reuse a cached body. We don't have a good way to tell clients to do + // error recovery in such case. + modified: response.status != 304, + matches: !1 + }; + let headers = {}; + for (let k in this._resHeaders) + headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k]; + let newResponse = Object.assign({}, response, { + status: this._status, + method: this._method, + headers + }); + return { + policy: new this.constructor(request, newResponse, { + shared: this._isShared, + cacheHeuristic: this._cacheHeuristic, + immutableMinTimeToLive: this._immutableMinTtl + }), + modified: !1, + matches: !0 + }; + } + }; + } +}); + +// packages/miniflare/src/workers/cache/cache.worker.ts +var import_http_cache_semantics = __toESM(require_http_cache_semantics()); +import assert from "node:assert"; +import { Buffer as Buffer2 } from "node:buffer"; +import { + DeferredPromise, + GET, + KeyValueStorage, + LogLevel, + MiniflareDurableObject, + PURGE, + PUT, + parseRanges +} from "miniflare:shared"; + +// packages/miniflare/src/workers/kv/constants.ts +import { testRegExps } from "miniflare:shared"; +var KVLimits = { + MIN_CACHE_TTL: 60, + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 512, + MAX_VALUE_SIZE: 25 * 1024 * 1024, + MAX_VALUE_SIZE_TEST: 1024, + MAX_METADATA_SIZE: 1024 +}; +var SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/"; +function isSitesRequest(request) { + return new URL(request.url).pathname.startsWith(`/${SITES_NO_CACHE_PREFIX}`); +} + +// packages/miniflare/src/workers/cache/errors.worker.ts +import { HttpError } from "miniflare:shared"; + +// packages/miniflare/src/workers/cache/constants.ts +var CacheHeaders = { + NAMESPACE: "cf-cache-namespace", + STATUS: "cf-cache-status" +}; + +// packages/miniflare/src/workers/cache/errors.worker.ts +var CacheError = class extends HttpError { + constructor(code, message, headers = []) { + super(code, message); + this.headers = headers; + } + toResponse() { + return new Response(null, { + status: this.code, + headers: this.headers + }); + } + context(info) { + return this.message += ` (${info})`, this; + } +}, StorageFailure = class extends CacheError { + constructor() { + super(413, "Cache storage failed"); + } +}, PurgeFailure = class extends CacheError { + constructor() { + super(404, "Couldn't find asset to purge"); + } +}, CacheMiss = class extends CacheError { + constructor() { + super( + // workerd ignores this, but it's the correct status code + 504, + "Asset not found in cache", + [[CacheHeaders.STATUS, "MISS"]] + ); + } +}, RangeNotSatisfiable = class extends CacheError { + constructor(size) { + super(416, "Range not satisfiable", [ + ["Content-Range", `bytes */${size}`], + [CacheHeaders.STATUS, "HIT"] + ]); + } +}; + +// packages/miniflare/src/workers/cache/cache.worker.ts +function getCacheKey(req) { + return req.cf?.cacheKey ? String(req.cf?.cacheKey) : req.url; +} +function getExpiration(timers, req, res) { + let reqHeaders = normaliseHeaders(req.headers); + delete reqHeaders["cache-control"]; + let resHeaders = normaliseHeaders(res.headers); + resHeaders["cache-control"]?.toLowerCase().includes("private=set-cookie") && (resHeaders["cache-control"] = resHeaders["cache-control"]?.toLowerCase().replace(/private=set-cookie;?/i, ""), delete resHeaders["set-cookie"]); + let cacheReq = { + url: req.url, + // If a request gets to the Cache service, it's method will be GET. See README.md for details + method: "GET", + headers: reqHeaders + }, cacheRes = { + status: res.status, + headers: resHeaders + }, originalNow = import_http_cache_semantics.default.prototype.now; + import_http_cache_semantics.default.prototype.now = timers.now; + try { + let policy = new import_http_cache_semantics.default(cacheReq, cacheRes, { shared: !0 }); + return { + // Check if the request & response is cacheable + storable: policy.storable() && !("set-cookie" in resHeaders), + expiration: policy.timeToLive(), + // Cache Policy Headers is typed as [header: string]: string | string[] | undefined + // It's safe to ignore the undefined here, which is what casting to HeadersInit does + headers: policy.responseHeaders() + }; + } finally { + import_http_cache_semantics.default.prototype.now = originalNow; + } +} +function normaliseHeaders(headers) { + let result = {}; + for (let [key, value] of headers) + result[key.toLowerCase()] = value; + return result; +} +var etagRegexp = /^(W\/)?"(.+)"$/; +function parseETag(value) { + return etagRegexp.exec(value.trim())?.[2] ?? void 0; +} +var utcDateRegexp = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d\d (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d\d\d\d \d\d:\d\d:\d\d GMT$/; +function parseUTCDate(value) { + return utcDateRegexp.test(value) ? Date.parse(value) : NaN; +} +function getMatchResponse(reqHeaders, res) { + let reqIfNoneMatchHeader = reqHeaders.get("If-None-Match"), resETagHeader = res.headers.get("ETag"); + if (reqIfNoneMatchHeader !== null && resETagHeader !== null) { + let resETag = parseETag(resETagHeader); + if (resETag !== void 0) { + if (reqIfNoneMatchHeader.trim() === "*") + return new Response(null, { status: 304, headers: res.headers }); + for (let reqIfNoneMatch of reqIfNoneMatchHeader.split(",")) + if (resETag === parseETag(reqIfNoneMatch)) + return new Response(null, { status: 304, headers: res.headers }); + } + } + let reqIfModifiedSinceHeader = reqHeaders.get("If-Modified-Since"), resLastModifiedHeader = res.headers.get("Last-Modified"); + if (reqIfModifiedSinceHeader !== null && resLastModifiedHeader !== null) { + let reqIfModifiedSince = parseUTCDate(reqIfModifiedSinceHeader); + if (parseUTCDate(resLastModifiedHeader) <= reqIfModifiedSince) + return new Response(null, { status: 304, headers: res.headers }); + } + if (res.ranges.length > 0) + if (res.status = 206, res.ranges.length > 1) + assert(!(res.body instanceof ReadableStream)), res.headers.set("Content-Type", res.body.multipartContentType); + else { + let { start, end } = res.ranges[0]; + res.headers.set( + "Content-Range", + `bytes ${start}-${end}/${res.totalSize}` + ), res.headers.set("Content-Length", `${end - start + 1}`); + } + return res.body instanceof ReadableStream || (res.body = res.body.body), new Response(res.body, { status: res.status, headers: res.headers }); +} +var CR = "\r".charCodeAt(0), LF = ` +`.charCodeAt(0), STATUS_REGEXP = /^HTTP\/\d(?:\.\d)? (?\d+) (?.*)$/; +async function parseHttpResponse(stream) { + let buffer = Buffer2.alloc(0), blankLineIndex = -1; + for await (let chunk of stream.values({ preventCancel: !0 })) + if (buffer = Buffer2.concat([buffer, chunk]), blankLineIndex = buffer.findIndex( + (_value, index) => buffer[index] === CR && buffer[index + 1] === LF && buffer[index + 2] === CR && buffer[index + 3] === LF + ), blankLineIndex !== -1) + break; + assert(blankLineIndex !== -1, "Expected to find blank line in HTTP message"); + let rawStatusHeaders = buffer.subarray(0, blankLineIndex).toString(), [rawStatus, ...rawHeaders] = rawStatusHeaders.split(`\r +`), statusMatch = rawStatus.match(STATUS_REGEXP); + assert( + statusMatch?.groups != null, + `Expected first line ${JSON.stringify(rawStatus)} to be HTTP status line` + ); + let { rawStatusCode, statusText } = statusMatch.groups, statusCode = parseInt(rawStatusCode), headers = rawHeaders.map((rawHeader) => { + let index = rawHeader.indexOf(":"); + return [ + rawHeader.substring(0, index), + rawHeader.substring(index + 1).trim() + ]; + }), prefix = buffer.subarray( + blankLineIndex + 4 + /* "\r\n\r\n" */ + ), { readable, writable } = new IdentityTransformStream(), writer = writable.getWriter(); + return writer.write(prefix).then(() => (writer.releaseLock(), stream.pipeTo(writable))).catch((e) => console.error("Error writing HTTP body:", e)), new Response(readable, { status: statusCode, statusText, headers }); +} +var SizingStream = class extends TransformStream { + size; + constructor() { + let sizePromise = new DeferredPromise(), size = 0; + super({ + transform(chunk, controller) { + size += chunk.byteLength, controller.enqueue(chunk); + }, + flush() { + sizePromise.resolve(size); + } + }), this.size = sizePromise; + } +}, CacheObject = class extends MiniflareDurableObject { + #warnedUsage = !1; + async #maybeWarnUsage(request) { + !this.#warnedUsage && request.cf?.miniflare?.cacheWarnUsage === !0 && (this.#warnedUsage = !0, await this.logWithLevel( + LogLevel.WARN, + "Cache operations will have no impact if you deploy to a workers.dev subdomain!" + )); + } + #storage; + get storage() { + return this.#storage ??= new KeyValueStorage(this); + } + match = async (req) => { + await this.#maybeWarnUsage(req); + let cacheKey = getCacheKey(req); + if (isSitesRequest(req)) + throw new CacheMiss(); + let resHeaders, resRanges, cached = await this.storage.get(cacheKey, ({ size, headers }) => { + resHeaders = new Headers(headers); + let contentType = resHeaders.get("Content-Type"), rangeHeader = req.headers.get("Range"); + if (rangeHeader !== null && (resRanges = parseRanges(rangeHeader, size), resRanges === void 0)) + throw new RangeNotSatisfiable(size); + return { + ranges: resRanges, + contentLength: size, + contentType: contentType ?? void 0 + }; + }); + if (cached?.metadata === void 0) + throw new CacheMiss(); + return assert(resHeaders !== void 0), resHeaders.set("CF-Cache-Status", "HIT"), resRanges ??= [], getMatchResponse(req.headers, { + status: cached.metadata.status, + headers: resHeaders, + ranges: resRanges, + body: cached.value, + totalSize: cached.metadata.size + }); + }; + put = async (req) => { + await this.#maybeWarnUsage(req); + let cacheKey = getCacheKey(req); + if (isSitesRequest(req)) + throw new CacheMiss(); + assert(req.body !== null); + let res = await parseHttpResponse(req.body), body = res.body; + assert(body !== null); + let { storable, expiration, headers } = getExpiration( + this.timers, + req, + res + ); + if (!storable) { + try { + await body.pipeTo(new WritableStream()); + } catch { + } + throw new StorageFailure(); + } + let contentLength = parseInt(res.headers.get("Content-Length")), sizePromise; + if (Number.isNaN(contentLength)) { + let stream = new SizingStream(); + body = body.pipeThrough(stream), sizePromise = stream.size; + } else + sizePromise = Promise.resolve(contentLength); + let metadata = sizePromise.then((size) => ({ + headers: Object.entries(headers), + status: res.status, + size + })); + return await this.storage.put({ + key: cacheKey, + value: body, + expiration: this.timers.now() + expiration, + metadata + }), new Response(null, { status: 204 }); + }; + delete = async (req) => { + await this.#maybeWarnUsage(req); + let cacheKey = getCacheKey(req); + if (!await this.storage.delete(cacheKey)) + throw new PurgeFailure(); + return new Response(null); + }; +}; +__decorateClass([ + GET() +], CacheObject.prototype, "match", 2), __decorateClass([ + PUT() +], CacheObject.prototype, "put", 2), __decorateClass([ + PURGE() +], CacheObject.prototype, "delete", 2); +export { + CacheObject, + parseHttpResponse +}; +//# sourceMappingURL=cache.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/cache/cache.worker.js.map b/node_modules/miniflare/dist/src/workers/cache/cache.worker.js.map new file mode 100644 index 0000000..db51edc --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/cache/cache.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../../../node_modules/http-cache-semantics/index.js", "../../../../src/workers/cache/cache.worker.ts", "../../../../src/workers/kv/constants.ts", "../../../../src/workers/cache/errors.worker.ts", "../../../../src/workers/cache/constants.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAM,+BAA+B,oBAAI,IAAI;AAAA,MACzC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACJ,CAAC,GAGK,qBAAqB,oBAAI,IAAI;AAAA,MAC/B;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACJ,CAAC,GAEK,mBAAmB,oBAAI,IAAI;AAAA,MAC7B;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACJ,CAAC,GAEK,kBAAkB;AAAA,MACpB,MAAM;AAAA;AAAA,MACN,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,sBAAsB;AAAA,MACtB,uBAAuB;AAAA,MACvB,IAAI;AAAA,MACJ,S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lBM,YAmBX,wBA8CA;AAAA,EADC,IAAI;AAAA,GAhEM,YAiEX,sBAwDA;AAAA,EADC,MAAM;AAAA,GAxHI,YAyHX;", + "names": ["Buffer", "CachePolicy", "Buffer"] +} diff --git a/node_modules/miniflare/dist/src/workers/core/entry.worker.js b/node_modules/miniflare/dist/src/workers/core/entry.worker.js new file mode 100644 index 0000000..d09861b --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/core/entry.worker.js @@ -0,0 +1,845 @@ +// node_modules/kleur/colors.mjs +var FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY = !0; +typeof process < "u" && ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}, isTTY = process.stdout && process.stdout.isTTY); +var $ = { + enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY) +}; +function init(x, y) { + let rgx = new RegExp(`\\x1b\\[${y}m`, "g"), open = `\x1B[${x}m`, close = `\x1B[${y}m`; + return function(txt) { + return !$.enabled || txt == null ? txt : open + (~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close; + }; +} +var reset = init(0, 0), bold = init(1, 22), dim = init(2, 22), italic = init(3, 23), underline = init(4, 24), inverse = init(7, 27), hidden = init(8, 28), strikethrough = init(9, 29), black = init(30, 39), red = init(31, 39), green = init(32, 39), yellow = init(33, 39), blue = init(34, 39), magenta = init(35, 39), cyan = init(36, 39), white = init(37, 39), gray = init(90, 39), grey = init(90, 39), bgBlack = init(40, 49), bgRed = init(41, 49), bgGreen = init(42, 49), bgYellow = init(43, 49), bgBlue = init(44, 49), bgMagenta = init(45, 49), bgCyan = init(46, 49), bgWhite = init(47, 49); + +// packages/miniflare/src/workers/core/entry.worker.ts +import { LogLevel, SharedHeaders } from "miniflare:shared"; + +// packages/miniflare/src/workers/core/constants.ts +var CoreHeaders = { + CUSTOM_SERVICE: "MF-Custom-Service", + ORIGINAL_URL: "MF-Original-URL", + ERROR_STACK: "MF-Experimental-Error-Stack", + ROUTE_OVERRIDE: "MF-Route-Override", + // API Proxy + OP: "MF-Op", + OP_TARGET: "MF-Op-Target", + OP_KEY: "MF-Op-Key", + OP_SYNC: "MF-Op-Sync", + OP_STRINGIFIED_SIZE: "MF-Op-Stringified-Size", + OP_RESULT_TYPE: "MF-Op-Result-Type" +}, CoreBindings = { + SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK", + SERVICE_USER_ROUTE_PREFIX: "MINIFLARE_USER_ROUTE_", + SERVICE_USER_FALLBACK: "MINIFLARE_USER_FALLBACK", + TEXT_CUSTOM_SERVICE: "MINIFLARE_CUSTOM_SERVICE", + TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL", + JSON_CF_BLOB: "CF_BLOB", + JSON_ROUTES: "MINIFLARE_ROUTES", + JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL", + DATA_LIVE_RELOAD_SCRIPT: "MINIFLARE_LIVE_RELOAD_SCRIPT", + DURABLE_OBJECT_NAMESPACE_PROXY: "MINIFLARE_PROXY" +}, ProxyOps = { + // Get the target or a property of the target + GET: "GET", + // Call a method on the target + CALL: "CALL", + // Remove the strong reference to the target on the "heap", allowing it to be + // garbage collected + FREE: "FREE" +}, ProxyAddresses = { + GLOBAL: 0, + // globalThis + ENV: 1, + // env + USER_START: 2 +}; +function isFetcherFetch(targetName, key) { + return (targetName === "Fetcher" || targetName === "DurableObject") && key === "fetch"; +} +function isR2ObjectWriteHttpMetadata(targetName, key) { + return (targetName === "HeadResult" || targetName === "GetResult") && key === "writeHttpMetadata"; +} + +// packages/miniflare/src/workers/core/http.ts +var STATUS_CODES = { + 100: "Continue", + 101: "Switching Protocols", + 102: "Processing", + 103: "Early Hints", + 200: "OK", + 201: "Created", + 202: "Accepted", + 203: "Non-Authoritative Information", + 204: "No Content", + 205: "Reset Content", + 206: "Partial Content", + 207: "Multi-Status", + 208: "Already Reported", + 226: "IM Used", + 300: "Multiple Choices", + 301: "Moved Permanently", + 302: "Found", + 303: "See Other", + 304: "Not Modified", + 305: "Use Proxy", + 307: "Temporary Redirect", + 308: "Permanent Redirect", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 409: "Conflict", + 410: "Gone", + 411: "Length Required", + 412: "Precondition Failed", + 413: "Payload Too Large", + 414: "URI Too Long", + 415: "Unsupported Media Type", + 416: "Range Not Satisfiable", + 417: "Expectation Failed", + 418: "I'm a Teapot", + 421: "Misdirected Request", + 422: "Unprocessable Entity", + 423: "Locked", + 424: "Failed Dependency", + 425: "Too Early", + 426: "Upgrade Required", + 428: "Precondition Required", + 429: "Too Many Requests", + 431: "Request Header Fields Too Large", + 451: "Unavailable For Legal Reasons", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Gateway Timeout", + 505: "HTTP Version Not Supported", + 506: "Variant Also Negotiates", + 507: "Insufficient Storage", + 508: "Loop Detected", + 509: "Bandwidth Limit Exceeded", + 510: "Not Extended", + 511: "Network Authentication Required" +}; + +// packages/miniflare/src/workers/core/routing.ts +function matchRoutes(routes, url) { + for (let route of routes) { + if (route.protocol && route.protocol !== url.protocol) + continue; + if (route.allowHostnamePrefix) { + if (!url.hostname.endsWith(route.hostname)) + continue; + } else if (url.hostname !== route.hostname) + continue; + let path = url.pathname + url.search; + if (route.allowPathSuffix) { + if (!path.startsWith(route.path)) + continue; + } else if (path !== route.path) + continue; + return route.target; + } + return null; +} + +// packages/miniflare/src/workers/core/proxy.worker.ts +import assert2 from "node:assert"; + +// node_modules/devalue/src/utils.js +var escaped = { + "<": "\\u003C", + ">": "\\u003E", + "/": "\\u002F", + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + " ": "\\t", + "\0": "\\u0000", + "\u2028": "\\u2028", + "\u2029": "\\u2029" +}, DevalueError = class extends Error { + /** + * @param {string} message + * @param {string[]} keys + */ + constructor(message, keys) { + super(message), this.name = "DevalueError", this.path = keys.join(""); + } +}; +function is_primitive(thing) { + return Object(thing) !== thing; +} +var object_proto_names = Object.getOwnPropertyNames(Object.prototype).sort().join("\0"); +function is_plain_object(thing) { + let proto = Object.getPrototypeOf(thing); + return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names; +} +function get_type(thing) { + return Object.prototype.toString.call(thing).slice(8, -1); +} +function stringify_string(str) { + let result = '"'; + for (let i = 0; i < str.length; i += 1) { + let char = str.charAt(i), code = char.charCodeAt(0); + if (char === '"') + result += '\\"'; + else if (char in escaped) + result += escaped[char]; + else if (code <= 31) + result += `\\u${code.toString(16).toUpperCase().padStart(4, "0")}`; + else if (code >= 55296 && code <= 57343) { + let next = str.charCodeAt(i + 1); + code <= 56319 && next >= 56320 && next <= 57343 ? result += char + str[++i] : result += `\\u${code.toString(16).toUpperCase()}`; + } else + result += char; + } + return result += '"', result; +} + +// node_modules/devalue/src/parse.js +function parse(serialized, revivers) { + return unflatten(JSON.parse(serialized), revivers); +} +function unflatten(parsed, revivers) { + if (typeof parsed == "number") + return hydrate(parsed, !0); + if (!Array.isArray(parsed) || parsed.length === 0) + throw new Error("Invalid input"); + let values = ( + /** @type {any[]} */ + parsed + ), hydrated = Array(values.length); + function hydrate(index, standalone = !1) { + if (index === -1) + return; + if (index === -3) + return NaN; + if (index === -4) + return 1 / 0; + if (index === -5) + return -1 / 0; + if (index === -6) + return -0; + if (standalone) + throw new Error("Invalid input"); + if (index in hydrated) + return hydrated[index]; + let value = values[index]; + if (!value || typeof value != "object") + hydrated[index] = value; + else if (Array.isArray(value)) + if (typeof value[0] == "string") { + let type = value[0], reviver = revivers?.[type]; + if (reviver) + return hydrated[index] = reviver(hydrate(value[1])); + switch (type) { + case "Date": + hydrated[index] = new Date(value[1]); + break; + case "Set": + let set = /* @__PURE__ */ new Set(); + hydrated[index] = set; + for (let i = 1; i < value.length; i += 1) + set.add(hydrate(value[i])); + break; + case "Map": + let map = /* @__PURE__ */ new Map(); + hydrated[index] = map; + for (let i = 1; i < value.length; i += 2) + map.set(hydrate(value[i]), hydrate(value[i + 1])); + break; + case "RegExp": + hydrated[index] = new RegExp(value[1], value[2]); + break; + case "Object": + hydrated[index] = Object(value[1]); + break; + case "BigInt": + hydrated[index] = BigInt(value[1]); + break; + case "null": + let obj = /* @__PURE__ */ Object.create(null); + hydrated[index] = obj; + for (let i = 1; i < value.length; i += 2) + obj[value[i]] = hydrate(value[i + 1]); + break; + default: + throw new Error(`Unknown type ${type}`); + } + } else { + let array = new Array(value.length); + hydrated[index] = array; + for (let i = 0; i < value.length; i += 1) { + let n = value[i]; + n !== -2 && (array[i] = hydrate(n)); + } + } + else { + let object = {}; + hydrated[index] = object; + for (let key in value) { + let n = value[key]; + object[key] = hydrate(n); + } + } + return hydrated[index]; + } + return hydrate(0); +} + +// node_modules/devalue/src/stringify.js +function stringify(value, reducers) { + let stringified = [], indexes = /* @__PURE__ */ new Map(), custom = []; + for (let key in reducers) + custom.push({ key, fn: reducers[key] }); + let keys = [], p = 0; + function flatten(thing) { + if (typeof thing == "function") + throw new DevalueError("Cannot stringify a function", keys); + if (indexes.has(thing)) + return indexes.get(thing); + if (thing === void 0) + return -1; + if (Number.isNaN(thing)) + return -3; + if (thing === 1 / 0) + return -4; + if (thing === -1 / 0) + return -5; + if (thing === 0 && 1 / thing < 0) + return -6; + let index2 = p++; + indexes.set(thing, index2); + for (let { key, fn } of custom) { + let value2 = fn(thing); + if (value2) + return stringified[index2] = `["${key}",${flatten(value2)}]`, index2; + } + let str = ""; + if (is_primitive(thing)) + str = stringify_primitive(thing); + else + switch (get_type(thing)) { + case "Number": + case "String": + case "Boolean": + str = `["Object",${stringify_primitive(thing)}]`; + break; + case "BigInt": + str = `["BigInt",${thing}]`; + break; + case "Date": + str = `["Date","${thing.toISOString()}"]`; + break; + case "RegExp": + let { source, flags } = thing; + str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`; + break; + case "Array": + str = "["; + for (let i = 0; i < thing.length; i += 1) + i > 0 && (str += ","), i in thing ? (keys.push(`[${i}]`), str += flatten(thing[i]), keys.pop()) : str += -2; + str += "]"; + break; + case "Set": + str = '["Set"'; + for (let value2 of thing) + str += `,${flatten(value2)}`; + str += "]"; + break; + case "Map": + str = '["Map"'; + for (let [key, value2] of thing) + keys.push( + `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})` + ), str += `,${flatten(key)},${flatten(value2)}`; + str += "]"; + break; + default: + if (!is_plain_object(thing)) + throw new DevalueError( + "Cannot stringify arbitrary non-POJOs", + keys + ); + if (Object.getOwnPropertySymbols(thing).length > 0) + throw new DevalueError( + "Cannot stringify POJOs with symbolic keys", + keys + ); + if (Object.getPrototypeOf(thing) === null) { + str = '["null"'; + for (let key in thing) + keys.push(`.${key}`), str += `,${stringify_string(key)},${flatten(thing[key])}`, keys.pop(); + str += "]"; + } else { + str = "{"; + let started = !1; + for (let key in thing) + started && (str += ","), started = !0, keys.push(`.${key}`), str += `${stringify_string(key)}:${flatten(thing[key])}`, keys.pop(); + str += "}"; + } + } + return stringified[index2] = str, index2; + } + let index = flatten(value); + return index < 0 ? `${index}` : `[${stringified.join(",")}]`; +} +function stringify_primitive(thing) { + let type = typeof thing; + return type === "string" ? stringify_string(thing) : thing instanceof String ? stringify_string(thing.toString()) : thing === void 0 ? (-1).toString() : thing === 0 && 1 / thing < 0 ? (-6).toString() : type === "bigint" ? `["BigInt","${thing}"]` : String(thing); +} + +// packages/miniflare/src/workers/core/proxy.worker.ts +import { readPrefix, reduceError } from "miniflare:shared"; + +// packages/miniflare/src/workers/core/devalue.ts +import assert from "node:assert"; +import { Buffer } from "node:buffer"; +var ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS = [ + DataView, + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + BigInt64Array, + BigUint64Array +], ALLOWED_ERROR_CONSTRUCTORS = [ + EvalError, + RangeError, + ReferenceError, + SyntaxError, + TypeError, + URIError, + Error + // `Error` last so more specific error subclasses preferred +], structuredSerializableReducers = { + ArrayBuffer(value) { + if (value instanceof ArrayBuffer) + return [Buffer.from(value).toString("base64")]; + }, + ArrayBufferView(value) { + if (ArrayBuffer.isView(value)) + return [ + value.constructor.name, + value.buffer, + value.byteOffset, + value.byteLength + ]; + }, + Error(value) { + for (let ctor of ALLOWED_ERROR_CONSTRUCTORS) + if (value instanceof ctor && value.name === ctor.name) + return [value.name, value.message, value.stack, value.cause]; + if (value instanceof Error) + return ["Error", value.message, value.stack, value.cause]; + } +}, structuredSerializableRevivers = { + ArrayBuffer(value) { + assert(Array.isArray(value)); + let [encoded] = value; + assert(typeof encoded == "string"); + let view = Buffer.from(encoded, "base64"); + return view.buffer.slice( + view.byteOffset, + view.byteOffset + view.byteLength + ); + }, + ArrayBufferView(value) { + assert(Array.isArray(value)); + let [name, buffer, byteOffset, byteLength] = value; + assert(typeof name == "string"), assert(buffer instanceof ArrayBuffer), assert(typeof byteOffset == "number"), assert(typeof byteLength == "number"); + let ctor = globalThis[name]; + assert(ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.includes(ctor)); + let length = byteLength; + return "BYTES_PER_ELEMENT" in ctor && (length /= ctor.BYTES_PER_ELEMENT), new ctor(buffer, byteOffset, length); + }, + Error(value) { + assert(Array.isArray(value)); + let [name, message, stack, cause] = value; + assert(typeof name == "string"), assert(typeof message == "string"), assert(stack === void 0 || typeof stack == "string"); + let ctor = globalThis[name]; + assert(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor)); + let error = new ctor(message, { cause }); + return error.stack = stack, error; + } +}; +function createHTTPReducers(impl) { + return { + Headers(val) { + if (val instanceof impl.Headers) + return Object.fromEntries(val); + }, + Request(val) { + if (val instanceof impl.Request) + return [val.method, val.url, val.headers, val.cf, val.body]; + }, + Response(val) { + if (val instanceof impl.Response) + return [val.status, val.statusText, val.headers, val.cf, val.body]; + } + }; +} +function createHTTPRevivers(impl) { + return { + Headers(value) { + return assert(typeof value == "object" && value !== null), new impl.Headers(value); + }, + Request(value) { + assert(Array.isArray(value)); + let [method, url, headers, cf, body] = value; + return assert(typeof method == "string"), assert(typeof url == "string"), assert(headers instanceof impl.Headers), assert(body === null || impl.isReadableStream(body)), new impl.Request(url, { + method, + headers, + cf, + // @ts-expect-error `duplex` is not required by `workerd` yet + duplex: body === null ? void 0 : "half", + body + }); + }, + Response(value) { + assert(Array.isArray(value)); + let [status, statusText, headers, cf, body] = value; + return assert(typeof status == "number"), assert(typeof statusText == "string"), assert(headers instanceof impl.Headers), assert(body === null || impl.isReadableStream(body)), new impl.Response(body, { + status, + statusText, + headers, + cf + }); + } + }; +} +function stringifyWithStreams(impl, value, reducers, allowUnbufferedStream) { + let unbufferedStream, bufferPromises = [], streamReducers = { + ReadableStream(value2) { + if (impl.isReadableStream(value2)) + return allowUnbufferedStream && unbufferedStream === void 0 ? unbufferedStream = value2 : bufferPromises.push(impl.bufferReadableStream(value2)), !0; + }, + Blob(value2) { + if (value2 instanceof impl.Blob) + return bufferPromises.push(value2.arrayBuffer()), !0; + }, + ...reducers + }, stringifiedValue = stringify(value, streamReducers); + return bufferPromises.length === 0 ? { value: stringifiedValue, unbufferedStream } : Promise.all(bufferPromises).then((streamBuffers) => (streamReducers.ReadableStream = function(value2) { + if (impl.isReadableStream(value2)) + return value2 === unbufferedStream ? !0 : streamBuffers.shift(); + }, streamReducers.Blob = function(value2) { + if (value2 instanceof impl.Blob) { + let array = [streamBuffers.shift(), value2.type]; + return value2 instanceof impl.File && array.push(value2.name, value2.lastModified), array; + } + }, { value: stringify(value, streamReducers), unbufferedStream })); +} +function parseWithReadableStreams(impl, stringified, revivers) { + let streamRevivers = { + ReadableStream(value) { + return value === !0 ? (assert(stringified.unbufferedStream !== void 0), stringified.unbufferedStream) : (assert(value instanceof ArrayBuffer), impl.unbufferReadableStream(value)); + }, + Blob(value) { + if (assert(Array.isArray(value)), value.length === 2) { + let [buffer, type] = value; + assert(buffer instanceof ArrayBuffer), assert(typeof type == "string"); + let opts = {}; + return type !== "" && (opts.type = type), new impl.Blob([buffer], opts); + } else { + assert(value.length === 4); + let [buffer, type, name, lastModified] = value; + assert(buffer instanceof ArrayBuffer), assert(typeof type == "string"), assert(typeof name == "string"), assert(typeof lastModified == "number"); + let opts = { lastModified }; + return type !== "" && (opts.type = type), new impl.File([buffer], name, opts); + } + }, + ...revivers + }; + return parse(stringified.value, streamRevivers); +} + +// packages/miniflare/src/workers/core/proxy.worker.ts +var ENCODER = new TextEncoder(), DECODER = new TextDecoder(), WORKERS_PLATFORM_IMPL = { + Blob, + File, + Headers, + Request, + Response, + isReadableStream(value) { + return value instanceof ReadableStream; + }, + bufferReadableStream(stream) { + return new Response(stream).arrayBuffer(); + }, + unbufferReadableStream(buffer) { + let body = new Response(buffer).body; + return assert2(body !== null), body; + } +}, objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0"); +function isPlainObject(value) { + let proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames; +} +function getType(value) { + return Object.prototype.toString.call(value).slice(8, -1); +} +var ProxyServer = class { + // On the first `fetch()`, start a `setInterval()` to keep this Durable Object + // and its heap alive. This is required to ensure heap references stay valid + // for the lifetime of this `workerd` process (except it isn't since `workerd` + // doesn't evict Durable Objects yet :P, but it probably will soon). + anchorInterval; + nextHeapAddress = ProxyAddresses.USER_START; + heap = /* @__PURE__ */ new Map(); + reducers = { + ...structuredSerializableReducers, + ...createHTTPReducers(WORKERS_PLATFORM_IMPL), + // Corresponding revivers in `ProxyClient` + // `Native` reducer *MUST* be applied last + Native: (value) => { + let type = getType(value); + if (type === "Object" && !isPlainObject(value) || type === "Promise") { + let address = this.nextHeapAddress++; + return this.heap.set(address, value), assert2(typeof value == "object" && value !== null), [address, value.constructor.name]; + } + } + }; + revivers = { + ...structuredSerializableRevivers, + ...createHTTPRevivers(WORKERS_PLATFORM_IMPL), + // Corresponding reducers in `ProxyClient` + Native: (value) => { + assert2(Array.isArray(value)); + let [address] = value; + assert2(typeof address == "number"); + let heapValue = this.heap.get(address); + return assert2(heapValue !== void 0), heapValue instanceof Promise && this.heap.delete(address), heapValue; + } + }; + nativeReviver = { Native: this.revivers.Native }; + constructor(_state, env) { + this.heap.set(ProxyAddresses.GLOBAL, globalThis), this.heap.set(ProxyAddresses.ENV, env); + } + async fetch(request) { + this.anchorInterval ??= setInterval(() => { + }, 1e4); + try { + return await this.#fetch(request); + } catch (e) { + let error = reduceError(e); + return Response.json(error, { + status: 500, + headers: { [CoreHeaders.ERROR_STACK]: "true" } + }); + } + } + async #fetch(request) { + let opHeader = request.headers.get(CoreHeaders.OP), targetHeader = request.headers.get(CoreHeaders.OP_TARGET), keyHeader = request.headers.get(CoreHeaders.OP_KEY), allowAsync = request.headers.get(CoreHeaders.OP_SYNC) === null, argsSizeHeader = request.headers.get(CoreHeaders.OP_STRINGIFIED_SIZE), contentLengthHeader = request.headers.get("Content-Length"); + if (targetHeader === null) + return new Response(null, { status: 400 }); + if (opHeader === ProxyOps.FREE) { + let targetAddress = parseInt(targetHeader); + return assert2(!Number.isNaN(targetAddress)), this.heap.delete(targetAddress), new Response(null, { status: 204 }); + } + let target = parse( + targetHeader, + this.nativeReviver + ), targetName = target.constructor.name, status = 200, result, unbufferedRest; + if (opHeader === ProxyOps.GET) { + if (result = keyHeader === null ? target : target[keyHeader], typeof result == "function") + return new Response(null, { + status: 204, + headers: { [CoreHeaders.OP_RESULT_TYPE]: "Function" } + }); + } else if (opHeader === ProxyOps.CALL) { + if (keyHeader === null) + return new Response(null, { status: 400 }); + let func = target[keyHeader]; + if (assert2(typeof func == "function"), isFetcherFetch(targetName, keyHeader)) + return request = new Request(request), request.headers.delete(CoreHeaders.OP), request.headers.delete(CoreHeaders.OP_TARGET), request.headers.delete(CoreHeaders.OP_KEY), func.call(target, request); + let args; + if (argsSizeHeader === null || argsSizeHeader === contentLengthHeader) + args = parseWithReadableStreams( + WORKERS_PLATFORM_IMPL, + { value: await request.text() }, + this.revivers + ); + else { + let argsSize = parseInt(argsSizeHeader); + assert2(!Number.isNaN(argsSize)), assert2(request.body !== null); + let [encodedArgs, rest] = await readPrefix(request.body, argsSize); + unbufferedRest = rest; + let stringifiedArgs = DECODER.decode(encodedArgs); + args = parseWithReadableStreams( + WORKERS_PLATFORM_IMPL, + { value: stringifiedArgs, unbufferedStream: rest }, + this.revivers + ); + } + assert2(Array.isArray(args)); + try { + result = func.apply(target, args), isR2ObjectWriteHttpMetadata(targetName, keyHeader) && (result = args[0]); + } catch (e) { + status = 500, result = e; + } + } else + return new Response(null, { status: 404 }); + let headers = new Headers(); + if (allowAsync && result instanceof Promise) { + try { + result = await result; + } catch (e) { + status = 500, result = e; + } + headers.append(CoreHeaders.OP_RESULT_TYPE, "Promise"); + } + if (unbufferedRest !== void 0 && !unbufferedRest.locked) + try { + await unbufferedRest.pipeTo(new WritableStream()); + } catch { + } + if (result instanceof ReadableStream) + return headers.append(CoreHeaders.OP_RESULT_TYPE, "ReadableStream"), new Response(result, { status, headers }); + { + let stringified = await stringifyWithStreams( + WORKERS_PLATFORM_IMPL, + result, + this.reducers, + /* allowUnbufferedStream */ + allowAsync + ); + if (stringified.unbufferedStream === void 0) + return new Response(stringified.value, { status, headers }); + { + let body = new IdentityTransformStream(), encodedValue = ENCODER.encode(stringified.value), encodedSize = encodedValue.byteLength.toString(); + return headers.set(CoreHeaders.OP_STRINGIFIED_SIZE, encodedSize), this.#writeWithUnbufferedStream( + body.writable, + encodedValue, + stringified.unbufferedStream + ), new Response(body.readable, { status, headers }); + } + } + } + async #writeWithUnbufferedStream(writable, encodedValue, unbufferedStream) { + let writer = writable.getWriter(); + await writer.write(encodedValue), writer.releaseLock(), await unbufferedStream.pipeTo(writable); + } +}; + +// packages/miniflare/src/workers/core/entry.worker.ts +function getUserRequest(request, env) { + let originalUrl = request.headers.get(CoreHeaders.ORIGINAL_URL), upstreamUrl = env[CoreBindings.TEXT_UPSTREAM_URL], url = new URL(originalUrl ?? request.url); + if (upstreamUrl !== void 0) { + let path = url.pathname + url.search; + path.startsWith("/") && (path = path.substring(1)), url = new URL(path, upstreamUrl); + } + return request = new Request(url, request), request.cf === void 0 && (request = new Request(request, { cf: env[CoreBindings.JSON_CF_BLOB] })), request.headers.delete(CoreHeaders.ORIGINAL_URL), request; +} +function getTargetService(request, url, env) { + let service = env[CoreBindings.SERVICE_USER_FALLBACK], override = request.headers.get(CoreHeaders.ROUTE_OVERRIDE); + request.headers.delete(CoreHeaders.ROUTE_OVERRIDE); + let route = override ?? matchRoutes(env[CoreBindings.JSON_ROUTES], url); + return route !== null && (service = env[`${CoreBindings.SERVICE_USER_ROUTE_PREFIX}${route}`]), service; +} +function maybePrettifyError(request, response, env) { + if (response.status !== 500 || response.headers.get(CoreHeaders.ERROR_STACK) === null) + return response; + let accept = request.headers.get("Accept"), userAgent = request.headers.get("User-Agent"), headers = new Headers(); + return accept !== null && headers.set("Accept", accept), userAgent !== null && headers.set("User-Agent", userAgent), env[CoreBindings.SERVICE_LOOPBACK].fetch( + "http://localhost/core/error", + { + method: "POST", + headers, + body: response.body + } + ); +} +function maybeInjectLiveReload(response, env, ctx) { + let liveReloadScript = env[CoreBindings.DATA_LIVE_RELOAD_SCRIPT]; + if (liveReloadScript === void 0 || !response.headers.get("Content-Type")?.toLowerCase().includes("text/html")) + return response; + let headers = new Headers(response.headers), contentLength = parseInt(headers.get("content-length")); + isNaN(contentLength) || headers.set( + "content-length", + String(contentLength + liveReloadScript.byteLength) + ); + let { readable, writable } = new IdentityTransformStream(); + return ctx.waitUntil( + (async () => { + await response.body?.pipeTo(writable, { preventClose: !0 }); + let writer = writable.getWriter(); + await writer.write(liveReloadScript), await writer.close(); + })() + ), new Response(readable, { + status: response.status, + statusText: response.statusText, + headers + }); +} +function colourFromHTTPStatus(status) { + return 200 <= status && status < 300 ? green : 400 <= status && status < 500 ? yellow : 500 <= status ? red : blue; +} +function maybeLogRequest(req, res, env, ctx, startTime) { + if (env[CoreBindings.JSON_LOG_LEVEL] < LogLevel.INFO) + return; + let url = new URL(req.url), statusText = (res.statusText.trim() || STATUS_CODES[res.status]) ?? "", lines = [ + `${bold(req.method)} ${url.pathname} `, + colourFromHTTPStatus(res.status)(`${bold(res.status)} ${statusText} `), + grey(`(${Date.now() - startTime}ms)`) + ], message = reset(lines.join("")); + ctx.waitUntil( + env[CoreBindings.SERVICE_LOOPBACK].fetch("http://localhost/core/log", { + method: "POST", + headers: { [SharedHeaders.LOG_LEVEL]: LogLevel.INFO.toString() }, + body: message + }) + ); +} +function handleProxy(request, env) { + let ns = env[CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY], id = ns.idFromName(""); + return ns.get(id).fetch(request); +} +async function handleScheduled(params, service) { + let time = params.get("time"), scheduledTime = time ? new Date(parseInt(time)) : void 0, cron = params.get("cron") ?? void 0, result = await service.scheduled({ + scheduledTime, + cron + }); + return new Response(result.outcome, { + status: result.outcome === "ok" ? 200 : 500 + }); +} +var entry_worker_default = { + async fetch(request, env, ctx) { + let startTime = Date.now(); + if (request.headers.get(CoreHeaders.OP) !== null) + return handleProxy(request, env); + let isDispatchFetch = request.headers.get(CoreHeaders.ORIGINAL_URL) !== null; + request = getUserRequest(request, env); + let url = new URL(request.url), service = getTargetService(request, url, env); + if (service === void 0) + return new Response("No entrypoint worker found", { status: 404 }); + try { + if (url.pathname === "/cdn-cgi/mf/scheduled") + return await handleScheduled(url.searchParams, service); + let response = await service.fetch(request); + return isDispatchFetch || (response = await maybePrettifyError(request, response, env)), response = maybeInjectLiveReload(response, env, ctx), maybeLogRequest(request, response, env, ctx, startTime), response; + } catch (e) { + return new Response(e?.stack ?? String(e), { status: 500 }); + } + } +}; +export { + ProxyServer, + entry_worker_default as default +}; +//# sourceMappingURL=entry.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/core/entry.worker.js.map b/node_modules/miniflare/dist/src/workers/core/entry.worker.js.map new file mode 100644 index 0000000..c7de168 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/core/entry.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../../../node_modules/kleur/colors.mjs", "../../../../src/workers/core/entry.worker.ts", "../../../../src/workers/core/constants.ts", "../../../../src/workers/core/http.ts", "../../../../src/workers/core/routing.ts", "../../../../src/workers/core/proxy.worker.ts", "../../../../../../node_modules/devalue/src/utils.js", "../../../../../../node_modules/devalue/src/parse.js", "../../../../../../node_modules/devalue/src/stringify.js", "../../../../src/workers/core/devalue.ts"], + "mappings": ";AAAA,IAAI,aAAa,qBAAqB,UAAU,MAAM,QAAM;AACxD,OAAO,UAAY,QACrB,EAAE,aAAa,qBAAqB,UAAU,KAAK,IAAI,QAAQ,OAAO,CAAC,GACxE,QAAQ,QAAQ,UAAU,QAAQ,OAAO;AAGnC,IAAM,IAAI;AAAA,EAChB,SAAS,CAAC,uBAAuB,YAAY,QAAQ,SAAS,WAC7D,eAAe,QAAQ,gBAAgB,OAAO;AAEhD;AAEA,SAAS,KAAK,GAAG,GAAG;AACnB,MAAI,MAAM,IAAI,OAAO,WAAW,MAAM,GAAG,GACrC,OAAO,QAAQ,MAAM,QAAQ,QAAQ;AAEzC,SAAO,SAAU,KAAK;AACrB,WAAI,CAAC,EAAE,WAAW,OAAO,OAAa,MAC/B,QAAU,EAAE,KAAG,KAAK,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,QAAQ,IAAI,IAAI,OAAO;AAAA,EACrF;AACD;AAGO,IAAM,QAAQ,KAAK,GAAG,CAAC,GACjB,OAAO,KAAK,GAAG,EAAE,GACjB,MAAM,KAAK,GAAG,EAAE,GAChB,SAAS,KAAK,GAAG,EAAE,GACnB,YAAY,KAAK,GAAG,EAAE,GACtB,UAAU,KAA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8B;AAAA,EACnC,MAAM,MAAM,SAAS,KAAK,KAAK;AAC7B,QAAM,YAAY,KAAK,IAAI;AAI3B,QADgB,QAAQ,QAAQ,IAAI,YAAY,EAAE,MAAM;AAC3C,aAAO,YAAY,SAAS,GAAG;AAK5C,QAAM,kBACJ,QAAQ,QAAQ,IAAI,YAAY,YAAY,MAAM;AAEpD,cAAU,eAAe,SAAS,GAAG;AACrC,QAAM,MAAM,IAAI,IAAI,QAAQ,GAAG,GACzB,UAAU,iBAAiB,SAAS,KAAK,GAAG;AAClD,QAAI,YAAY;AACd,aAAO,IAAI,SAAS,8BAA8B,EAAE,QAAQ,IAAI,CAAC;AAGnE,QAAI;AACF,UAAI,IAAI,aAAa;AACnB,eAAO,MAAM,gBAAgB,IAAI,cAAc,OAAO;AAGxD,UAAI,WAAW,MAAM,QAAQ,MAAM,OAAO;AAC1C,aAAK,oBACH,WAAW,MAAM,mBAAmB,SAAS,UAAU,GAAG,IAE5D,WAAW,sBAAsB,UAAU,KAAK,GAAG,GACnD,gBAAgB,SAAS,UAAU,KAAK,KAAK,SAAS,GAC/C;AAAA,IACT,SAAS,GAAP;AACA,aAAO,IAAI,SAAS,GAAG,SAAS,OAAO,CAAC,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC5D;AAAA,EACF;AACF;", + "names": ["assert", "index", "value", "value", "assert"] +} diff --git a/node_modules/miniflare/dist/src/workers/d1/database.worker.js b/node_modules/miniflare/dist/src/workers/d1/database.worker.js new file mode 100644 index 0000000..c2fbc92 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/d1/database.worker.js @@ -0,0 +1,113 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// packages/miniflare/src/workers/d1/database.worker.ts +import assert from "node:assert"; +import { + HttpError, + MiniflareDurableObject, + POST, + all, + get, + viewToBuffer +} from "miniflare:shared"; +import { z } from "miniflare:zod"; +var D1ValueSchema = z.union([ + z.number(), + z.string(), + z.null(), + z.number().array() +]), D1QuerySchema = z.object({ + sql: z.string(), + params: z.array(D1ValueSchema).nullable().optional() +}), D1QueriesSchema = z.union([D1QuerySchema, z.array(D1QuerySchema)]), served_by = "miniflare.db", D1Error = class extends HttpError { + constructor(cause) { + super(500); + this.cause = cause; + } + toResponse() { + let response = { success: !1, error: typeof this.cause == "object" && this.cause !== null && "message" in this.cause && typeof this.cause.message == "string" ? this.cause.message : String(this.cause) }; + return Response.json(response); + } +}; +function convertParams(params) { + return (params ?? []).map( + (param) => ( + // If `param` is an array, assume it's a byte array + Array.isArray(param) ? viewToBuffer(new Uint8Array(param)) : param + ) + ); +} +function convertResults(rows) { + return rows.map( + (row) => Object.fromEntries( + Object.entries(row).map(([key, value]) => { + let normalised; + return value instanceof ArrayBuffer ? normalised = Array.from(new Uint8Array(value)) : normalised = value, [key, normalised]; + }) + ) + ); +} +function sqlStmts(db) { + return { + getChanges: db.prepare( + "SELECT total_changes() AS totalChanges, last_insert_rowid() AS lastRowId" + ) + }; +} +var D1DatabaseObject = class extends MiniflareDurableObject { + #stmts; + constructor(state, env) { + super(state, env), this.#stmts = sqlStmts(this.db); + } + #changes() { + let changes = get(this.#stmts.getChanges()); + return assert(changes !== void 0), changes; + } + #query = (query) => { + let beforeTime = performance.now(), beforeSize = this.state.storage.sql.databaseSize, beforeChanges = this.#changes(), params = convertParams(query.params ?? []), cursor = this.db.prepare(query.sql)(...params), results = convertResults(all(cursor)), afterTime = performance.now(), afterSize = this.state.storage.sql.databaseSize, afterChanges = this.#changes(), duration = afterTime - beforeTime, changes = afterChanges.totalChanges - beforeChanges.totalChanges, hasChanges = changes !== 0, lastRowChanged = afterChanges.lastRowId !== beforeChanges.lastRowId, changed = hasChanges || lastRowChanged || afterSize !== beforeSize; + return { + success: !0, + results, + meta: { + served_by, + duration, + changes, + last_row_id: afterChanges.lastRowId, + changed_db: changed, + size_after: afterSize + } + }; + }; + #txn(queries) { + if (queries = queries.filter( + (query) => query.sql.replace(/^\s+--.*/gm, "").trim().length > 0 + ), queries.length === 0) { + let error = new Error("No SQL statements detected."); + throw new D1Error(error); + } + try { + return this.state.storage.transactionSync(() => queries.map(this.#query)); + } catch (e) { + throw new D1Error(e); + } + } + queryExecute = async (req) => { + let queries = D1QueriesSchema.parse(await req.json()); + return Array.isArray(queries) || (queries = [queries]), Response.json(this.#txn(queries)); + }; +}; +__decorateClass([ + POST("/query"), + POST("/execute") +], D1DatabaseObject.prototype, "queryExecute", 2); +export { + D1DatabaseObject, + D1Error +}; +//# sourceMappingURL=database.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/d1/database.worker.js.map b/node_modules/miniflare/dist/src/workers/d1/database.worker.js.map new file mode 100644 index 0000000..87681a5 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/d1/database.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/d1/database.worker.ts"], + "mappings": ";;;;;;;;;AAAA,OAAO,YAAY;AACnB;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAElB,IAAM,gBAAgB,EAAE,MAAM;AAAA,EAC5B,EAAE,OAAO;AAAA,EACT,EAAE,OAAO;AAAA,EACT,EAAE,KAAK;AAAA,EACP,EAAE,OAAO,EAAE,MAAM;AACnB,CAAC,GAGK,gBAAgB,EAAE,OAAO;AAAA,EAC7B,KAAK,EAAE,OAAO;AAAA,EACd,QAAQ,EAAE,MAAM,aAAa,EAAE,SAAS,EAAE,SAAS;AACrD,CAAC,GAEK,kBAAkB,EAAE,MAAM,CAAC,eAAe,EAAE,MAAM,aAAa,CAAC,CAAC,GAEjE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AA,EACzC;AACF;AALE;AAAA,EAFC,KAAK,QAAQ;AAAA,EACb,KAAK,UAAU;AAAA,GApEL,iBAqEX;", + "names": [] +} diff --git a/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js b/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js new file mode 100644 index 0000000..98e414a --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js @@ -0,0 +1,254 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// packages/miniflare/src/workers/kv/namespace.worker.ts +import assert from "node:assert"; +import { + DELETE, + DeferredPromise, + GET, + HttpError as HttpError2, + KeyValueStorage, + MiniflareDurableObject, + PUT, + maybeApply +} from "miniflare:shared"; + +// packages/miniflare/src/workers/kv/constants.ts +import { testRegExps } from "miniflare:shared"; +var KVLimits = { + MIN_CACHE_TTL: 60, + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 512, + MAX_VALUE_SIZE: 25 * 1024 * 1024, + MAX_VALUE_SIZE_TEST: 1024, + MAX_METADATA_SIZE: 1024 +}, KVParams = { + URL_ENCODED: "urlencoded", + CACHE_TTL: "cache_ttl", + EXPIRATION: "expiration", + EXPIRATION_TTL: "expiration_ttl", + LIST_LIMIT: "key_count_limit", + LIST_PREFIX: "prefix", + LIST_CURSOR: "cursor" +}, KVHeaders = { + EXPIRATION: "CF-Expiration", + METADATA: "CF-KV-Metadata" +}; + +// packages/miniflare/src/workers/kv/validator.worker.ts +import { Buffer as Buffer2 } from "node:buffer"; +import { HttpError } from "miniflare:shared"; +function decodeKey({ key }, query) { + if (query.get(KVParams.URL_ENCODED)?.toLowerCase() !== "true") + return key; + try { + return decodeURIComponent(key); + } catch (e) { + throw e instanceof URIError ? new HttpError(400, "Could not URL-decode key name") : e; + } +} +function validateKey(key) { + if (key === "") + throw new HttpError(400, "Key names must not be empty"); + if (key === "." || key === "..") + throw new HttpError( + 400, + `Illegal key name "${key}". Please use a different name.` + ); + validateKeyLength(key); +} +function validateKeyLength(key) { + let keyLength = Buffer2.byteLength(key); + if (keyLength > KVLimits.MAX_KEY_SIZE) + throw new HttpError( + 414, + `UTF-8 encoded length of ${keyLength} exceeds key length limit of ${KVLimits.MAX_KEY_SIZE}.` + ); +} +function validateGetOptions(key, options) { + validateKey(key); + let cacheTtl = options?.cacheTtl; + if (cacheTtl !== void 0 && (isNaN(cacheTtl) || cacheTtl < KVLimits.MIN_CACHE_TTL)) + throw new HttpError( + 400, + `Invalid ${KVParams.CACHE_TTL} of ${cacheTtl}. Cache TTL must be at least ${KVLimits.MIN_CACHE_TTL}.` + ); +} +function validatePutOptions(key, options) { + let { now, rawExpiration, rawExpirationTtl, rawMetadata } = options; + validateKey(key); + let expiration; + if (rawExpirationTtl !== null) { + let expirationTtl = parseInt(rawExpirationTtl); + if (Number.isNaN(expirationTtl) || expirationTtl <= 0) + throw new HttpError( + 400, + `Invalid ${KVParams.EXPIRATION_TTL} of ${rawExpirationTtl}. Please specify integer greater than 0.` + ); + if (expirationTtl < KVLimits.MIN_CACHE_TTL) + throw new HttpError( + 400, + `Invalid ${KVParams.EXPIRATION_TTL} of ${rawExpirationTtl}. Expiration TTL must be at least ${KVLimits.MIN_CACHE_TTL}.` + ); + expiration = now + expirationTtl; + } else if (rawExpiration !== null) { + if (expiration = parseInt(rawExpiration), Number.isNaN(expiration) || expiration <= now) + throw new HttpError( + 400, + `Invalid ${KVParams.EXPIRATION} of ${rawExpiration}. Please specify integer greater than the current number of seconds since the UNIX epoch.` + ); + if (expiration < now + KVLimits.MIN_CACHE_TTL) + throw new HttpError( + 400, + `Invalid ${KVParams.EXPIRATION} of ${rawExpiration}. Expiration times must be at least ${KVLimits.MIN_CACHE_TTL} seconds in the future.` + ); + } + let metadata; + if (rawMetadata !== null) { + let metadataLength = Buffer2.byteLength(rawMetadata); + if (metadataLength > KVLimits.MAX_METADATA_SIZE) + throw new HttpError( + 413, + `Metadata length of ${metadataLength} exceeds limit of ${KVLimits.MAX_METADATA_SIZE}.` + ); + metadata = JSON.parse(rawMetadata); + } + return { expiration, metadata }; +} +function decodeListOptions(url) { + let limitParam = url.searchParams.get(KVParams.LIST_LIMIT), limit = limitParam === null ? KVLimits.MAX_LIST_KEYS : parseInt(limitParam), prefix = url.searchParams.get(KVParams.LIST_PREFIX) ?? void 0, cursor = url.searchParams.get(KVParams.LIST_CURSOR) ?? void 0; + return { limit, prefix, cursor }; +} +function validateListOptions(options) { + let limit = options.limit; + if (limit !== void 0) { + if (isNaN(limit) || limit < 1) + throw new HttpError( + 400, + `Invalid ${KVParams.LIST_LIMIT} of ${limit}. Please specify an integer greater than 0.` + ); + if (limit > KVLimits.MAX_LIST_KEYS) + throw new HttpError( + 400, + `Invalid ${KVParams.LIST_LIMIT} of ${limit}. Please specify an integer less than ${KVLimits.MAX_LIST_KEYS}.` + ); + } + let prefix = options.prefix; + prefix != null && validateKeyLength(prefix); +} + +// packages/miniflare/src/workers/kv/namespace.worker.ts +function createMaxValueSizeError(length, maxValueSize) { + return new HttpError2( + 413, + `Value length of ${length} exceeds limit of ${maxValueSize}.` + ); +} +var MaxLengthStream = class extends TransformStream { + signal; + length; + constructor(maxLength) { + let abortController = new AbortController(), lengthPromise = new DeferredPromise(), length = 0; + super({ + transform(chunk, controller) { + length += chunk.byteLength, length <= maxLength ? controller.enqueue(chunk) : abortController.signal.aborted || abortController.abort(); + }, + flush() { + lengthPromise.resolve(length); + } + }), this.signal = abortController.signal, this.length = lengthPromise; + } +}; +function millisToSeconds(millis) { + return Math.floor(millis / 1e3); +} +function secondsToMillis(seconds) { + return seconds * 1e3; +} +var KVNamespaceObject = class extends MiniflareDurableObject { + #storage; + get storage() { + return this.#storage ??= new KeyValueStorage(this); + } + get = async (req, params, url) => { + let key = decodeKey(params, url.searchParams), cacheTtlParam = url.searchParams.get(KVParams.CACHE_TTL), cacheTtl = cacheTtlParam === null ? void 0 : parseInt(cacheTtlParam); + validateGetOptions(key, { cacheTtl }); + let entry = await this.storage.get(key); + if (entry === null) + throw new HttpError2(404, "Not Found"); + let headers = new Headers(); + return entry.expiration !== void 0 && headers.set( + KVHeaders.EXPIRATION, + millisToSeconds(entry.expiration).toString() + ), entry.metadata !== void 0 && headers.set(KVHeaders.METADATA, JSON.stringify(entry.metadata)), new Response(entry.value, { headers }); + }; + put = async (req, params, url) => { + let key = decodeKey(params, url.searchParams), rawExpiration = url.searchParams.get(KVParams.EXPIRATION), rawExpirationTtl = url.searchParams.get(KVParams.EXPIRATION_TTL), rawMetadata = req.headers.get(KVHeaders.METADATA), now = millisToSeconds(this.timers.now()), { expiration, metadata } = validatePutOptions(key, { + now, + rawExpiration, + rawExpirationTtl, + rawMetadata + }), value = req.body; + assert(value !== null); + let contentLength = parseInt(req.headers.get("Content-Length")), valueLengthHint = Number.isNaN(contentLength) ? void 0 : contentLength, maxValueSize = this.beingTested ? KVLimits.MAX_VALUE_SIZE_TEST : KVLimits.MAX_VALUE_SIZE, maxLengthStream; + if (valueLengthHint !== void 0 && valueLengthHint > maxValueSize) + throw createMaxValueSizeError(valueLengthHint, maxValueSize); + maxLengthStream = new MaxLengthStream(maxValueSize), value = value.pipeThrough(maxLengthStream); + try { + await this.storage.put({ + key, + value, + expiration: maybeApply(secondsToMillis, expiration), + metadata, + signal: maxLengthStream?.signal + }); + } catch (e) { + if (typeof e == "object" && e !== null && "name" in e && e.name === "AbortError") { + assert(maxLengthStream !== void 0); + let length = await maxLengthStream.length; + throw createMaxValueSizeError(length, maxValueSize); + } else + throw e; + } + return new Response(); + }; + delete = async (req, params, url) => { + let key = decodeKey(params, url.searchParams); + return validateKey(key), await this.storage.delete(key), new Response(); + }; + list = async (req, params, url) => { + let options = decodeListOptions(url); + validateListOptions(options); + let res = await this.storage.list(options), keys = res.keys.map((key) => ({ + name: key.key, + expiration: maybeApply(millisToSeconds, key.expiration), + // workerd expects metadata to be a JSON-serialised string + metadata: maybeApply(JSON.stringify, key.metadata) + })), result; + return res.cursor === void 0 ? result = { keys, list_complete: !0, cacheStatus: null } : result = { + keys, + list_complete: !1, + cursor: res.cursor, + cacheStatus: null + }, Response.json(result); + }; +}; +__decorateClass([ + GET("/:key") +], KVNamespaceObject.prototype, "get", 2), __decorateClass([ + PUT("/:key") +], KVNamespaceObject.prototype, "put", 2), __decorateClass([ + DELETE("/:key") +], KVNamespaceObject.prototype, "delete", 2), __decorateClass([ + GET("/") +], KVNamespaceObject.prototype, "list", 2); +export { + KVNamespaceObject +}; +//# sourceMappingURL=namespace.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js.map b/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js.map new file mode 100644 index 0000000..ddee3bb --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/kv/namespace.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/kv/namespace.worker.ts", "../../../../src/workers/kv/constants.ts", "../../../../src/workers/kv/validator.worker.ts"], + "mappings": ";;;;;;;;;AAAA,OAAO,YAAY;AACnB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;;;ACXP,SAAyB,mBAAmB;AAErC,IAAM,WAAW;AAAA,EACtB,eAAe;AAAA,EACf,eAAe;AAAA,EACf,cAAc;AAAA,EACd,gBAAgB,KAAK,OAAO;AAAA,EAC5B,qBAAqB;AAAA,EACrB,mBAAmB;AACrB,GAEa,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,aAAa;AACf,G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modules/miniflare/dist/src/workers/kv/sites.worker.js new file mode 100644 index 0000000..e81e4fe --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/kv/sites.worker.js @@ -0,0 +1,147 @@ +// packages/miniflare/src/workers/kv/sites.worker.ts +import { SharedBindings, base64Decode, base64Encode } from "miniflare:shared"; + +// packages/miniflare/src/workers/kv/constants.ts +import { testRegExps } from "miniflare:shared"; +var KVLimits = { + MIN_CACHE_TTL: 60, + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 512, + MAX_VALUE_SIZE: 25 * 1024 * 1024, + MAX_VALUE_SIZE_TEST: 1024, + MAX_METADATA_SIZE: 1024 +}, KVParams = { + URL_ENCODED: "urlencoded", + CACHE_TTL: "cache_ttl", + EXPIRATION: "expiration", + EXPIRATION_TTL: "expiration_ttl", + LIST_LIMIT: "key_count_limit", + LIST_PREFIX: "prefix", + LIST_CURSOR: "cursor" +}; +var SiteBindings = { + KV_NAMESPACE_SITE: "__STATIC_CONTENT", + JSON_SITE_MANIFEST: "__STATIC_CONTENT_MANIFEST", + JSON_SITE_FILTER: "MINIFLARE_SITE_FILTER" +}, SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/"; +function encodeSitesKey(key) { + return SITES_NO_CACHE_PREFIX + encodeURIComponent(key); +} +function decodeSitesKey(key) { + return key.startsWith(SITES_NO_CACHE_PREFIX) ? decodeURIComponent(key.substring(SITES_NO_CACHE_PREFIX.length)) : key; +} +function deserialiseRegExps(matcher) { + return { + include: matcher.include.map((regExp) => new RegExp(regExp)), + exclude: matcher.exclude.map((regExp) => new RegExp(regExp)) + }; +} +function deserialiseSiteRegExps(siteRegExps) { + return { + include: siteRegExps.include && deserialiseRegExps(siteRegExps.include), + exclude: siteRegExps.exclude && deserialiseRegExps(siteRegExps.exclude) + }; +} +function testSiteRegExps(regExps, key) { + return regExps.include !== void 0 ? testRegExps(regExps.include, key) : regExps.exclude !== void 0 ? !testRegExps(regExps.exclude, key) : !0; +} + +// packages/miniflare/src/workers/kv/validator.worker.ts +import { Buffer } from "node:buffer"; +import { HttpError } from "miniflare:shared"; +function validateKeyLength(key) { + let keyLength = Buffer.byteLength(key); + if (keyLength > KVLimits.MAX_KEY_SIZE) + throw new HttpError( + 414, + `UTF-8 encoded length of ${keyLength} exceeds key length limit of ${KVLimits.MAX_KEY_SIZE}.` + ); +} +function decodeListOptions(url) { + let limitParam = url.searchParams.get(KVParams.LIST_LIMIT), limit = limitParam === null ? KVLimits.MAX_LIST_KEYS : parseInt(limitParam), prefix = url.searchParams.get(KVParams.LIST_PREFIX) ?? void 0, cursor = url.searchParams.get(KVParams.LIST_CURSOR) ?? void 0; + return { limit, prefix, cursor }; +} +function validateListOptions(options) { + let limit = options.limit; + if (limit !== void 0) { + if (isNaN(limit) || limit < 1) + throw new HttpError( + 400, + `Invalid ${KVParams.LIST_LIMIT} of ${limit}. Please specify an integer greater than 0.` + ); + if (limit > KVLimits.MAX_LIST_KEYS) + throw new HttpError( + 400, + `Invalid ${KVParams.LIST_LIMIT} of ${limit}. Please specify an integer less than ${KVLimits.MAX_LIST_KEYS}.` + ); + } + let prefix = options.prefix; + prefix != null && validateKeyLength(prefix); +} + +// packages/miniflare/src/workers/kv/sites.worker.ts +var siteRegExpsCache = /* @__PURE__ */ new WeakMap(); +function getSiteRegExps(env) { + let regExps = siteRegExpsCache.get(env); + return regExps !== void 0 || (regExps = deserialiseSiteRegExps(env[SiteBindings.JSON_SITE_FILTER]), siteRegExpsCache.set(env, regExps)), regExps; +} +async function* walkDirectory(blobsService, path = "") { + let res = await blobsService.fetch(`http://placeholder/${path}`); + if (!(res.headers.get("Content-Type") ?? "").toLowerCase().startsWith("application/json")) { + await res.body?.pipeTo(new WritableStream()), yield path; + return; + } + let entries = await res.json(); + for (let { name, type } of entries) { + let entryPath = `${path}${path === "" ? "" : "/"}${name}`; + type === "directory" ? yield* walkDirectory(blobsService, entryPath) : yield entryPath; + } +} +var encoder = new TextEncoder(); +function arrayCompare(a, b) { + let minLength = Math.min(a.length, b.length); + for (let i = 0; i < minLength; i++) { + let aElement = a[i], bElement = b[i]; + if (aElement < bElement) + return -1; + if (aElement > bElement) + return 1; + } + return a.length - b.length; +} +async function handleListRequest(url, blobsService, siteRegExps) { + let options = decodeListOptions(url); + validateListOptions(options); + let { limit = KVLimits.MAX_LIST_KEYS, prefix, cursor } = options, keys = []; + for await (let name of walkDirectory(blobsService)) + testSiteRegExps(siteRegExps, name) && (name = encodeSitesKey(name), !(prefix !== void 0 && !name.startsWith(prefix)) && keys.push({ name, encodedName: encoder.encode(name) })); + keys.sort((a, b) => arrayCompare(a.encodedName, b.encodedName)); + for (let key of keys) + delete key.encodedName; + let startAfter = cursor === void 0 ? "" : base64Decode(cursor), startIndex = 0; + startAfter !== "" && (startIndex = keys.findIndex(({ name }) => name === startAfter), startIndex === -1 && (startIndex = keys.length), startIndex++); + let endIndex = startIndex + limit, nextCursor = endIndex < keys.length ? base64Encode(keys[endIndex - 1].name) : void 0; + return keys = keys.slice(startIndex, endIndex), nextCursor === void 0 ? Response.json({ keys, list_complete: !0 }) : Response.json({ keys, list_complete: !1, cursor: nextCursor }); +} +var sites_worker_default = { + async fetch(request, env) { + if (request.method !== "GET") { + let message = `Cannot ${request.method.toLowerCase()}() with Workers Sites namespace`; + return new Response(message, { status: 405, statusText: message }); + } + let url = new URL(request.url), key = url.pathname.substring(1); + url.searchParams.get(KVParams.URL_ENCODED)?.toLowerCase() === "true" && (key = decodeURIComponent(key)), key = decodeSitesKey(key); + let siteRegExps = getSiteRegExps(env); + if (key !== "" && !testSiteRegExps(siteRegExps, key)) + return new Response("Not Found", { + status: 404, + statusText: "Not Found" + }); + let blobsService = env[SharedBindings.MAYBE_SERVICE_BLOBS]; + return key === "" ? handleListRequest(url, blobsService, siteRegExps) : blobsService.fetch(new URL(key, "http://placeholder")); + } +}; +export { + sites_worker_default as default +}; +//# sourceMappingURL=sites.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/kv/sites.worker.js.map b/node_modules/miniflare/dist/src/workers/kv/sites.worker.js.map new file mode 100644 index 0000000..f44adab --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/kv/sites.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/kv/sites.worker.ts", "../../../../src/workers/kv/constants.ts", "../../../../src/workers/kv/validator.worker.ts"], + "mappings": ";AAAA,SAAS,gBAAgB,cAAc,oBAAoB;;;ACA3D,SAAyB,mBAAmB;AAErC,IAAM,WAAW;AAAA,EACtB,eAAe;AAAA,EACf,eAAe;AAAA,EACf,cAAc;AAAA,EACd,gBAAgB,KAAK,OAAO;AAAA,EAC5B,qBAAqB;AAAA,EACrB,mBAAmB;AACrB,GAEa,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,aAAa;AACf;AAOO,IAAM,eAAe;AAAA,EAC1B,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,kBAAkB;AACpB,GAKa,wBAAwB;AAE9B,SAAS,eAAe,KAAqB;AAGlD,SAAO,wBAAwB,mBAAmB,GAAG;AACvD;AACO,SAAS,eAAe,KAAqB;AAClD,SAAO,IAAI,WAAW,qBAAqB,IACvC,mBAAmB,IAAI,UAAU,sBAAsB,MAAM,CAAC,IAC9D;AACN;AAmCO,SAAS,mBACd,SACgB;AAChB,SAAO;AAAA,IACL,SAAS,QAAQ,QAAQ,IAAI,CAAC,WAAW,IAAI,OAAO,MAAM,CAAC;AAAA,IAC3D,SAAS,QAAQ,QAAQ,IAAI,CAAC,WAAW,IAAI,OAAO,MAAM,CAAC;AAAA,EAC7D;AACF;AAWO,SAAS,uBACd,aACoB;AACpB,SAAO;AAAA,IACL,SAAS,YAAY,WAAW,mBAAmB,YAAY,OAAO;AAAA,IACtE,SAAS,YAAY,WAAW,mBAAmB,YAAY,OAAO;AAAA,EACxE;AACF;AAEO,SAA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modules/miniflare/dist/src/workers/queues/broker.worker.js b/node_modules/miniflare/dist/src/workers/queues/broker.worker.js new file mode 100644 index 0000000..793e8f6 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/queues/broker.worker.js @@ -0,0 +1,238 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// packages/miniflare/src/workers/queues/broker.worker.ts +import assert from "node:assert"; +import { Buffer as Buffer2 } from "node:buffer"; + +// node_modules/kleur/colors.mjs +var FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY = !0; +typeof process < "u" && ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}, isTTY = process.stdout && process.stdout.isTTY); +var $ = { + enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY) +}; +function init(x, y) { + let rgx = new RegExp(`\\x1b\\[${y}m`, "g"), open = `\x1B[${x}m`, close = `\x1B[${y}m`; + return function(txt) { + return !$.enabled || txt == null ? txt : open + (~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close; + }; +} +var reset = init(0, 0), bold = init(1, 22), dim = init(2, 22), italic = init(3, 23), underline = init(4, 24), inverse = init(7, 27), hidden = init(8, 28), strikethrough = init(9, 29), black = init(30, 39), red = init(31, 39), green = init(32, 39), yellow = init(33, 39), blue = init(34, 39), magenta = init(35, 39), cyan = init(36, 39), white = init(37, 39), gray = init(90, 39), grey = init(90, 39), bgBlack = init(40, 49), bgRed = init(41, 49), bgGreen = init(42, 49), bgYellow = init(43, 49), bgBlue = init(44, 49), bgMagenta = init(45, 49), bgCyan = init(46, 49), bgWhite = init(47, 49); + +// packages/miniflare/src/workers/queues/broker.worker.ts +import { + HttpError, + LogLevel, + MiniflareDurableObject, + POST, + SharedBindings, + viewToBuffer +} from "miniflare:shared"; + +// packages/miniflare/src/workers/queues/constants.ts +var QueueBindings = { + SERVICE_WORKER_PREFIX: "MINIFLARE_WORKER_", + MAYBE_JSON_QUEUE_CONSUMERS: "MINIFLARE_QUEUE_CONSUMERS" +}; + +// packages/miniflare/src/workers/queues/schemas.ts +import { Base64DataSchema, z } from "miniflare:zod"; +var QueueConsumerOptionsSchema = /* @__PURE__ */ z.object({ + // https://developers.cloudflare.com/queues/platform/configuration/#consumer + // https://developers.cloudflare.com/queues/platform/limits/ + maxBatchSize: z.number().min(0).max(100).optional(), + maxBatchTimeout: z.number().min(0).max(30).optional(), + // seconds + maxRetires: z.number().min(0).max(100).optional(), + deadLetterQueue: z.ostring() +}), QueueConsumerSchema = /* @__PURE__ */ z.intersection( + QueueConsumerOptionsSchema, + z.object({ workerName: z.string() }) +), QueueConsumersSchema = /* @__PURE__ */ z.record(QueueConsumerSchema), QueueContentTypeSchema = /* @__PURE__ */ z.enum(["text", "json", "bytes", "v8"]).default("v8"), QueueIncomingMessageSchema = /* @__PURE__ */ z.object({ + contentType: QueueContentTypeSchema, + body: Base64DataSchema, + // When enqueuing messages on dead-letter queues, we want to reuse the same ID + // and timestamp + id: z.ostring(), + timestamp: z.onumber() +}), QueuesBatchRequestSchema = /* @__PURE__ */ z.object({ + messages: z.array(QueueIncomingMessageSchema) +}); + +// packages/miniflare/src/workers/queues/broker.worker.ts +var MAX_MESSAGE_SIZE_BYTES = 128 * 1e3, MAX_MESSAGE_BATCH_COUNT = 100, MAX_MESSAGE_BATCH_SIZE = (256 + 32) * 1e3, DEFAULT_BATCH_SIZE = 5, DEFAULT_BATCH_TIMEOUT = 1, DEFAULT_RETRIES = 2, exceptionQueueResponse = { + outcome: "exception", + retryAll: !1, + ackAll: !1, + explicitRetries: [], + explicitAcks: [] +}, PayloadTooLargeError = class extends HttpError { + constructor(message) { + super(413, message); + } +}; +function validateMessageSize(headers) { + let size = headers.get("Content-Length"); + if (size !== null && parseInt(size) > MAX_MESSAGE_SIZE_BYTES) + throw new PayloadTooLargeError( + `message length of ${size} bytes exceeds limit of ${MAX_MESSAGE_SIZE_BYTES}` + ); +} +function validateContentType(headers) { + let format = headers.get("X-Msg-Fmt") ?? void 0, result = QueueContentTypeSchema.safeParse(format); + if (!result.success) + throw new HttpError( + 400, + `message content type ${format} is invalid; if specified, must be one of 'text', 'json', 'bytes', or 'v8'` + ); + return result.data; +} +function validateBatchSize(headers) { + let count = headers.get("CF-Queue-Batch-Count"); + if (count !== null && parseInt(count) > MAX_MESSAGE_BATCH_COUNT) + throw new PayloadTooLargeError( + `batch message count of ${count} exceeds limit of ${MAX_MESSAGE_BATCH_COUNT}` + ); + let largestSize = headers.get("CF-Queue-Largest-Msg"); + if (largestSize !== null && parseInt(largestSize) > MAX_MESSAGE_SIZE_BYTES) + throw new PayloadTooLargeError( + `message in batch has length ${largestSize} bytes which exceeds single message size limit of ${MAX_MESSAGE_SIZE_BYTES}` + ); + let batchSize = headers.get("CF-Queue-Batch-Bytes"); + if (batchSize !== null && parseInt(batchSize) > MAX_MESSAGE_BATCH_SIZE) + throw new PayloadTooLargeError( + `batch size of ${batchSize} bytes exceeds limit of 256000` + ); +} +function deserialise({ contentType, body }) { + return contentType === "text" ? { contentType, body: body.toString() } : contentType === "json" ? { contentType, body: JSON.parse(body.toString()) } : contentType === "bytes" ? { contentType, body: viewToBuffer(body) } : { contentType, body }; +} +function serialise(msg) { + let body; + return msg.body.contentType === "text" ? body = Buffer2.from(msg.body.body) : msg.body.contentType === "json" ? body = Buffer2.from(JSON.stringify(msg.body.body)) : msg.body.contentType === "bytes" ? body = Buffer2.from(msg.body.body) : body = msg.body.body, { + id: msg.id, + timestamp: msg.timestamp, + contentType: msg.body.contentType, + body: body.toString("base64") + }; +} +var QueueMessage = class { + constructor(id, timestamp, body) { + this.id = id; + this.timestamp = timestamp; + this.body = body; + } + #failedAttempts = 0; + incrementFailedAttempts() { + return ++this.#failedAttempts; + } +}; +function formatQueueResponse(queueName, acked, total, time) { + let colour; + acked === total ? colour = green : acked > 0 ? colour = yellow : colour = red; + let message = `${bold("QUEUE")} ${queueName} ${colour(`${acked}/${total}`)}`; + return time !== void 0 && (message += grey(` (${time}ms)`)), reset(message); +} +var QueueBrokerObject = class extends MiniflareDurableObject { + #consumers; + #messages = []; + #pendingFlush; + constructor(state, env) { + super(state, env); + let maybeConsumers = env[QueueBindings.MAYBE_JSON_QUEUE_CONSUMERS]; + maybeConsumers === void 0 ? this.#consumers = {} : this.#consumers = QueueConsumersSchema.parse(maybeConsumers); + } + get #maybeConsumer() { + return this.#consumers[this.name]; + } + #dispatchBatch(workerName, batch) { + let bindingName = `${QueueBindings.SERVICE_WORKER_PREFIX}${workerName}`, maybeService = this.env[bindingName]; + assert( + maybeService !== void 0, + `Expected ${bindingName} service binding` + ); + let messages = batch.map(({ id, timestamp, body }) => body.contentType === "v8" ? { id, timestamp, serializedBody: body.body } : { id, timestamp, body: body.body }); + return maybeService.queue(this.name, messages); + } + #flush = async () => { + let consumer = this.#maybeConsumer; + assert(consumer !== void 0); + let batchSize = consumer.maxBatchSize ?? DEFAULT_BATCH_SIZE, maxAttempts = (consumer.maxRetires ?? DEFAULT_RETRIES) + 1, maxAttemptsS = maxAttempts === 1 ? "" : "s", batch = this.#messages.splice(0, batchSize), startTime = Date.now(), endTime, response; + try { + response = await this.#dispatchBatch(consumer.workerName, batch), endTime = Date.now(); + } catch (e) { + endTime = Date.now(), await this.logWithLevel(LogLevel.ERROR, String(e)), response = exceptionQueueResponse; + } + let retryAll = response.retryAll || response.outcome !== "ok", explicitRetries = new Set(response.explicitRetries), failedMessages = 0, toRetry = [], toDeadLetterQueue = []; + for (let message of batch) + (retryAll || explicitRetries.has(message.id)) && (failedMessages++, message.incrementFailedAttempts() < maxAttempts ? (await this.logWithLevel( + LogLevel.DEBUG, + `Retrying message "${message.id}" on queue "${this.name}"...` + ), toRetry.push(message)) : consumer.deadLetterQueue !== void 0 ? (await this.logWithLevel( + LogLevel.WARN, + `Moving message "${message.id}" on queue "${this.name}" to dead letter queue "${consumer.deadLetterQueue}" after ${maxAttempts} failed attempt${maxAttemptsS}...` + ), toDeadLetterQueue.push(message)) : await this.logWithLevel( + LogLevel.WARN, + `Dropped message "${message.id}" on queue "${this.name}" after ${maxAttempts} failed attempt${maxAttemptsS}!` + )); + let acked = batch.length - failedMessages; + if (await this.logWithLevel( + LogLevel.INFO, + formatQueueResponse(this.name, acked, batch.length, endTime - startTime) + ), this.#messages.push(...toRetry), this.#pendingFlush = void 0, this.#messages.length > 0 && this.#ensurePendingFlush(), toDeadLetterQueue.length > 0) { + let name = consumer.deadLetterQueue; + assert(name !== void 0); + let ns = this.env[SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT], id = ns.idFromName(name), stub = ns.get(id), cf = { miniflare: { name } }, batchRequest = { + messages: toDeadLetterQueue.map(serialise) + }, res = await stub.fetch("http://placeholder/batch", { + method: "POST", + body: JSON.stringify(batchRequest), + cf + }); + assert(res.ok); + } + }; + #ensurePendingFlush() { + let consumer = this.#maybeConsumer; + assert(consumer !== void 0); + let batchSize = consumer.maxBatchSize ?? DEFAULT_BATCH_SIZE, batchTimeout = consumer.maxBatchTimeout ?? DEFAULT_BATCH_TIMEOUT, batchHasSpace = this.#messages.length < batchSize; + if (this.#pendingFlush !== void 0) { + if (this.#pendingFlush.immediate || batchHasSpace) + return; + this.timers.clearTimeout(this.#pendingFlush.timeout), this.#pendingFlush = void 0; + } + let delay = batchHasSpace ? batchTimeout * 1e3 : 0, timeout = this.timers.setTimeout(this.#flush, delay); + this.#pendingFlush = { immediate: delay === 0, timeout }; + } + #enqueue(messages) { + for (let message of messages) { + let randomness = crypto.getRandomValues(new Uint8Array(16)), id = message.id ?? Buffer2.from(randomness).toString("hex"), timestamp = message.timestamp ?? this.timers.now(), body = deserialise(message); + this.#messages.push(new QueueMessage(id, timestamp, body)); + } + this.#ensurePendingFlush(); + } + message = async (req) => { + validateMessageSize(req.headers); + let contentType = validateContentType(req.headers), body = Buffer2.from(await req.arrayBuffer()); + return this.#maybeConsumer === void 0 ? new Response() : (this.#enqueue([{ contentType, body }]), new Response()); + }; + batch = async (req) => { + validateBatchSize(req.headers); + let body = QueuesBatchRequestSchema.parse(await req.json()); + return this.#maybeConsumer === void 0 ? new Response() : (this.#enqueue(body.messages), new Response()); + }; +}; +__decorateClass([ + POST("/message") +], QueueBrokerObject.prototype, "message", 2), __decorateClass([ + POST("/batch") +], QueueBrokerObject.prototype, "batch", 2); +export { + QueueBrokerObject +}; +//# sourceMappingURL=broker.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/queues/broker.worker.js.map b/node_modules/miniflare/dist/src/workers/queues/broker.worker.js.map new file mode 100644 index 0000000..abb4f32 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/queues/broker.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/queues/broker.worker.ts", "../../../../../../node_modules/kleur/colors.mjs", "../../../../src/workers/queues/constants.ts", "../../../../src/workers/queues/schemas.ts"], + "mappings": ";;;;;;;;;AAAA,OAAO,YAAY;AACnB,SAAS,UAAAA,eAAc;;;ACDvB,IAAI,aAAa,qBAAqB,UAAU,MAAM,QAAM;AACxD,OAAO,UAAY,QACrB,EAAE,aAAa,qBAAqB,UAAU,KAAK,IAAI,QAAQ,OAAO,CAAC,GACxE,QAAQ,QAAQ,UAAU,QAAQ,OAAO;AAGnC,IAAM,IAAI;AAAA,EAChB,SAAS,CAAC,uBAAuB,YAAY,QAAQ,SAAS,WAC7D,eAAe,QAAQ,gBAAgB,OAAO;AAEhD;AAEA,SAAS,KAAK,GAAG,GAAG;AACnB,MAAI,MAAM,IAAI,OAAO,WAAW,MAAM,GAAG,GACrC,OAAO,QAAQ,MAAM,QAAQ,QAAQ;AAEzC,S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UAAU,EAAE,SAAS,KAAK,GACzD,YAAY,QAAQ,aAAa,KAAK,OAAO,IAAI,GACjD,OAAO,YAAY,OAAO;AAChC,WAAK,UAAU,KAAK,IAAI,aAAa,IAAI,WAAW,IAAI,CAAC;AAAA,IAC3D;AACA,SAAK,oBAAoB;AAAA,EAC3B;AAAA,EAGA,UAAwB,OAAO,QAAQ;AACrC,wBAAoB,IAAI,OAAO;AAC/B,QAAM,cAAc,oBAAoB,IAAI,OAAO,GAC7C,OAAOA,QAAO,KAAK,MAAM,IAAI,YAAY,CAAC;AAIhD,WADiB,KAAK,mBACL,SAAkB,IAAI,SAAS,KAEhD,KAAK,SAAS,CAAC,EAAE,aAAa,KAAK,CAAC,CAAC,GAC9B,IAAI,SAAS;AAAA,EACtB;AAAA,EAGA,QAAsB,OAAO,QAAQ;AAKnC,sBAAkB,IAAI,OAAO;AAC7B,QAAM,OAAO,yBAAyB,MAAM,MAAM,IAAI,KAAK,CAAC;AAI5D,WADiB,KAAK,mBACL,SAAkB,IAAI,SAAS,KAEhD,KAAK,SAAS,KAAK,QAAQ,GACpB,IAAI,SAAS;AAAA,EACtB;AACF;AA7BE;AAAA,EADC,KAAK,UAAU;AAAA,GA9JL,kBA+JX,0BAcA;AAAA,EADC,KAAK,QAAQ;AAAA,GA5KH,kBA6KX;", + "names": ["Buffer", "Buffer"] +} diff --git a/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js b/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js new file mode 100644 index 0000000..2c239d7 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js @@ -0,0 +1,1158 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __decorateClass = (decorators, target, key, kind) => { + for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--) + (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result); + return kind && result && __defProp(target, key, result), result; +}; + +// packages/miniflare/src/workers/r2/bucket.worker.ts +import assert2 from "node:assert"; +import { Buffer as Buffer3 } from "node:buffer"; +import { createHash } from "node:crypto"; +import { + DeferredPromise, + GET, + MiniflareDurableObject, + PUT, + WaitGroup, + all, + base64Decode, + base64Encode, + escapeLike, + get, + maybeApply, + readPrefix +} from "miniflare:shared"; + +// packages/miniflare/src/workers/r2/constants.ts +var R2Limits = { + MAX_LIST_KEYS: 1e3, + MAX_KEY_SIZE: 1024, + // https://developers.cloudflare.com/r2/platform/limits/ + MAX_VALUE_SIZE: 5363466240, + // 5 GiB - 5 MiB + MAX_METADATA_SIZE: 2048, + // 2048 B + MIN_MULTIPART_PART_SIZE: 5242880, + MIN_MULTIPART_PART_SIZE_TEST: 50 +}, R2Headers = { + ERROR: "cf-r2-error", + REQUEST: "cf-r2-request", + METADATA_SIZE: "cf-r2-metadata-size" +}; + +// packages/miniflare/src/workers/r2/errors.worker.ts +import { HttpError } from "miniflare:shared"; +var R2ErrorCode = { + INTERNAL_ERROR: 10001, + NO_SUCH_OBJECT_KEY: 10007, + ENTITY_TOO_LARGE: 100100, + ENTITY_TOO_SMALL: 10011, + METADATA_TOO_LARGE: 10012, + INVALID_OBJECT_NAME: 10020, + INVALID_MAX_KEYS: 10022, + NO_SUCH_UPLOAD: 10024, + INVALID_PART: 10025, + INVALID_ARGUMENT: 10029, + PRECONDITION_FAILED: 10031, + BAD_DIGEST: 10037, + INVALID_RANGE: 10039, + BAD_UPLOAD: 10048 +}, R2Error = class extends HttpError { + constructor(code, message, v4Code) { + super(code, message); + this.v4Code = v4Code; + } + object; + toResponse() { + if (this.object !== void 0) { + let { metadataSize, value } = this.object.encode(); + return new Response(value, { + status: this.code, + headers: { + [R2Headers.METADATA_SIZE]: `${metadataSize}`, + "Content-Type": "application/json", + [R2Headers.ERROR]: JSON.stringify({ + message: this.message, + version: 1, + // Note the lowercase 'c', which the runtime expects + v4code: this.v4Code + }) + } + }); + } + return new Response(null, { + status: this.code, + headers: { + [R2Headers.ERROR]: JSON.stringify({ + message: this.message, + version: 1, + // Note the lowercase 'c', which the runtime expects + v4code: this.v4Code + }) + } + }); + } + context(info) { + return this.message += ` (${info})`, this; + } + attach(object) { + return this.object = object, this; + } +}, InvalidMetadata = class extends R2Error { + constructor() { + super(400, "Metadata missing or invalid", R2ErrorCode.INVALID_ARGUMENT); + } +}, InternalError = class extends R2Error { + constructor() { + super( + 500, + "We encountered an internal error. Please try again.", + R2ErrorCode.INTERNAL_ERROR + ); + } +}, NoSuchKey = class extends R2Error { + constructor() { + super( + 404, + "The specified key does not exist.", + R2ErrorCode.NO_SUCH_OBJECT_KEY + ); + } +}, EntityTooLarge = class extends R2Error { + constructor() { + super( + 400, + "Your proposed upload exceeds the maximum allowed object size.", + R2ErrorCode.ENTITY_TOO_LARGE + ); + } +}, EntityTooSmall = class extends R2Error { + constructor() { + super( + 400, + "Your proposed upload is smaller than the minimum allowed object size.", + R2ErrorCode.ENTITY_TOO_SMALL + ); + } +}, MetadataTooLarge = class extends R2Error { + constructor() { + super( + 400, + "Your metadata headers exceed the maximum allowed metadata size.", + R2ErrorCode.METADATA_TOO_LARGE + ); + } +}, BadDigest = class extends R2Error { + constructor(algorithm, provided, calculated) { + super( + 400, + [ + `The ${algorithm} checksum you specified did not match what we received.`, + `You provided a ${algorithm} checksum with value: ${provided.toString( + "hex" + )}`, + `Actual ${algorithm} was: ${calculated.toString("hex")}` + ].join(` +`), + R2ErrorCode.BAD_DIGEST + ); + } +}, InvalidObjectName = class extends R2Error { + constructor() { + super( + 400, + "The specified object name is not valid.", + R2ErrorCode.INVALID_OBJECT_NAME + ); + } +}, InvalidMaxKeys = class extends R2Error { + constructor() { + super( + 400, + "MaxKeys params must be positive integer <= 1000.", + R2ErrorCode.INVALID_MAX_KEYS + ); + } +}, NoSuchUpload = class extends R2Error { + constructor() { + super( + 400, + "The specified multipart upload does not exist.", + R2ErrorCode.NO_SUCH_UPLOAD + ); + } +}, InvalidPart = class extends R2Error { + constructor() { + super( + 400, + "One or more of the specified parts could not be found.", + R2ErrorCode.INVALID_PART + ); + } +}, PreconditionFailed = class extends R2Error { + constructor() { + super( + 412, + "At least one of the pre-conditions you specified did not hold.", + R2ErrorCode.PRECONDITION_FAILED + ); + } +}, InvalidRange = class extends R2Error { + constructor() { + super( + 416, + "The requested range is not satisfiable", + R2ErrorCode.INVALID_RANGE + ); + } +}, BadUpload = class extends R2Error { + constructor() { + super( + 500, + "There was a problem with the multipart upload.", + R2ErrorCode.BAD_UPLOAD + ); + } +}; + +// packages/miniflare/src/workers/r2/r2Object.worker.ts +import { HEX_REGEXP } from "miniflare:zod"; +var InternalR2Object = class { + key; + version; + size; + etag; + uploaded; + httpMetadata; + customMetadata; + range; + checksums; + constructor(row, range) { + this.key = row.key, this.version = row.version, this.size = row.size, this.etag = row.etag, this.uploaded = row.uploaded, this.httpMetadata = JSON.parse(row.http_metadata), this.customMetadata = JSON.parse(row.custom_metadata), this.range = range; + let checksums = JSON.parse(row.checksums); + this.etag.length === 32 && HEX_REGEXP.test(this.etag) && (checksums.md5 = row.etag), this.checksums = checksums; + } + // Format for return to the Workers Runtime + #rawProperties() { + return { + name: this.key, + version: this.version, + size: this.size, + etag: this.etag, + uploaded: this.uploaded, + httpFields: this.httpMetadata, + customFields: Object.entries(this.customMetadata).map(([k, v]) => ({ + k, + v + })), + range: this.range, + checksums: { + 0: this.checksums.md5, + 1: this.checksums.sha1, + 2: this.checksums.sha256, + 3: this.checksums.sha384, + 4: this.checksums.sha512 + } + }; + } + encode() { + let json = JSON.stringify(this.#rawProperties()), blob = new Blob([json]); + return { metadataSize: blob.size, value: blob.stream() }; + } + static encodeMultiple(objects) { + let json = JSON.stringify({ + ...objects, + objects: objects.objects.map((o) => o.#rawProperties()) + }), blob = new Blob([json]); + return { metadataSize: blob.size, value: blob.stream() }; + } +}, InternalR2ObjectBody = class extends InternalR2Object { + constructor(metadata, body, range) { + super(metadata, range); + this.body = body; + } + encode() { + let { metadataSize, value: metadata } = super.encode(), identity2 = new IdentityTransformStream(); + return metadata.pipeTo(identity2.writable, { preventClose: !0 }).then(() => this.body.pipeTo(identity2.writable)), { + metadataSize, + value: identity2.readable + }; + } +}; + +// packages/miniflare/src/workers/r2/schemas.worker.ts +import { Base64DataSchema, HexDataSchema, z } from "miniflare:zod"; +var MultipartUploadState = { + IN_PROGRESS: 0, + COMPLETED: 1, + ABORTED: 2 +}, SQL_SCHEMA = ` +CREATE TABLE IF NOT EXISTS _mf_objects ( + key TEXT PRIMARY KEY, + blob_id TEXT, + version TEXT NOT NULL, + size INTEGER NOT NULL, + etag TEXT NOT NULL, + uploaded INTEGER NOT NULL, + checksums TEXT NOT NULL, + http_metadata TEXT NOT NULL, + custom_metadata TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS _mf_multipart_uploads ( + upload_id TEXT PRIMARY KEY, + key TEXT NOT NULL, + http_metadata TEXT NOT NULL, + custom_metadata TEXT NOT NULL, + state TINYINT DEFAULT 0 NOT NULL +); +CREATE TABLE IF NOT EXISTS _mf_multipart_parts ( + upload_id TEXT NOT NULL REFERENCES _mf_multipart_uploads(upload_id), + part_number INTEGER NOT NULL, + blob_id TEXT NOT NULL, + size INTEGER NOT NULL, + etag TEXT NOT NULL, + checksum_md5 TEXT NOT NULL, + object_key TEXT REFERENCES _mf_objects(key) DEFERRABLE INITIALLY DEFERRED, + PRIMARY KEY (upload_id, part_number) +); +`, DateSchema = z.coerce.number().transform((value) => new Date(value)), RecordSchema = z.object({ + k: z.string(), + v: z.string() +}).array().transform( + (entries) => Object.fromEntries(entries.map(({ k, v }) => [k, v])) +), R2RangeSchema = z.object({ + offset: z.coerce.number().optional(), + length: z.coerce.number().optional(), + suffix: z.coerce.number().optional() +}), R2EtagSchema = z.discriminatedUnion("type", [ + z.object({ type: z.literal("strong"), value: z.string() }), + z.object({ type: z.literal("weak"), value: z.string() }), + z.object({ type: z.literal("wildcard") }) +]), R2EtagMatchSchema = R2EtagSchema.array().min(1).optional(), R2ConditionalSchema = z.object({ + // Performs the operation if the object's ETag matches the given string + etagMatches: R2EtagMatchSchema, + // "If-Match" + // Performs the operation if the object's ETag does NOT match the given string + etagDoesNotMatch: R2EtagMatchSchema, + // "If-None-Match" + // Performs the operation if the object was uploaded BEFORE the given date + uploadedBefore: DateSchema.optional(), + // "If-Unmodified-Since" + // Performs the operation if the object was uploaded AFTER the given date + uploadedAfter: DateSchema.optional(), + // "If-Modified-Since" + // Truncates dates to seconds before performing comparisons + secondsGranularity: z.oboolean() +}), R2ChecksumsSchema = z.object({ + 0: HexDataSchema.optional(), + 1: HexDataSchema.optional(), + 2: HexDataSchema.optional(), + 3: HexDataSchema.optional(), + 4: HexDataSchema.optional() +}).transform((checksums) => ({ + md5: checksums[0], + sha1: checksums[1], + sha256: checksums[2], + sha384: checksums[3], + sha512: checksums[4] +})), R2PublishedPartSchema = z.object({ + etag: z.string(), + part: z.number() +}), R2HttpFieldsSchema = z.object({ + contentType: z.ostring(), + contentLanguage: z.ostring(), + contentDisposition: z.ostring(), + contentEncoding: z.ostring(), + cacheControl: z.ostring(), + cacheExpiry: z.coerce.number().optional() +}), R2HeadRequestSchema = z.object({ + method: z.literal("head"), + object: z.string() +}), R2GetRequestSchema = z.object({ + method: z.literal("get"), + object: z.string(), + // Specifies that only a specific length (from an optional offset) or suffix + // of bytes from the object should be returned. Refer to + // https://developers.cloudflare.com/r2/runtime-apis/#ranged-reads. + range: R2RangeSchema.optional(), + rangeHeader: z.ostring(), + // Specifies that the object should only be returned given satisfaction of + // certain conditions in the R2Conditional. Refer to R2Conditional above. + onlyIf: R2ConditionalSchema.optional() +}), R2PutRequestSchema = z.object({ + method: z.literal("put"), + object: z.string(), + customFields: RecordSchema.optional(), + // (renamed in transform) + httpFields: R2HttpFieldsSchema.optional(), + // (renamed in transform) + onlyIf: R2ConditionalSchema.optional(), + md5: Base64DataSchema.optional(), + // (intentionally base64, not hex) + sha1: HexDataSchema.optional(), + sha256: HexDataSchema.optional(), + sha384: HexDataSchema.optional(), + sha512: HexDataSchema.optional() +}).transform((value) => ({ + method: value.method, + object: value.object, + customMetadata: value.customFields, + httpMetadata: value.httpFields, + onlyIf: value.onlyIf, + md5: value.md5, + sha1: value.sha1, + sha256: value.sha256, + sha384: value.sha384, + sha512: value.sha512 +})), R2CreateMultipartUploadRequestSchema = z.object({ + method: z.literal("createMultipartUpload"), + object: z.string(), + customFields: RecordSchema.optional(), + // (renamed in transform) + httpFields: R2HttpFieldsSchema.optional() + // (renamed in transform) +}).transform((value) => ({ + method: value.method, + object: value.object, + customMetadata: value.customFields, + httpMetadata: value.httpFields +})), R2UploadPartRequestSchema = z.object({ + method: z.literal("uploadPart"), + object: z.string(), + uploadId: z.string(), + partNumber: z.number() +}), R2CompleteMultipartUploadRequestSchema = z.object({ + method: z.literal("completeMultipartUpload"), + object: z.string(), + uploadId: z.string(), + parts: R2PublishedPartSchema.array() +}), R2AbortMultipartUploadRequestSchema = z.object({ + method: z.literal("abortMultipartUpload"), + object: z.string(), + uploadId: z.string() +}), R2ListRequestSchema = z.object({ + method: z.literal("list"), + limit: z.onumber(), + prefix: z.ostring(), + cursor: z.ostring(), + delimiter: z.ostring(), + startAfter: z.ostring(), + include: z.union([z.literal(0), z.literal(1)]).transform((value) => value === 0 ? "httpMetadata" : "customMetadata").array().optional() +}), R2DeleteRequestSchema = z.intersection( + z.object({ method: z.literal("delete") }), + z.union([ + z.object({ object: z.string() }), + z.object({ objects: z.string().array() }) + ]) +), R2BindingRequestSchema = z.union([ + R2HeadRequestSchema, + R2GetRequestSchema, + R2PutRequestSchema, + R2CreateMultipartUploadRequestSchema, + R2UploadPartRequestSchema, + R2CompleteMultipartUploadRequestSchema, + R2AbortMultipartUploadRequestSchema, + R2ListRequestSchema, + R2DeleteRequestSchema +]); + +// packages/miniflare/src/workers/r2/validator.worker.ts +import assert from "node:assert"; +import { Buffer as Buffer2 } from "node:buffer"; +import { parseRanges } from "miniflare:shared"; +function identity(ms) { + return ms; +} +function truncateToSeconds(ms) { + return Math.floor(ms / 1e3) * 1e3; +} +function includesEtag(conditions, etag, comparison) { + for (let condition of conditions) + if (condition.type === "wildcard" || condition.value === etag && (condition.type === "strong" || comparison === "weak")) + return !0; + return !1; +} +function _testR2Conditional(cond, metadata) { + if (metadata === void 0) { + let ifMatch2 = cond.etagMatches === void 0, ifModifiedSince2 = cond.uploadedAfter === void 0; + return ifMatch2 && ifModifiedSince2; + } + let { etag, uploaded: lastModifiedRaw } = metadata, ifMatch = cond.etagMatches === void 0 || includesEtag(cond.etagMatches, etag, "strong"), ifNoneMatch = cond.etagDoesNotMatch === void 0 || !includesEtag(cond.etagDoesNotMatch, etag, "weak"), maybeTruncate = cond.secondsGranularity ? truncateToSeconds : identity, lastModified = maybeTruncate(lastModifiedRaw), ifModifiedSince = cond.uploadedAfter === void 0 || maybeTruncate(cond.uploadedAfter.getTime()) < lastModified || cond.etagDoesNotMatch !== void 0 && ifNoneMatch, ifUnmodifiedSince = cond.uploadedBefore === void 0 || lastModified < maybeTruncate(cond.uploadedBefore.getTime()) || cond.etagMatches !== void 0 && ifMatch; + return ifMatch && ifNoneMatch && ifModifiedSince && ifUnmodifiedSince; +} +var R2_HASH_ALGORITHMS = [ + { name: "MD5", field: "md5" }, + { name: "SHA-1", field: "sha1" }, + { name: "SHA-256", field: "sha256" }, + { name: "SHA-384", field: "sha384" }, + { name: "SHA-512", field: "sha512" } +]; +function serialisedLength(x) { + for (let i = 0; i < x.length; i++) + if (x.charCodeAt(i) >= 256) + return x.length * 2; + return x.length; +} +var Validator = class { + hash(digests, hashes) { + let checksums = {}; + for (let { name, field } of R2_HASH_ALGORITHMS) { + let providedHash = hashes[field]; + if (providedHash !== void 0) { + let computedHash = digests.get(name); + if (assert(computedHash !== void 0), !providedHash.equals(computedHash)) + throw new BadDigest(name, providedHash, computedHash); + checksums[field] = computedHash.toString("hex"); + } + } + return checksums; + } + condition(meta, onlyIf) { + if (onlyIf !== void 0 && !_testR2Conditional(onlyIf, meta)) + throw new PreconditionFailed(); + return this; + } + range(options, size) { + if (options.rangeHeader !== void 0) { + let ranges = parseRanges(options.rangeHeader, size); + if (ranges?.length === 1) + return ranges[0]; + } else if (options.range !== void 0) { + let { offset, length, suffix } = options.range; + if (suffix !== void 0) { + if (suffix <= 0) + throw new InvalidRange(); + suffix > size && (suffix = size), offset = size - suffix, length = suffix; + } + if (offset === void 0 && (offset = 0), length === void 0 && (length = size - offset), offset < 0 || offset > size || length <= 0) + throw new InvalidRange(); + return offset + length > size && (length = size - offset), { start: offset, end: offset + length - 1 }; + } + } + size(size) { + if (size > R2Limits.MAX_VALUE_SIZE) + throw new EntityTooLarge(); + return this; + } + metadataSize(customMetadata) { + if (customMetadata === void 0) + return this; + let metadataLength = 0; + for (let [key, value] of Object.entries(customMetadata)) + metadataLength += serialisedLength(key) + serialisedLength(value); + if (metadataLength > R2Limits.MAX_METADATA_SIZE) + throw new MetadataTooLarge(); + return this; + } + key(key) { + if (Buffer2.byteLength(key) >= R2Limits.MAX_KEY_SIZE) + throw new InvalidObjectName(); + return this; + } + limit(limit) { + if (limit !== void 0 && (limit < 1 || limit > R2Limits.MAX_LIST_KEYS)) + throw new InvalidMaxKeys(); + return this; + } +}; + +// packages/miniflare/src/workers/r2/bucket.worker.ts +var DigestingStream = class extends TransformStream { + digests; + constructor(algorithms) { + let digests = new DeferredPromise(), hashes = algorithms.map((alg) => { + let stream = new crypto.DigestStream(alg), writer = stream.getWriter(); + return { stream, writer }; + }); + super({ + async transform(chunk, controller) { + for (let hash of hashes) + await hash.writer.write(chunk); + controller.enqueue(chunk); + }, + async flush() { + let result = /* @__PURE__ */ new Map(); + for (let i = 0; i < hashes.length; i++) + await hashes[i].writer.close(), result.set(algorithms[i], Buffer3.from(await hashes[i].stream.digest)); + digests.resolve(result); + } + }), this.digests = digests; + } +}, validate = new Validator(), decoder = new TextDecoder(); +function generateVersion() { + return Buffer3.from(crypto.getRandomValues(new Uint8Array(16))).toString( + "hex" + ); +} +function generateId() { + return Buffer3.from(crypto.getRandomValues(new Uint8Array(128))).toString( + "base64url" + ); +} +function generateMultipartEtag(md5Hexes) { + let hash = createHash("md5"); + for (let md5Hex of md5Hexes) + hash.update(md5Hex, "hex"); + return `${hash.digest("hex")}-${md5Hexes.length}`; +} +function rangeOverlaps(a, b) { + return a.start <= b.end && b.start <= a.end; +} +async function decodeMetadata(req) { + let metadataSize = parseInt(req.headers.get(R2Headers.METADATA_SIZE)); + if (Number.isNaN(metadataSize)) + throw new InvalidMetadata(); + assert2(req.body !== null); + let body = req.body, [metadataBuffer, value] = await readPrefix(body, metadataSize), metadataJson = decoder.decode(metadataBuffer); + return { metadata: R2BindingRequestSchema.parse(JSON.parse(metadataJson)), metadataSize, value }; +} +function decodeHeaderMetadata(req) { + let header = req.headers.get(R2Headers.REQUEST); + if (header === null) + throw new InvalidMetadata(); + return R2BindingRequestSchema.parse(JSON.parse(header)); +} +function encodeResult(result) { + let encoded; + return result instanceof InternalR2Object ? encoded = result.encode() : encoded = InternalR2Object.encodeMultiple(result), new Response(encoded.value, { + headers: { + [R2Headers.METADATA_SIZE]: `${encoded.metadataSize}`, + "Content-Type": "application/json" + } + }); +} +function encodeJSONResult(result) { + let encoded = JSON.stringify(result); + return new Response(encoded, { + headers: { + [R2Headers.METADATA_SIZE]: `${Buffer3.byteLength(encoded)}`, + "Content-Type": "application/json" + } + }); +} +function sqlStmts(db) { + let stmtGetPreviousByKey = db.stmt("SELECT blob_id, etag, uploaded FROM _mf_objects WHERE key = :key"), stmtGetByKey = db.stmt(` + SELECT key, blob_id, version, size, etag, uploaded, checksums, http_metadata, custom_metadata + FROM _mf_objects WHERE key = :key + `), stmtPut = db.stmt(` + INSERT OR REPLACE INTO _mf_objects (key, blob_id, version, size, etag, uploaded, checksums, http_metadata, custom_metadata) + VALUES (:key, :blob_id, :version, :size, :etag, :uploaded, :checksums, :http_metadata, :custom_metadata) + `), stmtDelete = db.stmt("DELETE FROM _mf_objects WHERE key = :key RETURNING blob_id"); + function stmtListWithoutDelimiter(...extraColumns) { + let columns = [ + "key", + "version", + "size", + "etag", + "uploaded", + "checksums", + ...extraColumns + ]; + return db.stmt(` + SELECT ${columns.join(", ")} + FROM _mf_objects + WHERE key LIKE :escaped_prefix || '%' ESCAPE '\\' + AND (:start_after IS NULL OR key > :start_after) + ORDER BY key LIMIT :limit + `); + } + let stmtGetUploadState = db.stmt( + // For checking current upload state + "SELECT state FROM _mf_multipart_uploads WHERE upload_id = :upload_id AND key = :key" + ), stmtGetUploadMetadata = db.stmt( + // For checking current upload state, and getting metadata for completion + "SELECT http_metadata, custom_metadata, state FROM _mf_multipart_uploads WHERE upload_id = :upload_id AND key = :key" + ), stmtUpdateUploadState = db.stmt( + // For completing/aborting uploads + "UPDATE _mf_multipart_uploads SET state = :state WHERE upload_id = :upload_id" + ), stmtGetPreviousPartByNumber = db.stmt( + // For getting part number's previous blob ID to garbage collect + "SELECT blob_id FROM _mf_multipart_parts WHERE upload_id = :upload_id AND part_number = :part_number" + ), stmtPutPart = db.stmt( + // For recording metadata when uploading parts + `INSERT OR REPLACE INTO _mf_multipart_parts (upload_id, part_number, blob_id, size, etag, checksum_md5) + VALUES (:upload_id, :part_number, :blob_id, :size, :etag, :checksum_md5)` + ), stmtLinkPart = db.stmt( + // For linking parts with an object when completing uploads + `UPDATE _mf_multipart_parts SET object_key = :object_key + WHERE upload_id = :upload_id AND part_number = :part_number` + ), stmtDeletePartsByUploadId = db.stmt( + // For deleting parts when aborting uploads + "DELETE FROM _mf_multipart_parts WHERE upload_id = :upload_id RETURNING blob_id" + ), stmtDeleteUnlinkedPartsByUploadId = db.stmt( + // For deleting unused parts when completing uploads + "DELETE FROM _mf_multipart_parts WHERE upload_id = :upload_id AND object_key IS NULL RETURNING blob_id" + ), stmtDeletePartsByKey = db.stmt( + // For deleting dangling parts when overwriting an existing key + "DELETE FROM _mf_multipart_parts WHERE object_key = :object_key RETURNING blob_id" + ), stmtListPartsByUploadId = db.stmt( + // For getting part metadata when completing uploads + `SELECT upload_id, part_number, blob_id, size, etag, checksum_md5, object_key + FROM _mf_multipart_parts WHERE upload_id = :upload_id` + ), stmtListPartsByKey = db.stmt( + // For getting part metadata when getting values, size included for range + // requests, so we only need to read blobs containing the required data + "SELECT blob_id, size FROM _mf_multipart_parts WHERE object_key = :object_key ORDER BY part_number" + ); + return { + getByKey: stmtGetByKey, + getPartsByKey: db.txn((key) => { + let row = get(stmtGetByKey({ key })); + if (row !== void 0) + if (row.blob_id === null) { + let partsRows = all(stmtListPartsByKey({ object_key: key })); + return { row, parts: partsRows }; + } else + return { row }; + }), + put: db.txn((newRow, onlyIf) => { + let key = newRow.key, row = get(stmtGetPreviousByKey({ key })); + onlyIf !== void 0 && validate.condition(row, onlyIf), stmtPut(newRow); + let maybeOldBlobId = row?.blob_id; + return maybeOldBlobId === void 0 ? [] : maybeOldBlobId === null ? all(stmtDeletePartsByKey({ object_key: key })).map(({ blob_id }) => blob_id) : [maybeOldBlobId]; + }), + deleteByKeys: db.txn((keys) => { + let oldBlobIds = []; + for (let key of keys) { + let maybeOldBlobId = get(stmtDelete({ key }))?.blob_id; + if (maybeOldBlobId === null) { + let partRows = stmtDeletePartsByKey({ object_key: key }); + for (let partRow of partRows) + oldBlobIds.push(partRow.blob_id); + } else + maybeOldBlobId !== void 0 && oldBlobIds.push(maybeOldBlobId); + } + return oldBlobIds; + }), + listWithoutDelimiter: stmtListWithoutDelimiter(), + listHttpMetadataWithoutDelimiter: stmtListWithoutDelimiter("http_metadata"), + listCustomMetadataWithoutDelimiter: stmtListWithoutDelimiter("custom_metadata"), + listHttpCustomMetadataWithoutDelimiter: stmtListWithoutDelimiter( + "http_metadata", + "custom_metadata" + ), + listMetadata: db.stmt(` + SELECT + -- When grouping by a delimited prefix, this will give us the last key with that prefix. + -- NOTE: we'll use this for the next cursor. If we didn't return the last key, the next page may return the + -- same delimited prefix. Essentially, we're skipping over all keys with this group's delimited prefix. + -- When grouping by a key, this will just give us the key. + max(key) AS last_key, + iif( + -- Try get 1-indexed position \`i\` of :delimiter in rest of key after :prefix... + instr(substr(key, length(:prefix) + 1), :delimiter), + -- ...if found, we have a delimited prefix of the :prefix followed by the rest of key up to and including the :delimiter + 'dlp:' || substr(key, 1, length(:prefix) + instr(substr(key, length(:prefix) + 1), :delimiter) + length(:delimiter) - 1), + -- ...otherwise, we just have a regular key + 'key:' || key + ) AS delimited_prefix_or_key, + -- NOTE: we'll ignore metadata for delimited prefix rows, so it doesn't matter which keys' we return + version, size, etag, uploaded, checksums, http_metadata, custom_metadata + FROM _mf_objects + WHERE key LIKE :escaped_prefix || '%' ESCAPE '\\' + AND (:start_after IS NULL OR key > :start_after) + GROUP BY delimited_prefix_or_key -- Group keys with same delimited prefix into a row, leaving others in their own rows + ORDER BY last_key LIMIT :limit; + `), + createMultipartUpload: db.stmt(` + INSERT INTO _mf_multipart_uploads (upload_id, key, http_metadata, custom_metadata) + VALUES (:upload_id, :key, :http_metadata, :custom_metadata) + `), + putPart: db.txn( + (key, newRow) => { + if (get( + stmtGetUploadState({ + key, + upload_id: newRow.upload_id + }) + )?.state !== MultipartUploadState.IN_PROGRESS) + throw new NoSuchUpload(); + let partRow = get( + stmtGetPreviousPartByNumber({ + upload_id: newRow.upload_id, + part_number: newRow.part_number + }) + ); + return stmtPutPart(newRow), partRow?.blob_id; + } + ), + completeMultipartUpload: db.txn( + (key, upload_id, selectedParts, minPartSize) => { + let uploadRow = get(stmtGetUploadMetadata({ key, upload_id })); + if (uploadRow === void 0) + throw new InternalError(); + if (uploadRow.state > MultipartUploadState.IN_PROGRESS) + throw new NoSuchUpload(); + let partNumberSet = /* @__PURE__ */ new Set(); + for (let { part } of selectedParts) { + if (partNumberSet.has(part)) + throw new InternalError(); + partNumberSet.add(part); + } + let uploadedPartRows = stmtListPartsByUploadId({ upload_id }), uploadedParts = /* @__PURE__ */ new Map(); + for (let row of uploadedPartRows) + uploadedParts.set(row.part_number, row); + let parts = selectedParts.map((selectedPart) => { + let uploadedPart = uploadedParts.get(selectedPart.part); + if (uploadedPart?.etag !== selectedPart.etag) + throw new InvalidPart(); + return uploadedPart; + }); + for (let part of parts.slice(0, -1)) + if (part.size < minPartSize) + throw new EntityTooSmall(); + parts.sort((a, b) => a.part_number - b.part_number); + let partSize; + for (let part of parts.slice(0, -1)) + if (partSize ??= part.size, part.size < minPartSize || part.size !== partSize) + throw new BadUpload(); + if (partSize !== void 0 && parts[parts.length - 1].size > partSize) + throw new BadUpload(); + let oldBlobIds = [], maybeOldBlobId = get(stmtGetPreviousByKey({ key }))?.blob_id; + if (maybeOldBlobId === null) { + let partRows2 = stmtDeletePartsByKey({ object_key: key }); + for (let partRow of partRows2) + oldBlobIds.push(partRow.blob_id); + } else + maybeOldBlobId !== void 0 && oldBlobIds.push(maybeOldBlobId); + let totalSize = parts.reduce((acc, { size }) => acc + size, 0), etag = generateMultipartEtag( + parts.map(({ checksum_md5 }) => checksum_md5) + ), newRow = { + key, + blob_id: null, + version: generateVersion(), + size: totalSize, + etag, + uploaded: Date.now(), + checksums: "{}", + http_metadata: uploadRow.http_metadata, + custom_metadata: uploadRow.custom_metadata + }; + stmtPut(newRow); + for (let part of parts) + stmtLinkPart({ + upload_id, + part_number: part.part_number, + object_key: key + }); + let partRows = stmtDeleteUnlinkedPartsByUploadId({ upload_id }); + for (let partRow of partRows) + oldBlobIds.push(partRow.blob_id); + return stmtUpdateUploadState({ + upload_id, + state: MultipartUploadState.COMPLETED + }), { newRow, oldBlobIds }; + } + ), + abortMultipartUpload: db.txn((key, upload_id) => { + let uploadRow = get(stmtGetUploadState({ key, upload_id })); + if (uploadRow === void 0) + throw new InternalError(); + if (uploadRow.state > MultipartUploadState.IN_PROGRESS) + return []; + let oldBlobIds = all(stmtDeletePartsByUploadId({ upload_id })).map(({ blob_id }) => blob_id); + return stmtUpdateUploadState({ + upload_id, + state: MultipartUploadState.ABORTED + }), oldBlobIds; + }) + }; +} +var R2BucketObject = class extends MiniflareDurableObject { + #stmts; + // Multipart uploads are stored as multiple blobs. Therefore, when reading a + // multipart upload, we'll be reading multiple blobs. When an object is + // deleted, all its blobs are deleted in the background. + // + // Normally for single part objects, this is fine, since we'd open a handle to + // a single blob, which we'd have until we closed it, at which point the blob + // may be deleted. With multipart, we don't want to open handles for all blobs + // as we could hit open file descriptor limits. Similarly, we don't want to + // read all blobs first, as we'd have to buffer them. + // + // Instead, we set up in-process locking on blobs needed for multipart reads. + // When we start a multipart read, we acquire all the blobs we need, then + // release them as we've streamed each part. Multiple multipart reads may be + // in-progress at any given time, so we use a wait group. + // + // This assumes we only ever have a single Miniflare instance operating on a + // blob store, which is always true for in-memory stores, and usually true for + // on-disk ones. If we really wanted to do this properly, we could store the + // bookkeeping for the wait group in SQLite, but then we'd have to implement + // some inter-process signalling/subscription system. + #inUseBlobs = /* @__PURE__ */ new Map(); + constructor(state, env) { + super(state, env), this.db.exec("PRAGMA case_sensitive_like = TRUE"), this.db.exec(SQL_SCHEMA), this.#stmts = sqlStmts(this.db); + } + #acquireBlob(blobId) { + let waitGroup = this.#inUseBlobs.get(blobId); + waitGroup === void 0 ? (waitGroup = new WaitGroup(), this.#inUseBlobs.set(blobId, waitGroup), waitGroup.add(), waitGroup.wait().then(() => this.#inUseBlobs.delete(blobId))) : waitGroup.add(); + } + #releaseBlob(blobId) { + this.#inUseBlobs.get(blobId)?.done(); + } + #backgroundDelete(blobId) { + this.timers.queueMicrotask(async () => (await this.#inUseBlobs.get(blobId)?.wait(), this.blob.delete(blobId).catch((e) => { + console.error("R2BucketObject##backgroundDelete():", e); + }))); + } + #assembleMultipartValue(parts, queryRange) { + let requiredParts = [], start = 0; + for (let part of parts) { + let partRange = { start, end: start + part.size - 1 }; + if (rangeOverlaps(partRange, queryRange)) { + let range = { + start: Math.max(partRange.start, queryRange.start) - partRange.start, + end: Math.min(partRange.end, queryRange.end) - partRange.start + }; + this.#acquireBlob(part.blob_id), requiredParts.push({ blobId: part.blob_id, range }); + } + start = partRange.end + 1; + } + let identity2 = new TransformStream(); + return (async () => { + let i = 0; + try { + for (; i < requiredParts.length; i++) { + let { blobId, range } = requiredParts[i], value = await this.blob.get(blobId, range), msg = `Expected to find blob "${blobId}" for multipart value`; + assert2(value !== null, msg), await value.pipeTo(identity2.writable, { preventClose: !0 }), this.#releaseBlob(blobId); + } + await identity2.writable.close(); + } catch (e) { + await identity2.writable.abort(e); + } finally { + for (; i < requiredParts.length; i++) + this.#releaseBlob(requiredParts[i].blobId); + } + })(), identity2.readable; + } + async #head(key) { + validate.key(key); + let row = get(this.#stmts.getByKey({ key })); + if (row === void 0) + throw new NoSuchKey(); + let range = { offset: 0, length: row.size }; + return new InternalR2Object(row, range); + } + async #get(key, opts) { + validate.key(key); + let result = this.#stmts.getPartsByKey(key); + if (result === void 0) + throw new NoSuchKey(); + let { row, parts } = result, defaultR2Range = { offset: 0, length: row.size }; + try { + validate.condition(row, opts.onlyIf); + } catch (e) { + throw e instanceof PreconditionFailed && e.attach(new InternalR2Object(row, defaultR2Range)), e; + } + let range = validate.range(opts, row.size), r2Range; + if (range === void 0) + r2Range = defaultR2Range; + else { + let start = range.start, end = Math.min(range.end, row.size); + r2Range = { offset: start, length: end - start + 1 }; + } + let value; + if (row.blob_id === null) { + assert2(parts !== void 0); + let defaultRange = { start: 0, end: row.size - 1 }; + value = this.#assembleMultipartValue(parts, range ?? defaultRange); + } else if (value = await this.blob.get(row.blob_id, range), value === null) + throw new NoSuchKey(); + return new InternalR2ObjectBody(row, value, r2Range); + } + async #put(key, value, valueSize, opts) { + let algorithms = []; + for (let { name, field } of R2_HASH_ALGORITHMS) + (field === "md5" || opts[field] !== void 0) && algorithms.push(name); + let digesting = new DigestingStream(algorithms), blobId = await this.blob.put(value.pipeThrough(digesting)), digests = await digesting.digests, md5Digest = digests.get("MD5"); + assert2(md5Digest !== void 0); + let md5DigestHex = md5Digest.toString("hex"), checksums = validate.key(key).size(valueSize).metadataSize(opts.customMetadata).hash(digests, opts), row = { + key, + blob_id: blobId, + version: generateVersion(), + size: valueSize, + etag: md5DigestHex, + uploaded: Date.now(), + checksums: JSON.stringify(checksums), + http_metadata: JSON.stringify(opts.httpMetadata ?? {}), + custom_metadata: JSON.stringify(opts.customMetadata ?? {}) + }, oldBlobIds; + try { + oldBlobIds = this.#stmts.put(row, opts.onlyIf); + } catch (e) { + throw this.#backgroundDelete(blobId), e; + } + if (oldBlobIds !== void 0) + for (let blobId2 of oldBlobIds) + this.#backgroundDelete(blobId2); + return new InternalR2Object(row); + } + #delete(keys) { + Array.isArray(keys) || (keys = [keys]); + for (let key of keys) + validate.key(key); + let oldBlobIds = this.#stmts.deleteByKeys(keys); + for (let blobId of oldBlobIds) + this.#backgroundDelete(blobId); + } + #listWithoutDelimiterQuery(excludeHttp, excludeCustom) { + return excludeHttp && excludeCustom ? this.#stmts.listWithoutDelimiter : excludeHttp ? this.#stmts.listCustomMetadataWithoutDelimiter : excludeCustom ? this.#stmts.listHttpMetadataWithoutDelimiter : this.#stmts.listHttpCustomMetadataWithoutDelimiter; + } + async #list(opts) { + let prefix = opts.prefix ?? "", limit = opts.limit ?? R2Limits.MAX_LIST_KEYS; + validate.limit(limit); + let include = opts.include ?? []; + include.length > 0 && (limit = Math.min(limit, 100)); + let excludeHttp = !include.includes("httpMetadata"), excludeCustom = !include.includes("customMetadata"), rowObject = (row) => ((row.http_metadata === void 0 || excludeHttp) && (row.http_metadata = "{}"), (row.custom_metadata === void 0 || excludeCustom) && (row.custom_metadata = "{}"), new InternalR2Object(row)), startAfter = opts.startAfter; + if (opts.cursor !== void 0) { + let cursorStartAfter = base64Decode(opts.cursor); + (startAfter === void 0 || cursorStartAfter > startAfter) && (startAfter = cursorStartAfter); + } + let delimiter = opts.delimiter; + delimiter === "" && (delimiter = void 0); + let params = { + escaped_prefix: escapeLike(prefix), + start_after: startAfter ?? null, + // Increase the queried limit by 1, if we return this many results, we + // know there are more rows. We'll truncate to the original limit before + // returning results. + limit: limit + 1 + }, objects, delimitedPrefixes = [], nextCursorStartAfter; + if (delimiter !== void 0) { + let rows = all( + this.#stmts.listMetadata({ ...params, prefix, delimiter }) + ), hasMoreRows = rows.length === limit + 1; + rows.splice(limit, 1), objects = []; + for (let row of rows) + row.delimited_prefix_or_key.startsWith("dlp:") ? delimitedPrefixes.push(row.delimited_prefix_or_key.substring(4)) : objects.push(rowObject({ ...row, key: row.last_key })); + hasMoreRows && (nextCursorStartAfter = rows[limit - 1].last_key); + } else { + let query = this.#listWithoutDelimiterQuery(excludeHttp, excludeCustom), rows = all(query(params)), hasMoreRows = rows.length === limit + 1; + rows.splice(limit, 1), objects = rows.map(rowObject), hasMoreRows && (nextCursorStartAfter = rows[limit - 1].key); + } + let nextCursor = maybeApply(base64Encode, nextCursorStartAfter); + return { + objects, + truncated: nextCursor !== void 0, + cursor: nextCursor, + delimitedPrefixes + }; + } + async #createMultipartUpload(key, opts) { + validate.key(key); + let uploadId = generateId(); + return this.#stmts.createMultipartUpload({ + key, + upload_id: uploadId, + http_metadata: JSON.stringify(opts.httpMetadata ?? {}), + custom_metadata: JSON.stringify(opts.customMetadata ?? {}) + }), { uploadId }; + } + async #uploadPart(key, uploadId, partNumber, value, valueSize) { + validate.key(key); + let digesting = new DigestingStream(["MD5"]), blobId = await this.blob.put(value.pipeThrough(digesting)), md5Digest = (await digesting.digests).get("MD5"); + assert2(md5Digest !== void 0); + let etag = generateId(), maybeOldBlobId; + try { + maybeOldBlobId = this.#stmts.putPart(key, { + upload_id: uploadId, + part_number: partNumber, + blob_id: blobId, + size: valueSize, + etag, + checksum_md5: md5Digest.toString("hex") + }); + } catch (e) { + throw this.#backgroundDelete(blobId), e; + } + return maybeOldBlobId !== void 0 && this.#backgroundDelete(maybeOldBlobId), { etag }; + } + async #completeMultipartUpload(key, uploadId, parts) { + validate.key(key); + let minPartSize = this.beingTested ? R2Limits.MIN_MULTIPART_PART_SIZE_TEST : R2Limits.MIN_MULTIPART_PART_SIZE, { newRow, oldBlobIds } = this.#stmts.completeMultipartUpload( + key, + uploadId, + parts, + minPartSize + ); + for (let blobId of oldBlobIds) + this.#backgroundDelete(blobId); + return new InternalR2Object(newRow); + } + async #abortMultipartUpload(key, uploadId) { + validate.key(key); + let oldBlobIds = this.#stmts.abortMultipartUpload(key, uploadId); + for (let blobId of oldBlobIds) + this.#backgroundDelete(blobId); + } + get = async (req) => { + let metadata = decodeHeaderMetadata(req), result; + if (metadata.method === "head") + result = await this.#head(metadata.object); + else if (metadata.method === "get") + result = await this.#get(metadata.object, metadata); + else if (metadata.method === "list") + result = await this.#list(metadata); + else + throw new InternalError(); + return encodeResult(result); + }; + put = async (req) => { + let { metadata, metadataSize, value } = await decodeMetadata(req); + if (metadata.method === "delete") + return await this.#delete( + "object" in metadata ? metadata.object : metadata.objects + ), new Response(); + if (metadata.method === "put") { + let contentLength = parseInt(req.headers.get("Content-Length")); + assert2(!isNaN(contentLength)); + let valueSize = contentLength - metadataSize, result = await this.#put( + metadata.object, + value, + valueSize, + metadata + ); + return encodeResult(result); + } else if (metadata.method === "createMultipartUpload") { + let result = await this.#createMultipartUpload( + metadata.object, + metadata + ); + return encodeJSONResult(result); + } else if (metadata.method === "uploadPart") { + let contentLength = parseInt(req.headers.get("Content-Length")); + assert2(!isNaN(contentLength)); + let valueSize = contentLength - metadataSize, result = await this.#uploadPart( + metadata.object, + metadata.uploadId, + metadata.partNumber, + value, + valueSize + ); + return encodeJSONResult(result); + } else if (metadata.method === "completeMultipartUpload") { + let result = await this.#completeMultipartUpload( + metadata.object, + metadata.uploadId, + metadata.parts + ); + return encodeResult(result); + } else { + if (metadata.method === "abortMultipartUpload") + return await this.#abortMultipartUpload(metadata.object, metadata.uploadId), new Response(); + throw new InternalError(); + } + }; +}; +__decorateClass([ + GET("/") +], R2BucketObject.prototype, "get", 2), __decorateClass([ + PUT("/") +], R2BucketObject.prototype, "put", 2); +export { + R2BucketObject +}; +//# sourceMappingURL=bucket.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js.map b/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js.map new file mode 100644 index 0000000..d0c6155 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/r2/bucket.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/r2/bucket.worker.ts", "../../../../src/workers/r2/constants.ts", "../../../../src/workers/r2/errors.worker.ts", "../../../../src/workers/r2/r2Object.worker.ts", "../../../../src/workers/r2/schemas.worker.ts", "../../../../src/workers/r2/validator.worker.ts"], + "mappings": ";;;;;;;;;AAAA,OAAOA,aAAY;AACnB,SAAS,UAAAC,eAAc;AACvB,SAAS,kBAAkB;AAC3B;AAAA,EAEE;AAAA,EACA;AAAA,EAEA;AAAA,EAEA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACrBA,IAAM,WAAW;AAAA,EACtB,eAAe;AAAA,EACf,cAAc;AAAA;AAAA,EAEd,gBAAgB;AAAA;AAAA,EAChB,mBAAmB;AAAA;AAAA,EACnB,yBAAyB;AAAA,EACzB,8BAA8B;AAChC,GAEa,YAAY;AAAA,EACvB,OAAO;AAAA,EACP,SAAS;AAAA,EACT,eAAe;AACjB;;;ACbA,SAAS,iBAAiB;AAI1B,IAAM,cAAc;AAAA,EAClB,gBAAgB;AAAA,EAChB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EACrB,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,qBAAqB;AAAA,EACrB,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,YAAY;AACd,GAEa,UAAN,cAAsB,UAAU;AAAA,EAGrC,YAAY,MAAc,SAA0B,QAAgB;AAClE,UAAM,MAAM,OAAO;AAD+B;AAAA,EAEpD;AAAA,EAJA;AAAA,EAMA,aAAa;AACX,QAAI,KAAK,WAAW,QAAW;AAC7B,UAAM,E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ert", "partRows", "identity", "blobId"] +} diff --git a/node_modules/miniflare/dist/src/workers/shared/index.worker.js b/node_modules/miniflare/dist/src/workers/shared/index.worker.js new file mode 100644 index 0000000..1fb902c --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/index.worker.js @@ -0,0 +1,706 @@ +// packages/miniflare/src/workers/shared/blob.worker.ts +import assert from "node-internal:internal_assert"; +import { Buffer as Buffer2 } from "node-internal:internal_buffer"; + +// packages/miniflare/src/workers/shared/data.ts +import { Buffer } from "node-internal:internal_buffer"; +function viewToBuffer(view) { + return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength); +} +function base64Encode(value) { + return Buffer.from(value, "utf8").toString("base64"); +} +function base64Decode(encoded) { + return Buffer.from(encoded, "base64").toString("utf8"); +} +var dotRegexp = /(^|\/|\\)(\.+)(\/|\\|$)/g, illegalRegexp = /[?<>*"'^/\\:|\x00-\x1f\x80-\x9f]/g, windowsReservedRegexp = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i, leadingRegexp = /^[ /\\]+/, trailingRegexp = /[ /\\]+$/; +function dotReplacement(match, g1, g2, g3) { + return `${g1}${"".padStart(g2.length, "_")}${g3}`; +} +function underscoreReplacement(match) { + return "".padStart(match.length, "_"); +} +function sanitisePath(unsafe) { + return unsafe.replace(dotRegexp, dotReplacement).replace(dotRegexp, dotReplacement).replace(illegalRegexp, "_").replace(windowsReservedRegexp, "_").replace(leadingRegexp, underscoreReplacement).replace(trailingRegexp, underscoreReplacement).substring(0, 255); +} + +// packages/miniflare/src/workers/shared/blob.worker.ts +var ENCODER = new TextEncoder(); +async function readPrefix(stream, prefixLength) { + let reader = await stream.getReader({ mode: "byob" }), result = await reader.readAtLeast( + prefixLength, + new Uint8Array(prefixLength) + ); + assert(result.value !== void 0), reader.releaseLock(); + let rest = stream.pipeThrough(new IdentityTransformStream()); + return [result.value, rest]; +} +function rangeHeaders(range) { + return { Range: `bytes=${range.start}-${range.end}` }; +} +function assertFullRangeRequest(range, contentLength) { + assert( + range.start === 0 && range.end === contentLength - 1, + "Received full content, but requested partial content" + ); +} +async function fetchSingleRange(fetcher, url, range) { + let headers = range === void 0 ? {} : rangeHeaders(range), res = await fetcher.fetch(url, { headers }); + if (res.status === 404) + return null; + if (assert(res.ok && res.body !== null), range !== void 0 && res.status !== 206) { + let contentLength = parseInt(res.headers.get("Content-Length")); + assert(!Number.isNaN(contentLength)), assertFullRangeRequest(range, contentLength); + } + return res.body; +} +async function writeMultipleRanges(fetcher, url, ranges, boundary, writable, contentLength, contentType) { + for (let i = 0; i < ranges.length; i++) { + let range = ranges[i], writer2 = writable.getWriter(); + i > 0 && await writer2.write(ENCODER.encode(`\r +`)), await writer2.write(ENCODER.encode(`--${boundary}\r +`)), contentType !== void 0 && await writer2.write(ENCODER.encode(`Content-Type: ${contentType}\r +`)); + let start = range.start, end = Math.min(range.end, contentLength - 1); + await writer2.write( + ENCODER.encode( + `Content-Range: bytes ${start}-${end}/${contentLength}\r +\r +` + ) + ), writer2.releaseLock(); + let res = await fetcher.fetch(url, { headers: rangeHeaders(range) }); + assert( + res.ok && res.body !== null, + `Failed to fetch ${url}[${range.start},${range.end}], received ${res.status} ${res.statusText}` + ), res.status !== 206 && assertFullRangeRequest(range, contentLength), await res.body.pipeTo(writable, { preventClose: !0 }); + } + let writer = writable.getWriter(); + ranges.length > 0 && await writer.write(ENCODER.encode(`\r +`)), await writer.write(ENCODER.encode(`--${boundary}--`)), await writer.close(); +} +async function fetchMultipleRanges(fetcher, url, ranges, opts) { + let res = await fetcher.fetch(url, { method: "HEAD" }); + if (res.status === 404) + return null; + assert(res.ok); + let contentLength = parseInt(res.headers.get("Content-Length")); + assert(!Number.isNaN(contentLength)); + let boundary = `miniflare-boundary-${crypto.randomUUID()}`, multipartContentType = `multipart/byteranges; boundary=${boundary}`, { readable, writable } = new IdentityTransformStream(); + return writeMultipleRanges( + fetcher, + url, + ranges, + boundary, + writable, + contentLength, + opts?.contentType + ).catch((e) => console.error("Error writing multipart stream:", e)), { multipartContentType, body: readable }; +} +async function fetchRange(fetcher, url, range, opts) { + return Array.isArray(range) ? fetchMultipleRanges(fetcher, url, range, opts) : fetchSingleRange(fetcher, url, range); +} +function generateBlobId() { + let idBuffer = Buffer2.alloc(40); + return crypto.getRandomValues( + new Uint8Array(idBuffer.buffer, idBuffer.byteOffset, 32) + ), idBuffer.writeBigInt64BE( + BigInt(performance.timeOrigin + performance.now()), + 32 + ), idBuffer.toString("hex"); +} +var BlobStore = class { + // Database for binary large objects. Provides single and multi-ranged + // streaming reads and writes. + // + // Blobs have unguessable identifiers, can be deleted, but are otherwise + // immutable. These properties make it possible to perform atomic updates with + // the SQLite metadata store. No other operations will be able to interact + // with the blob until it's committed to the metadata store, because they + // won't be able to guess the ID, and we don't allow listing blobs. + // + // For example, if we put a blob in the store, then fail to insert the blob ID + // into the SQLite database for some reason during a transaction (e.g. + // `onlyIf` condition failed), no other operations can read that blob because + // the ID is lost (we'll just background-delete the blob in this case). + #fetcher; + #baseURL; + constructor(fetcher, namespace) { + namespace = encodeURIComponent(sanitisePath(namespace)), this.#fetcher = fetcher, this.#baseURL = `http://placeholder/${namespace}/blobs/`; + } + idURL(id) { + let url = new URL(this.#baseURL + id); + return url.toString().startsWith(this.#baseURL) ? url : null; + } + async get(id, range, opts) { + let idURL = this.idURL(id); + return idURL === null ? null : fetchRange(this.#fetcher, idURL, range, opts); + } + async put(stream) { + let id = generateBlobId(), idURL = this.idURL(id); + return assert(idURL !== null), await this.#fetcher.fetch(idURL, { + method: "PUT", + body: stream + }), id; + } + async delete(id) { + let idURL = this.idURL(id); + if (idURL === null) + return; + let res = await this.#fetcher.fetch(idURL, { method: "DELETE" }); + assert(res.ok || res.status === 404); + } +}; + +// packages/miniflare/src/workers/shared/constants.ts +var SharedHeaders = { + LOG_LEVEL: "MF-Log-Level" +}, SharedBindings = { + TEXT_NAMESPACE: "MINIFLARE_NAMESPACE", + DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT", + MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS", + MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK" +}, LogLevel = /* @__PURE__ */ ((LogLevel3) => (LogLevel3[LogLevel3.NONE = 0] = "NONE", LogLevel3[LogLevel3.ERROR = 1] = "ERROR", LogLevel3[LogLevel3.WARN = 2] = "WARN", LogLevel3[LogLevel3.INFO = 3] = "INFO", LogLevel3[LogLevel3.DEBUG = 4] = "DEBUG", LogLevel3[LogLevel3.VERBOSE = 5] = "VERBOSE", LogLevel3))(LogLevel || {}); + +// packages/miniflare/src/workers/shared/keyvalue.worker.ts +import assert3 from "node-internal:internal_assert"; + +// packages/miniflare/src/workers/shared/sql.worker.ts +import assert2 from "node-internal:internal_assert"; +function isTypedValue(value) { + return value === null || typeof value == "string" || typeof value == "number" || value instanceof ArrayBuffer; +} +function createStatementFactory(sql) { + return (query) => { + let keyIndices = /* @__PURE__ */ new Map(); + query = query.replace(/[:@$]([a-z0-9_]+)/gi, (_, name) => { + let index = keyIndices.get(name); + return index === void 0 && (index = keyIndices.size, keyIndices.set(name, index)), `?${index + 1}`; + }); + let stmt = sql.prepare(query); + return (argsObject) => { + let entries = Object.entries(argsObject); + assert2.strictEqual( + entries.length, + keyIndices.size, + "Expected same number of keys in bindings and query" + ); + let argsArray = new Array(entries.length); + for (let [key, value] of entries) { + let index = keyIndices.get(key); + assert2(index !== void 0, `Unexpected binding key: ${key}`), argsArray[index] = value; + } + return stmt(...argsArray); + }; + }; +} +function createTransactionFactory(storage) { + return (closure) => (...args) => storage.transactionSync(() => closure(...args)); +} +function createTypedSql(storage) { + let sql = storage.sql; + return sql.stmt = createStatementFactory(sql), sql.txn = createTransactionFactory(storage), sql; +} +function get(cursor) { + let result; + for (let row of cursor) + result ??= row; + return result; +} +function all(cursor) { + return Array.from(cursor); +} +function drain(cursor) { + for (let _ of cursor) + ; +} +function escapeLike(prefix) { + return prefix.replace(/[\\_%]/g, "\\$&"); +} + +// packages/miniflare/src/workers/shared/keyvalue.worker.ts +var SQL_SCHEMA = ` +CREATE TABLE IF NOT EXISTS _mf_entries ( + key TEXT PRIMARY KEY, + blob_id TEXT NOT NULL, + expiration INTEGER, + metadata TEXT +); +CREATE INDEX IF NOT EXISTS _mf_entries_expiration_idx ON _mf_entries(expiration); +`; +function sqlStmts(db) { + let stmtGetBlobIdByKey = db.stmt( + "SELECT blob_id FROM _mf_entries WHERE :key" + ), stmtPut = db.stmt( + `INSERT OR REPLACE INTO _mf_entries (key, blob_id, expiration, metadata) + VALUES (:key, :blob_id, :expiration, :metadata)` + ); + return { + getByKey: db.prepare( + "SELECT key, blob_id, expiration, metadata FROM _mf_entries WHERE key = ?1" + ), + put: db.txn((newEntry) => { + let key = newEntry.key, previousEntry = get(stmtGetBlobIdByKey({ key })); + return stmtPut(newEntry), previousEntry?.blob_id; + }), + deleteByKey: db.stmt( + "DELETE FROM _mf_entries WHERE key = :key RETURNING blob_id, expiration" + ), + deleteExpired: db.stmt( + // `expiration` may be `NULL`, but `NULL < ...` should be falsy + "DELETE FROM _mf_entries WHERE expiration < :now RETURNING blob_id" + ), + list: db.stmt( + `SELECT key, expiration, metadata FROM _mf_entries + WHERE key LIKE :escaped_prefix || '%' ESCAPE '\\' + AND key > :start_after + AND (expiration IS NULL OR expiration >= :now) + ORDER BY key LIMIT :limit` + ) + }; +} +function escapePrefix(prefix) { + return prefix.replace(/[\\_%]/g, "\\$&"); +} +function rowEntry(entry) { + return { + key: entry.key, + expiration: entry.expiration ?? void 0, + metadata: entry.metadata === null ? void 0 : JSON.parse(entry.metadata) + }; +} +var KeyValueStorage = class { + #stmts; + #blob; + #timers; + constructor(object) { + object.db.exec("PRAGMA case_sensitive_like = TRUE"), object.db.exec(SQL_SCHEMA), this.#stmts = sqlStmts(object.db), this.#blob = object.blob, this.#timers = object.timers; + } + #hasExpired(entry) { + return entry.expiration !== null && entry.expiration <= this.#timers.now(); + } + #backgroundDelete(blobId) { + this.#timers.queueMicrotask( + () => this.#blob.delete(blobId).catch(() => { + }) + ); + } + async get(key, optsFactory) { + let row = get(this.#stmts.getByKey(key)); + if (row === void 0) + return null; + if (this.#hasExpired(row)) + return drain(this.#stmts.deleteByKey({ key })), this.#backgroundDelete(row.blob_id), null; + let entry = rowEntry(row), opts = entry.metadata && optsFactory?.(entry.metadata); + if (opts?.ranges === void 0 || opts.ranges.length <= 1) { + let value = await this.#blob.get(row.blob_id, opts?.ranges?.[0]); + return value === null ? null : { ...entry, value }; + } else { + let value = await this.#blob.get(row.blob_id, opts.ranges, opts); + return value === null ? null : { ...entry, value }; + } + } + async put(entry) { + assert3(entry.key !== ""); + let blobId = await this.#blob.put(entry.value); + entry.signal?.aborted && (this.#backgroundDelete(blobId), entry.signal.throwIfAborted()); + let maybeOldBlobId = this.#stmts.put({ + key: entry.key, + blob_id: blobId, + expiration: entry.expiration ?? null, + metadata: entry.metadata === void 0 ? null : JSON.stringify(await entry.metadata) + }); + maybeOldBlobId !== void 0 && this.#backgroundDelete(maybeOldBlobId); + } + async delete(key) { + let cursor = this.#stmts.deleteByKey({ key }), row = get(cursor); + return row === void 0 ? !1 : (this.#backgroundDelete(row.blob_id), !this.#hasExpired(row)); + } + async list(opts) { + let now = this.#timers.now(), escaped_prefix = escapePrefix(opts.prefix ?? ""), start_after = opts.cursor === void 0 ? "" : base64Decode(opts.cursor), limit = opts.limit + 1, rowsCursor = this.#stmts.list({ + now, + escaped_prefix, + start_after, + limit + }), rows = Array.from(rowsCursor), expiredRows = this.#stmts.deleteExpired({ now }); + for (let row of expiredRows) + this.#backgroundDelete(row.blob_id); + let hasMoreRows = rows.length === opts.limit + 1; + rows.splice(opts.limit, 1); + let keys = rows.map((row) => rowEntry(row)), nextCursor = hasMoreRows ? base64Encode(rows[opts.limit - 1].key) : void 0; + return { keys, cursor: nextCursor }; + } +}; + +// packages/miniflare/src/workers/shared/matcher.ts +function testRegExps(matcher, value) { + for (let exclude of matcher.exclude) + if (exclude.test(value)) + return !1; + for (let include of matcher.include) + if (include.test(value)) + return !0; + return !1; +} + +// packages/miniflare/src/workers/shared/object.worker.ts +import assert5 from "node-internal:internal_assert"; + +// packages/miniflare/src/workers/shared/router.worker.ts +var HttpError = class extends Error { + constructor(code, message) { + super(message); + this.code = code; + Object.setPrototypeOf(this, new.target.prototype), this.name = `${new.target.name} [${code}]`; + } + toResponse() { + return new Response(this.message, { + status: this.code, + // Custom statusMessage is required for runtime error messages + statusText: this.message.substring(0, 512) + }); + } +}, kRoutesTemplate = Symbol("kRoutesTemplate"), Router = class { + // Routes added by @METHOD decorators + #routes; + constructor() { + this.#routes = new.target.prototype[kRoutesTemplate]; + } + async fetch(req) { + let url = new URL(req.url), methodRoutes = this.#routes?.get(req.method); + if (methodRoutes === void 0) + return new Response(null, { status: 405 }); + let handlers = this; + try { + for (let [path, key] of methodRoutes) { + let match = path.exec(url.pathname); + if (match !== null) + return await handlers[key](req, match.groups, url); + } + return new Response(null, { status: 404 }); + } catch (e) { + if (e instanceof HttpError) + return e.toResponse(); + throw e; + } + } +}; +function pathToRegexp(path) { + return path === void 0 ? /^.*$/ : (path.endsWith("/") || (path += "/?"), path = path.replace(/\//g, "\\/"), path = path.replace(/:(\w+)/g, "(?<$1>[^\\/]+)"), new RegExp(`^${path}$`)); +} +var createRouteDecorator = (method) => (path) => (prototype, key) => { + let route = [pathToRegexp(path), key], routes = prototype[kRoutesTemplate] ??= /* @__PURE__ */ new Map(), methodRoutes = routes.get(method); + methodRoutes ? methodRoutes.push(route) : routes.set(method, [route]); +}, GET = createRouteDecorator("GET"), HEAD = createRouteDecorator("HEAD"), POST = createRouteDecorator("POST"), PUT = createRouteDecorator("PUT"), DELETE = createRouteDecorator("DELETE"), PURGE = createRouteDecorator("PURGE"), PATCH = createRouteDecorator("PATCH"); + +// packages/miniflare/src/workers/shared/timers.worker.ts +import assert4 from "node-internal:internal_assert"; +var kFakeTimerHandle = Symbol("kFakeTimerHandle"), Timers = class { + // Fake unix time in milliseconds. If defined, fake timers will be enabled. + #fakeTimestamp; + #fakeNextTimerHandle = 0; + #fakePendingTimeouts = /* @__PURE__ */ new Map(); + #fakeRunningTasks = /* @__PURE__ */ new Set(); + // Timers API + now = () => this.#fakeTimestamp ?? Date.now(); + setTimeout(closure, delay, ...args) { + if (this.#fakeTimestamp === void 0) + return setTimeout(closure, delay, ...args); + let handle = this.#fakeNextTimerHandle++, argsClosure = () => closure(...args); + if (delay === 0) + this.queueMicrotask(argsClosure); + else { + let timeout = { + triggerTimestamp: this.#fakeTimestamp + delay, + closure: argsClosure + }; + this.#fakePendingTimeouts.set(handle, timeout); + } + return { [kFakeTimerHandle]: handle }; + } + clearTimeout(handle) { + if (typeof handle == "number") + return clearTimeout(handle); + this.#fakePendingTimeouts.delete(handle[kFakeTimerHandle]); + } + queueMicrotask(closure) { + if (this.#fakeTimestamp === void 0) + return queueMicrotask(closure); + let result = closure(); + result instanceof Promise && (this.#fakeRunningTasks.add(result), result.finally(() => this.#fakeRunningTasks.delete(result))); + } + // Fake Timers Control API + #runPendingTimeouts() { + if (this.#fakeTimestamp !== void 0) + for (let [handle, timeout] of this.#fakePendingTimeouts) + timeout.triggerTimestamp <= this.#fakeTimestamp && (this.#fakePendingTimeouts.delete(handle), this.queueMicrotask(timeout.closure)); + } + enableFakeTimers(timestamp) { + this.#fakeTimestamp = timestamp, this.#runPendingTimeouts(); + } + disableFakeTimers() { + this.#fakeTimestamp = void 0, this.#fakePendingTimeouts.clear(); + } + advanceFakeTime(delta) { + assert4( + this.#fakeTimestamp !== void 0, + "Expected fake timers to be enabled before `advanceFakeTime()` call" + ), this.#fakeTimestamp += delta, this.#runPendingTimeouts(); + } + async waitForFakeTasks() { + for (; this.#fakeRunningTasks.size > 0; ) + await Promise.all(this.#fakeRunningTasks); + } +}; + +// packages/miniflare/src/workers/shared/types.ts +function reduceError(e) { + return { + name: e?.name, + message: e?.message ?? String(e), + stack: e?.stack, + cause: e?.cause === void 0 ? void 0 : reduceError(e.cause) + }; +} +function maybeApply(f, maybeValue) { + return maybeValue === void 0 ? void 0 : f(maybeValue); +} + +// packages/miniflare/src/workers/shared/object.worker.ts +var MiniflareDurableObject = class extends Router { + constructor(state, env) { + super(); + this.state = state; + this.env = env; + } + timers = new Timers(); + // If this Durable Object receives a control op, assume it's being tested. + // We use this to adjust some limits in tests. + beingTested = !1; + #db; + get db() { + return this.#db ??= createTypedSql(this.state.storage); + } + #name; + get name() { + return assert5( + this.#name !== void 0, + "Expected `MiniflareDurableObject#fetch()` call before `name` access" + ), this.#name; + } + #blob; + get blob() { + if (this.#blob !== void 0) + return this.#blob; + let maybeBlobsService = this.env[SharedBindings.MAYBE_SERVICE_BLOBS]; + return assert5( + maybeBlobsService !== void 0, + `Expected ${SharedBindings.MAYBE_SERVICE_BLOBS} service binding` + ), this.#blob = new BlobStore(maybeBlobsService, this.name), this.#blob; + } + async logWithLevel(level, message) { + await this.env[SharedBindings.MAYBE_SERVICE_LOOPBACK]?.fetch( + "http://localhost/core/log", + { + method: "POST", + headers: { [SharedHeaders.LOG_LEVEL]: level.toString() }, + body: message + } + ); + } + async #handleControlOp({ + name, + args + }) { + if (this.beingTested = !0, name === "sqlQuery") { + assert5(args !== void 0); + let [query, ...params] = args; + assert5(typeof query == "string"), assert5(params.every(isTypedValue)); + let results = all(this.db.prepare(query)(...params)); + return Response.json(results); + } else if (name === "getBlob") { + assert5(args !== void 0); + let [id] = args; + assert5(typeof id == "string"); + let stream = await this.blob.get(id); + return new Response(stream, { status: stream === null ? 404 : 200 }); + } else { + let func = this.timers[name]; + assert5(typeof func == "function"); + let result = await func.apply(this.timers, args); + return Response.json(result ?? null); + } + } + async fetch(req) { + let controlOp = req?.cf?.miniflare?.controlOp; + if (controlOp !== void 0) + return this.#handleControlOp(controlOp); + let name = req.cf?.miniflare?.name; + assert5(name !== void 0, "Expected `cf.miniflare.name`"), this.#name = name; + try { + return await super.fetch(req); + } catch (e) { + let error = reduceError(e), fallback = error.stack ?? error.message, loopbackService = this.env[SharedBindings.MAYBE_SERVICE_LOOPBACK]; + return loopbackService !== void 0 ? loopbackService.fetch("http://localhost/core/error", { + method: "POST", + body: JSON.stringify(error) + }).catch(() => { + console.error(fallback); + }) : console.error(fallback), new Response(fallback, { status: 500 }); + } finally { + req.body !== null && !req.bodyUsed && await req.body.pipeTo(new WritableStream()); + } + } +}; + +// packages/miniflare/src/workers/shared/range.ts +var rangePrefixRegexp = /^ *bytes *=/i, rangeRegexp = /^ *(?\d+)? *- *(?\d+)? *$/; +function parseRanges(rangeHeader, length) { + let prefixMatch = rangePrefixRegexp.exec(rangeHeader); + if (prefixMatch === null) + return; + if (rangeHeader = rangeHeader.substring(prefixMatch[0].length), rangeHeader.trimStart() === "") + return []; + let ranges = rangeHeader.split(","), result = []; + for (let range of ranges) { + let match = rangeRegexp.exec(range); + if (match === null) + return; + let { start, end } = match.groups; + if (start !== void 0 && end !== void 0) { + let rangeStart = parseInt(start), rangeEnd = parseInt(end); + if (rangeStart > rangeEnd || rangeStart >= length) + return; + rangeEnd >= length && (rangeEnd = length - 1), result.push({ start: rangeStart, end: rangeEnd }); + } else if (start !== void 0 && end === void 0) { + let rangeStart = parseInt(start); + if (rangeStart >= length) + return; + result.push({ start: rangeStart, end: length - 1 }); + } else if (start === void 0 && end !== void 0) { + let suffix = parseInt(end); + if (suffix >= length) + return []; + if (suffix === 0) + continue; + result.push({ start: length - suffix, end: length - 1 }); + } else + return; + } + return result; +} + +// packages/miniflare/src/workers/shared/sync.ts +import assert6 from "node-internal:internal_assert"; +var DeferredPromise = class extends Promise { + resolve; + reject; + constructor(executor = () => { + }) { + let promiseResolve, promiseReject; + super((resolve, reject) => (promiseResolve = resolve, promiseReject = reject, executor(resolve, reject))), this.resolve = promiseResolve, this.reject = promiseReject; + } +}, Mutex = class { + locked = !1; + resolveQueue = []; + drainQueue = []; + lock() { + if (!this.locked) { + this.locked = !0; + return; + } + return new Promise((resolve) => this.resolveQueue.push(resolve)); + } + unlock() { + if (assert6(this.locked), this.resolveQueue.length > 0) + this.resolveQueue.shift()?.(); + else { + this.locked = !1; + let resolve; + for (; (resolve = this.drainQueue.shift()) !== void 0; ) + resolve(); + } + } + get hasWaiting() { + return this.resolveQueue.length > 0; + } + async runWith(closure) { + let acquireAwaitable = this.lock(); + acquireAwaitable instanceof Promise && await acquireAwaitable; + try { + let awaitable = closure(); + return awaitable instanceof Promise ? await awaitable : awaitable; + } finally { + this.unlock(); + } + } + async drained() { + if (this.resolveQueue.length !== 0) + return new Promise((resolve) => this.drainQueue.push(resolve)); + } +}, WaitGroup = class { + counter = 0; + resolveQueue = []; + add() { + this.counter++; + } + done() { + if (assert6(this.counter > 0), this.counter--, this.counter === 0) { + let resolve; + for (; (resolve = this.resolveQueue.shift()) !== void 0; ) + resolve(); + } + } + wait() { + return this.counter === 0 ? Promise.resolve() : new Promise((resolve) => this.resolveQueue.push(resolve)); + } +}; +export { + BlobStore, + DELETE, + DeferredPromise, + GET, + HEAD, + HttpError, + KeyValueStorage, + LogLevel, + MiniflareDurableObject, + Mutex, + PATCH, + POST, + PURGE, + PUT, + Router, + SharedBindings, + SharedHeaders, + Timers, + WaitGroup, + all, + base64Decode, + base64Encode, + drain, + escapeLike, + get, + maybeApply, + parseRanges, + readPrefix, + reduceError, + testRegExps, + viewToBuffer +}; +/*! Path sanitisation regexps adapted from node-sanitize-filename: + * https://github.com/parshap/node-sanitize-filename/blob/209c39b914c8eb48ee27bcbde64b2c7822fdf3de/index.js#L4-L37 + * + * Licensed under the ISC license: + * + * Copyright Parsha Pourkhomami + * + * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the + * above copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ +//# sourceMappingURL=index.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/shared/index.worker.js.map b/node_modules/miniflare/dist/src/workers/shared/index.worker.js.map new file mode 100644 index 0000000..63ad169 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/index.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/shared/blob.worker.ts", "../../../../src/workers/shared/data.ts", "../../../../src/workers/shared/constants.ts", "../../../../src/workers/shared/keyvalue.worker.ts", "../../../../src/workers/shared/sql.worker.ts", "../../../../src/workers/shared/matcher.ts", "../../../../src/workers/shared/object.worker.ts", "../../../../src/workers/shared/router.worker.ts", "../../../../src/workers/shared/timers.worker.ts", "../../../../src/workers/shared/types.ts", "../../../../src/workers/shared/range.ts", "../../../../src/workers/shared/sync.ts"], + "mappings": ";AAAA,OAAO,YAAY;AACnB,SAAS,UAAAA,eAAc;;;ACDvB,SAAS,cAAc;AAEhB,SAAS,aAAa,MAAoC;AAC/D,SAAO,KAAK,OAAO,MAAM,KAAK,YAAY,KAAK,aAAa,KAAK,UAAU;AAC7E;AAEO,SAAS,aAAa,OAAuB;AAClD,SAAO,OAAO,KAAK,OAAO,MAAM,EAAE,SAAS,QAAQ;AACrD;AACO,SAAS,aAAa,SAAyB;AACpD,SAAO,OAAO,KAAK,SAAS,QAAQ,EAAE,SAAS,MAAM;AACvD;AAiBA,IAAM,YAAY,4BACZ,gBAAgB,qCAChB,wBAAwB,iDACxB,gBAAgB,YAChB,iBAAiB;AAEvB,SAAS,eAAe,OAAe,IAAY,IAAY,IAAY;AACzE,SAAO,GAAG,KAAK,GAAG,SAAS,GAAG,QAAQ,GAAG,IAA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ert", "assert", "assert", "assert", "assert"] +} diff --git a/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js b/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js new file mode 100644 index 0000000..d9763e3 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js @@ -0,0 +1,19 @@ +// packages/miniflare/src/workers/shared/constants.ts +var SharedBindings = { + TEXT_NAMESPACE: "MINIFLARE_NAMESPACE", + DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT", + MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS", + MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK" +}; + +// packages/miniflare/src/workers/shared/object-entry.worker.ts +var object_entry_worker_default = { + async fetch(request, env) { + let name = env[SharedBindings.TEXT_NAMESPACE], objectNamespace = env[SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT], id = objectNamespace.idFromName(name), stub = objectNamespace.get(id), cf = { miniflare: { name } }; + return await stub.fetch(request, { cf }); + } +}; +export { + object_entry_worker_default as default +}; +//# sourceMappingURL=object-entry.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js.map b/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js.map new file mode 100644 index 0000000..5d16e94 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/object-entry.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/shared/constants.ts", "../../../../src/workers/shared/object-entry.worker.ts"], + "mappings": ";AAIO,IAAM,iBAAiB;AAAA,EAC5B,gBAAgB;AAAA,EAChB,iCAAiC;AAAA,EACjC,qBAAqB;AAAA,EACrB,wBAAwB;AAC1B;;;ACDA,IAAO,8BAA8B;AAAA,EACnC,MAAM,MAAM,SAAS,KAAK;AACxB,QAAM,OAAO,IAAI,eAAe,cAAc,GACxC,kBAAkB,IAAI,eAAe,+BAA+B,GACpE,KAAK,gBAAgB,WAAW,IAAI,GACpC,OAAO,gBAAgB,IAAI,EAAE,GAC7B,KAA+B,EAAE,WAAW,EAAE,KAAK,EAAE;AAC3D,WAAO,MAAM,KAAK,MAAM,SAAS,EAAE,GAAkC,CAAC;AAAA,EACxE;AACF;", + "names": [] +} diff --git a/node_modules/miniflare/dist/src/workers/shared/zod.worker.js b/node_modules/miniflare/dist/src/workers/shared/zod.worker.js new file mode 100644 index 0000000..9cd18f1 --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/zod.worker.js @@ -0,0 +1,2486 @@ +// packages/miniflare/src/workers/shared/zod.worker.ts +import { Buffer } from "node-internal:internal_buffer"; + +// node_modules/zod/lib/index.mjs +var util; +(function(util2) { + util2.assertEqual = (val) => val; + function assertIs(_arg) { + } + util2.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util2.assertNever = assertNever, util2.arrayToEnum = (items) => { + let obj = {}; + for (let item of items) + obj[item] = item; + return obj; + }, util2.getValidEnumValues = (obj) => { + let validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] != "number"), filtered = {}; + for (let k of validKeys) + filtered[k] = obj[k]; + return util2.objectValues(filtered); + }, util2.objectValues = (obj) => util2.objectKeys(obj).map(function(e) { + return obj[e]; + }), util2.objectKeys = typeof Object.keys == "function" ? (obj) => Object.keys(obj) : (object) => { + let keys = []; + for (let key in object) + Object.prototype.hasOwnProperty.call(object, key) && keys.push(key); + return keys; + }, util2.find = (arr, checker) => { + for (let item of arr) + if (checker(item)) + return item; + }, util2.isInteger = typeof Number.isInteger == "function" ? (val) => Number.isInteger(val) : (val) => typeof val == "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => typeof val == "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues, util2.jsonStringifyReplacer = (_, value) => typeof value == "bigint" ? value.toString() : value; +})(util || (util = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]), getParsedType = (data) => { + switch (typeof data) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + return Array.isArray(data) ? ZodParsedType.array : data === null ? ZodParsedType.null : data.then && typeof data.then == "function" && data.catch && typeof data.catch == "function" ? ZodParsedType.promise : typeof Map < "u" && data instanceof Map ? ZodParsedType.map : typeof Set < "u" && data instanceof Set ? ZodParsedType.set : typeof Date < "u" && data instanceof Date ? ZodParsedType.date : ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}, ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]), quotelessJson = (obj) => JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:"), ZodError = class extends Error { + constructor(issues) { + super(), this.issues = [], this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }, this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + let actualProto = new.target.prototype; + Object.setPrototypeOf ? Object.setPrototypeOf(this, actualProto) : this.__proto__ = actualProto, this.name = "ZodError", this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + let mapper = _mapper || function(issue) { + return issue.message; + }, fieldErrors = { _errors: [] }, processError = (error) => { + for (let issue of error.issues) + if (issue.code === "invalid_union") + issue.unionErrors.map(processError); + else if (issue.code === "invalid_return_type") + processError(issue.returnTypeError); + else if (issue.code === "invalid_arguments") + processError(issue.argumentsError); + else if (issue.path.length === 0) + fieldErrors._errors.push(mapper(issue)); + else { + let curr = fieldErrors, i = 0; + for (; i < issue.path.length; ) { + let el = issue.path[i]; + i === issue.path.length - 1 ? (curr[el] = curr[el] || { _errors: [] }, curr[el]._errors.push(mapper(issue))) : curr[el] = curr[el] || { _errors: [] }, curr = curr[el], i++; + } + } + }; + return processError(this), fieldErrors; + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + let fieldErrors = {}, formErrors = []; + for (let sub of this.issues) + sub.path.length > 0 ? (fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [], fieldErrors[sub.path[0]].push(mapper(sub))) : formErrors.push(mapper(sub)); + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +}; +ZodError.create = (issues) => new ZodError(issues); +var errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + issue.received === ZodParsedType.undefined ? message = "Required" : message = `Expected ${issue.expected}, received ${issue.received}`; + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = "Invalid input"; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = "Invalid function arguments"; + break; + case ZodIssueCode.invalid_return_type: + message = "Invalid function return type"; + break; + case ZodIssueCode.invalid_date: + message = "Invalid date"; + break; + case ZodIssueCode.invalid_string: + typeof issue.validation == "object" ? "startsWith" in issue.validation ? message = `Invalid input: must start with "${issue.validation.startsWith}"` : "endsWith" in issue.validation ? message = `Invalid input: must end with "${issue.validation.endsWith}"` : util.assertNever(issue.validation) : issue.validation !== "regex" ? message = `Invalid ${issue.validation}` : message = "Invalid"; + break; + case ZodIssueCode.too_small: + issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "more than"} ${issue.minimum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "over"} ${issue.minimum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : issue.type === "date" ? message = `Date must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${new Date(issue.minimum)}` : message = "Invalid input"; + break; + case ZodIssueCode.too_big: + issue.type === "array" ? message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "less than"} ${issue.maximum} element(s)` : issue.type === "string" ? message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "under"} ${issue.maximum} character(s)` : issue.type === "number" ? message = `Number must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : issue.type === "date" ? message = `Date must be ${issue.exact ? "exactly" : issue.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(issue.maximum)}` : message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = "Invalid input"; + break; + case ZodIssueCode.invalid_intersection_types: + message = "Intersection results could not be merged"; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError, util.assertNever(issue); + } + return { message }; +}, overrideErrorMap = errorMap; +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} +var makeIssue = (params) => { + let { data, path, errorMaps, issueData } = params, fullPath = [...path, ...issueData.path || []], fullIssue = { + ...issueData, + path: fullPath + }, errorMessage = "", maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (let map of maps) + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + return { + ...issueData, + path: fullPath, + message: issueData.message || errorMessage + }; +}, EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + let issue = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + // then global default map + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue); +} +var ParseStatus = class { + constructor() { + this.value = "valid"; + } + dirty() { + this.value === "valid" && (this.value = "dirty"); + } + abort() { + this.value !== "aborted" && (this.value = "aborted"); + } + static mergeArray(status, results) { + let arrayValue = []; + for (let s of results) { + if (s.status === "aborted") + return INVALID; + s.status === "dirty" && status.dirty(), arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + let syncPairs = []; + for (let pair of pairs) + syncPairs.push({ + key: await pair.key, + value: await pair.value + }); + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + let finalObject = {}; + for (let pair of pairs) { + let { key, value } = pair; + if (key.status === "aborted" || value.status === "aborted") + return INVALID; + key.status === "dirty" && status.dirty(), value.status === "dirty" && status.dirty(), (typeof value.value < "u" || pair.alwaysSet) && (finalObject[key.value] = value.value); + } + return { status: status.value, value: finalObject }; + } +}, INVALID = Object.freeze({ + status: "aborted" +}), DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x) => x.status === "aborted", isDirty = (x) => x.status === "dirty", isValid = (x) => x.status === "valid", isAsync = (x) => typeof Promise < "u" && x instanceof Promise, errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message == "string" ? { message } : message || {}, errorUtil2.toString = (message) => typeof message == "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); +var ParseInputLazyPath = class { + constructor(parent, value, path, key) { + this.parent = parent, this.data = value, this._path = path, this._key = key; + } + get path() { + return this._path.concat(this._key); + } +}, handleResult = (ctx, result) => { + if (isValid(result)) + return { success: !0, data: result.value }; + if (!ctx.common.issues.length) + throw new Error("Validation failed but no issues detected."); + return { success: !1, error: new ZodError(ctx.common.issues) }; +}; +function processCreateParams(params) { + if (!params) + return {}; + let { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + return errorMap2 ? { errorMap: errorMap2, description } : { errorMap: (iss, ctx) => iss.code !== "invalid_type" ? { message: ctx.defaultError } : typeof ctx.data > "u" ? { message: required_error ?? ctx.defaultError } : { message: invalid_type_error ?? ctx.defaultError }, description }; +} +var ZodType = class { + constructor(def) { + this.spa = this.safeParseAsync, this._def = def, this.parse = this.parse.bind(this), this.safeParse = this.safeParse.bind(this), this.parseAsync = this.parseAsync.bind(this), this.safeParseAsync = this.safeParseAsync.bind(this), this.spa = this.spa.bind(this), this.refine = this.refine.bind(this), this.refinement = this.refinement.bind(this), this.superRefine = this.superRefine.bind(this), this.optional = this.optional.bind(this), this.nullable = this.nullable.bind(this), this.nullish = this.nullish.bind(this), this.array = this.array.bind(this), this.promise = this.promise.bind(this), this.or = this.or.bind(this), this.and = this.and.bind(this), this.transform = this.transform.bind(this), this.brand = this.brand.bind(this), this.default = this.default.bind(this), this.catch = this.catch.bind(this), this.describe = this.describe.bind(this), this.pipe = this.pipe.bind(this), this.isNullable = this.isNullable.bind(this), this.isOptional = this.isOptional.bind(this); + } + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + let result = this._parse(input); + if (isAsync(result)) + throw new Error("Synchronous parse encountered promise."); + return result; + } + _parseAsync(input) { + let result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + let result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + let ctx = { + common: { + issues: [], + async: (_a = params?.async) !== null && _a !== void 0 ? _a : !1, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }, result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + async parseAsync(data, params) { + let result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + let ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: !0 + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }, maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }), result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + let getIssueProperties = (val) => typeof message == "string" || typeof message > "u" ? { message } : typeof message == "function" ? message(val) : message; + return this._refinement((val, ctx) => { + let result = check(val), setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + return typeof Promise < "u" && result instanceof Promise ? result.then((data) => data ? !0 : (setError(), !1)) : result ? !0 : (setError(), !1); + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => check(val) ? !0 : (ctx.addIssue(typeof refinementData == "function" ? refinementData(val, ctx) : refinementData), !1)); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + let defaultValueFunc = typeof def == "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + let catchValueFunc = typeof def == "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + let This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}, cuidRegex = /^c[^\s-]{8,}$/i, cuid2Regex = /^[a-z][a-z0-9]*$/, uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i, emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|([^-]([a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}))$/, datetimeRegex = (args) => args.precision ? args.offset ? new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`) : new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`) : args.precision === 0 ? args.offset ? new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$") : new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$") : args.offset ? new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$") : new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"), ZodString = class extends ZodType { + constructor() { + super(...arguments), this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }), this.nonempty = (message) => this.min(1, errorUtil.errToObj(message)), this.trim = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + _parse(input) { + if (this._def.coerce && (input.data = String(input.data)), this._getType(input) !== ZodParsedType.string) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext( + ctx2, + { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + } + // + ), INVALID; + } + let status = new ParseStatus(), ctx; + for (let check of this._def.checks) + if (check.kind === "min") + input.data.length < check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: !0, + exact: !1, + message: check.message + }), status.dirty()); + else if (check.kind === "max") + input.data.length > check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: !0, + exact: !1, + message: check.message + }), status.dirty()); + else if (check.kind === "length") { + let tooBig = input.data.length > check.value, tooSmall = input.data.length < check.value; + (tooBig || tooSmall) && (ctx = this._getOrReturnCtx(input, ctx), tooBig ? addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: !0, + exact: !0, + message: check.message + }) : tooSmall && addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: !0, + exact: !0, + message: check.message + }), status.dirty()); + } else if (check.kind === "email") + emailRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "uuid") + uuidRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "cuid") + cuidRegex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "cuid2") + cuid2Regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty()); + else if (check.kind === "url") + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty(); + } + else + check.kind === "regex" ? (check.regex.lastIndex = 0, check.regex.test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message + }), status.dirty())) : check.kind === "trim" ? input.data = input.data.trim() : check.kind === "startsWith" ? input.data.startsWith(check.value) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }), status.dirty()) : check.kind === "endsWith" ? input.data.endsWith(check.value) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }), status.dirty()) : check.kind === "datetime" ? datetimeRegex(check).test(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }), status.dirty()) : util.assertNever(check); + return { status: status.value, value: input.data }; + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + datetime(options) { + var _a; + return typeof options == "string" ? this._addCheck({ + kind: "datetime", + precision: null, + offset: !1, + message: options + }) : this._addCheck({ + kind: "datetime", + precision: typeof options?.precision > "u" ? null : options?.precision, + offset: (_a = options?.offset) !== null && _a !== void 0 ? _a : !1, + ...errorUtil.errToObj(options?.message) + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get minLength() { + let min = null; + for (let ch of this._def.checks) + ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value); + return min; + } + get maxLength() { + let max = null; + for (let ch of this._def.checks) + ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value); + return max; + } +}; +ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params?.coerce) !== null && _a !== void 0 ? _a : !1, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step) { + let valDecCount = (val.toString().split(".")[1] || "").length, stepDecCount = (step.toString().split(".")[1] || "").length, decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount, valInt = parseInt(val.toFixed(decCount).replace(".", "")), stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / Math.pow(10, decCount); +} +var ZodNumber = class extends ZodType { + constructor() { + super(...arguments), this.min = this.gte, this.max = this.lte, this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce && (input.data = Number(input.data)), this._getType(input) !== ZodParsedType.number) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }), INVALID; + } + let ctx, status = new ParseStatus(); + for (let check of this._def.checks) + check.kind === "int" ? util.isInteger(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }), status.dirty()) : check.kind === "min" ? (check.inclusive ? input.data < check.value : input.data <= check.value) && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: !1, + message: check.message + }), status.dirty()) : check.kind === "max" ? (check.inclusive ? input.data > check.value : input.data >= check.value) && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: !1, + message: check.message + }), status.dirty()) : check.kind === "multipleOf" ? floatSafeRemainder(input.data, check.value) !== 0 && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }), status.dirty()) : check.kind === "finite" ? Number.isFinite(input.data) || (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message + }), status.dirty()) : util.assertNever(check); + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, !0, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, !1, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, !0, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, !1, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: !1, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: !1, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: !0, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: !0, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (let ch of this._def.checks) + ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value); + return min; + } + get maxValue() { + let max = null; + for (let ch of this._def.checks) + ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value); + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null, min = null; + for (let ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") + return !0; + ch.kind === "min" ? (min === null || ch.value > min) && (min = ch.value) : ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value); + } + return Number.isFinite(min) && Number.isFinite(max); + } +}; +ZodNumber.create = (params) => new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || !1, + ...processCreateParams(params) +}); +var ZodBigInt = class extends ZodType { + _parse(input) { + if (this._def.coerce && (input.data = BigInt(input.data)), this._getType(input) !== ZodParsedType.bigint) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params?.coerce) !== null && _a !== void 0 ? _a : !1, + ...processCreateParams(params) + }); +}; +var ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce && (input.data = Boolean(input.data)), this._getType(input) !== ZodParsedType.boolean) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodBoolean.create = (params) => new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || !1, + ...processCreateParams(params) +}); +var ZodDate = class extends ZodType { + _parse(input) { + if (this._def.coerce && (input.data = new Date(input.data)), this._getType(input) !== ZodParsedType.date) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }), INVALID; + } + if (isNaN(input.data.getTime())) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }), INVALID; + } + let status = new ParseStatus(), ctx; + for (let check of this._def.checks) + check.kind === "min" ? input.data.getTime() < check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: !0, + exact: !1, + minimum: check.value, + type: "date" + }), status.dirty()) : check.kind === "max" ? input.data.getTime() > check.value && (ctx = this._getOrReturnCtx(input, ctx), addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: !0, + exact: !1, + maximum: check.value, + type: "date" + }), status.dirty()) : util.assertNever(check); + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (let ch of this._def.checks) + ch.kind === "min" && (min === null || ch.value > min) && (min = ch.value); + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (let ch of this._def.checks) + ch.kind === "max" && (max === null || ch.value < max) && (max = ch.value); + return max != null ? new Date(max) : null; + } +}; +ZodDate.create = (params) => new ZodDate({ + checks: [], + coerce: params?.coerce || !1, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) +}); +var ZodSymbol = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.symbol) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodSymbol.create = (params) => new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) +}); +var ZodUndefined = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.undefined) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodUndefined.create = (params) => new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) +}); +var ZodNull = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.null) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodNull.create = (params) => new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) +}); +var ZodAny = class extends ZodType { + constructor() { + super(...arguments), this._any = !0; + } + _parse(input) { + return OK(input.data); + } +}; +ZodAny.create = (params) => new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) +}); +var ZodUnknown = class extends ZodType { + constructor() { + super(...arguments), this._unknown = !0; + } + _parse(input) { + return OK(input.data); + } +}; +ZodUnknown.create = (params) => new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) +}); +var ZodNever = class extends ZodType { + _parse(input) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }), INVALID; + } +}; +ZodNever.create = (params) => new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) +}); +var ZodVoid = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.undefined) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }), INVALID; + } + return OK(input.data); + } +}; +ZodVoid.create = (params) => new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) +}); +var ZodArray = class extends ZodType { + _parse(input) { + let { ctx, status } = this._processInputParams(input), def = this._def; + if (ctx.parsedType !== ZodParsedType.array) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }), INVALID; + if (def.exactLength !== null) { + let tooBig = ctx.data.length > def.exactLength.value, tooSmall = ctx.data.length < def.exactLength.value; + (tooBig || tooSmall) && (addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: !0, + exact: !0, + message: def.exactLength.message + }), status.dirty()); + } + if (def.minLength !== null && ctx.data.length < def.minLength.value && (addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: !0, + exact: !1, + message: def.minLength.message + }), status.dirty()), def.maxLength !== null && ctx.data.length > def.maxLength.value && (addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: !0, + exact: !1, + message: def.maxLength.message + }), status.dirty()), ctx.common.async) + return Promise.all([...ctx.data].map((item, i) => def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)))).then((result2) => ParseStatus.mergeArray(status, result2)); + let result = [...ctx.data].map((item, i) => def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i))); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodArray.create = (schema, params) => new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) +}); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => ({ + ...first, + ...second + // second overwrites first + }); +})(objectUtil || (objectUtil = {})); +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + let newShape = {}; + for (let key in schema.shape) { + let fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else + return schema instanceof ZodArray ? ZodArray.create(deepPartialify(schema.element)) : schema instanceof ZodOptional ? ZodOptional.create(deepPartialify(schema.unwrap())) : schema instanceof ZodNullable ? ZodNullable.create(deepPartialify(schema.unwrap())) : schema instanceof ZodTuple ? ZodTuple.create(schema.items.map((item) => deepPartialify(item))) : schema; +} +var ZodObject = class extends ZodType { + constructor() { + super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + let shape = this._def.shape(), keys = util.objectKeys(shape); + return this._cached = { shape, keys }; + } + _parse(input) { + if (this._getType(input) !== ZodParsedType.object) { + let ctx2 = this._getOrReturnCtx(input); + return addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }), INVALID; + } + let { status, ctx } = this._processInputParams(input), { shape, keys: shapeKeys } = this._getCached(), extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) + for (let key in ctx.data) + shapeKeys.includes(key) || extraKeys.push(key); + let pairs = []; + for (let key of shapeKeys) { + let keyValidator = shape[key], value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + let unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") + for (let key of extraKeys) + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + else if (unknownKeys === "strict") + extraKeys.length > 0 && (addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }), status.dirty()); + else if (unknownKeys !== "strip") + throw new Error("Internal ZodObject error: invalid unknownKeys value."); + } else { + let catchall = this._def.catchall; + for (let key of extraKeys) { + let value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + return ctx.common.async ? Promise.resolve().then(async () => { + let syncPairs = []; + for (let pair of pairs) { + let key = await pair.key; + syncPairs.push({ + key, + value: await pair.value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => ParseStatus.mergeObjectSync(status, syncPairs)) : ParseStatus.mergeObjectSync(status, pairs); + } + get shape() { + return this._def.shape(); + } + strict(message) { + return errorUtil.errToObj, new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + let defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + return issue.code === "unrecognized_keys" ? { + message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError + } : { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + return new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + let shape = {}; + return util.objectKeys(mask).forEach((key) => { + mask[key] && this.shape[key] && (shape[key] = this.shape[key]); + }), new ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + let shape = {}; + return util.objectKeys(this.shape).forEach((key) => { + mask[key] || (shape[key] = this.shape[key]); + }), new ZodObject({ + ...this._def, + shape: () => shape + }); + } + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + let newShape = {}; + return util.objectKeys(this.shape).forEach((key) => { + let fieldSchema = this.shape[key]; + mask && !mask[key] ? newShape[key] = fieldSchema : newShape[key] = fieldSchema.optional(); + }), new ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + let newShape = {}; + return util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) + newShape[key] = this.shape[key]; + else { + let newField = this.shape[key]; + for (; newField instanceof ZodOptional; ) + newField = newField._def.innerType; + newShape[key] = newField; + } + }), new ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +}; +ZodObject.create = (shape, params) => new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) +}); +ZodObject.strictCreate = (shape, params) => new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) +}); +ZodObject.lazycreate = (shape, params) => new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) +}); +var ZodUnion = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input), options = this._def.options; + function handleResults(results) { + for (let result of results) + if (result.result.status === "valid") + return result.result; + for (let result of results) + if (result.result.status === "dirty") + return ctx.common.issues.push(...result.ctx.common.issues), result.result; + let unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }), INVALID; + } + if (ctx.common.async) + return Promise.all(options.map(async (option) => { + let childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + { + let dirty, issues = []; + for (let option of options) { + let childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }, result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") + return result; + result.status === "dirty" && !dirty && (dirty = { result, ctx: childCtx }), childCtx.common.issues.length && issues.push(childCtx.common.issues); + } + if (dirty) + return ctx.common.issues.push(...dirty.ctx.common.issues), dirty.result; + let unionErrors = issues.map((issues2) => new ZodError(issues2)); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }), INVALID; + } + } + get options() { + return this._def.options; + } +}; +ZodUnion.create = (types, params) => new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) +}); +var getDiscriminator = (type) => type instanceof ZodLazy ? getDiscriminator(type.schema) : type instanceof ZodEffects ? getDiscriminator(type.innerType()) : type instanceof ZodLiteral ? [type.value] : type instanceof ZodEnum ? type.options : type instanceof ZodNativeEnum ? Object.keys(type.enum) : type instanceof ZodDefault ? getDiscriminator(type._def.innerType) : type instanceof ZodUndefined ? [void 0] : type instanceof ZodNull ? [null] : null, ZodDiscriminatedUnion = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }), INVALID; + let discriminator = this.discriminator, discriminatorValue = ctx.data[discriminator], option = this.optionsMap.get(discriminatorValue); + return option ? ctx.common.async ? option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) : option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) : (addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }), INVALID); + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + let optionsMap = /* @__PURE__ */ new Map(); + for (let type of options) { + let discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues) + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + for (let value of discriminatorValues) { + if (optionsMap.has(value)) + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a, b) { + let aType = getParsedType(a), bType = getParsedType(b); + if (a === b) + return { valid: !0, data: a }; + if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + let bKeys = util.objectKeys(b), sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1), newObj = { ...a, ...b }; + for (let key of sharedKeys) { + let sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) + return { valid: !1 }; + newObj[key] = sharedValue.data; + } + return { valid: !0, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) + return { valid: !1 }; + let newArray = []; + for (let index = 0; index < a.length; index++) { + let itemA = a[index], itemB = b[index], sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) + return { valid: !1 }; + newArray.push(sharedValue.data); + } + return { valid: !0, data: newArray }; + } else + return aType === ZodParsedType.date && bType === ZodParsedType.date && +a == +b ? { valid: !0, data: a } : { valid: !1 }; +} +var ZodIntersection = class extends ZodType { + _parse(input) { + let { status, ctx } = this._processInputParams(input), handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) + return INVALID; + let merged = mergeValues(parsedLeft.value, parsedRight.value); + return merged.valid ? ((isDirty(parsedLeft) || isDirty(parsedRight)) && status.dirty(), { status: status.value, value: merged.data }) : (addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }), INVALID); + }; + return ctx.common.async ? Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)) : handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } +}; +ZodIntersection.create = (left, right, params) => new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) +}); +var ZodTuple = class extends ZodType { + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }), INVALID; + if (ctx.data.length < this._def.items.length) + return addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: !0, + exact: !1, + type: "array" + }), INVALID; + !this._def.rest && ctx.data.length > this._def.items.length && (addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: !0, + exact: !1, + type: "array" + }), status.dirty()); + let items = [...ctx.data].map((item, itemIndex) => { + let schema = this._def.items[itemIndex] || this._def.rest; + return schema ? schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)) : null; + }).filter((x) => !!x); + return ctx.common.async ? Promise.all(items).then((results) => ParseStatus.mergeArray(status, results)) : ParseStatus.mergeArray(status, items); + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest + }); + } +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }), INVALID; + let pairs = [], keyType = this._def.keyType, valueType = this._def.valueType; + for (let key in ctx.data) + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)) + }); + return ctx.common.async ? ParseStatus.mergeObjectAsync(status, pairs) : ParseStatus.mergeObjectSync(status, pairs); + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + return second instanceof ZodType ? new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }) : new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } +}, ZodMap = class extends ZodType { + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }), INVALID; + let keyType = this._def.keyType, valueType = this._def.valueType, pairs = [...ctx.data.entries()].map(([key, value], index) => ({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + })); + if (ctx.common.async) { + let finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (let pair of pairs) { + let key = await pair.key, value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") + return INVALID; + (key.status === "dirty" || value.status === "dirty") && status.dirty(), finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + let finalMap = /* @__PURE__ */ new Map(); + for (let pair of pairs) { + let key = pair.key, value = pair.value; + if (key.status === "aborted" || value.status === "aborted") + return INVALID; + (key.status === "dirty" || value.status === "dirty") && status.dirty(), finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) +}); +var ZodSet = class extends ZodType { + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }), INVALID; + let def = this._def; + def.minSize !== null && ctx.data.size < def.minSize.value && (addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: !0, + exact: !1, + message: def.minSize.message + }), status.dirty()), def.maxSize !== null && ctx.data.size > def.maxSize.value && (addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: !0, + exact: !1, + message: def.maxSize.message + }), status.dirty()); + let valueType = this._def.valueType; + function finalizeSet(elements2) { + let parsedSet = /* @__PURE__ */ new Set(); + for (let element of elements2) { + if (element.status === "aborted") + return INVALID; + element.status === "dirty" && status.dirty(), parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + let elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + return ctx.common.async ? Promise.all(elements).then((elements2) => finalizeSet(elements2)) : finalizeSet(elements); + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodSet.create = (valueType, params) => new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) +}); +var ZodFunction = class extends ZodType { + constructor() { + super(...arguments), this.validate = this.implement; + } + _parse(input) { + let { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }), INVALID; + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + let params = { errorMap: ctx.common.contextualErrorMap }, fn = ctx.data; + return this._def.returns instanceof ZodPromise ? OK(async (...args) => { + let error = new ZodError([]), parsedArgs = await this._def.args.parseAsync(args, params).catch((e) => { + throw error.addIssue(makeArgsIssue(args, e)), error; + }), result = await fn(...parsedArgs); + return await this._def.returns._def.type.parseAsync(result, params).catch((e) => { + throw error.addIssue(makeReturnsIssue(result, e)), error; + }); + }) : OK((...args) => { + let parsedArgs = this._def.args.safeParse(args, params); + if (!parsedArgs.success) + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + let result = fn(...parsedArgs.data), parsedReturns = this._def.returns.safeParse(result, params); + if (!parsedReturns.success) + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + return parsedReturns.data; + }); + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + return this.parse(func); + } + strictImplement(func) { + return this.parse(func); + } + static create(args, returns, params) { + return new ZodFunction({ + args: args || ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } +}, ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + let { ctx } = this._processInputParams(input); + return this._def.getter()._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +}; +ZodLazy.create = (getter, params) => new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) +}); +var ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }), INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +}; +ZodLiteral.create = (value, params) => new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) +}); +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class extends ZodType { + _parse(input) { + if (typeof input.data != "string") { + let ctx = this._getOrReturnCtx(input), expectedValues = this._def.values; + return addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }), INVALID; + } + if (this._def.values.indexOf(input.data) === -1) { + let ctx = this._getOrReturnCtx(input), expectedValues = this._def.values; + return addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }), INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + let enumValues = {}; + for (let val of this._def.values) + enumValues[val] = val; + return enumValues; + } + get Values() { + let enumValues = {}; + for (let val of this._def.values) + enumValues[val] = val; + return enumValues; + } + get Enum() { + let enumValues = {}; + for (let val of this._def.values) + enumValues[val] = val; + return enumValues; + } + extract(values) { + return ZodEnum.create(values); + } + exclude(values) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); + } +}; +ZodEnum.create = createZodEnum; +var ZodNativeEnum = class extends ZodType { + _parse(input) { + let nativeEnumValues = util.getValidEnumValues(this._def.values), ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + let expectedValues = util.objectValues(nativeEnumValues); + return addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }), INVALID; + } + if (nativeEnumValues.indexOf(input.data) === -1) { + let expectedValues = util.objectValues(nativeEnumValues); + return addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }), INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +}; +ZodNativeEnum.create = (values, params) => new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) +}); +var ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + let { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === !1) + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }), INVALID; + let promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }))); + } +}; +ZodPromise.create = (schema, params) => new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) +}); +var ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + let { status, ctx } = this._processInputParams(input), effect = this._def.effect || null; + if (effect.type === "preprocess") { + let processed = effect.transform(ctx.data); + return ctx.common.async ? Promise.resolve(processed).then((processed2) => this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + })) : this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + } + let checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg), arg.fatal ? status.abort() : status.dirty(); + }, + get path() { + return ctx.path; + } + }; + if (checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx), effect.type === "refinement") { + let executeRefinement = (acc) => { + let result = effect.refinement(acc, checkCtx); + if (ctx.common.async) + return Promise.resolve(result); + if (result instanceof Promise) + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + return acc; + }; + if (ctx.common.async === !1) { + let inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + return inner.status === "aborted" ? INVALID : (inner.status === "dirty" && status.dirty(), executeRefinement(inner.value), { status: status.value, value: inner.value }); + } else + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => inner.status === "aborted" ? INVALID : (inner.status === "dirty" && status.dirty(), executeRefinement(inner.value).then(() => ({ status: status.value, value: inner.value })))); + } + if (effect.type === "transform") + if (ctx.common.async === !1) { + let base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return base; + let result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) + throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead."); + return { status: status.value, value: result }; + } else + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => isValid(base) ? Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })) : base); + util.assertNever(effect); + } +}; +ZodEffects.create = (schema, effect, params) => new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) +}); +ZodEffects.createWithPreprocess = (preprocess, schema, params) => new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) +}); +var ZodOptional = class extends ZodType { + _parse(input) { + return this._getType(input) === ZodParsedType.undefined ? OK(void 0) : this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type, params) => new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) +}); +var ZodNullable = class extends ZodType { + _parse(input) { + return this._getType(input) === ZodParsedType.null ? OK(null) : this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodNullable.create = (type, params) => new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) +}); +var ZodDefault = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input), data = ctx.data; + return ctx.parsedType === ZodParsedType.undefined && (data = this._def.defaultValue()), this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } +}; +ZodDefault.create = (type, params) => new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default == "function" ? params.default : () => params.default, + ...processCreateParams(params) +}); +var ZodCatch = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input), result = this._def.innerType._parse({ + data: ctx.data, + path: ctx.path, + parent: { + ...ctx, + common: { + ...ctx.common, + issues: [] + // don't collect issues from inner type + } + } + }); + return isAsync(result) ? result.then((result2) => ({ + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue() + })) : { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue() + }; + } + removeCatch() { + return this._def.innerType; + } +}; +ZodCatch.create = (type, params) => new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch == "function" ? params.catch : () => params.catch, + ...processCreateParams(params) +}); +var ZodNaN = class extends ZodType { + _parse(input) { + if (this._getType(input) !== ZodParsedType.nan) { + let ctx = this._getOrReturnCtx(input); + return addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }), INVALID; + } + return { status: "valid", value: input.data }; + } +}; +ZodNaN.create = (params) => new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) +}); +var BRAND = Symbol("zod_brand"), ZodBranded = class extends ZodType { + _parse(input) { + let { ctx } = this._processInputParams(input), data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } +}, ZodPipeline = class extends ZodType { + _parse(input) { + let { status, ctx } = this._processInputParams(input); + if (ctx.common.async) + return (async () => { + let inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + return inResult.status === "aborted" ? INVALID : inResult.status === "dirty" ? (status.dirty(), DIRTY(inResult.value)) : this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + })(); + { + let inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + return inResult.status === "aborted" ? INVALID : inResult.status === "dirty" ? (status.dirty(), { + status: "dirty", + value: inResult.value + }) : this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } +}, custom = (check, params = {}, fatal) => check ? ZodAny.create().superRefine((data, ctx) => { + if (!check(data)) { + let p = typeof params == "function" ? params(data) : params, p2 = typeof p == "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal }); + } +}) : ZodAny.create(), late = { + object: ZodObject.lazycreate +}, ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind2) { + ZodFirstPartyTypeKind2.ZodString = "ZodString", ZodFirstPartyTypeKind2.ZodNumber = "ZodNumber", ZodFirstPartyTypeKind2.ZodNaN = "ZodNaN", ZodFirstPartyTypeKind2.ZodBigInt = "ZodBigInt", ZodFirstPartyTypeKind2.ZodBoolean = "ZodBoolean", ZodFirstPartyTypeKind2.ZodDate = "ZodDate", ZodFirstPartyTypeKind2.ZodSymbol = "ZodSymbol", ZodFirstPartyTypeKind2.ZodUndefined = "ZodUndefined", ZodFirstPartyTypeKind2.ZodNull = "ZodNull", ZodFirstPartyTypeKind2.ZodAny = "ZodAny", ZodFirstPartyTypeKind2.ZodUnknown = "ZodUnknown", ZodFirstPartyTypeKind2.ZodNever = "ZodNever", ZodFirstPartyTypeKind2.ZodVoid = "ZodVoid", ZodFirstPartyTypeKind2.ZodArray = "ZodArray", ZodFirstPartyTypeKind2.ZodObject = "ZodObject", ZodFirstPartyTypeKind2.ZodUnion = "ZodUnion", ZodFirstPartyTypeKind2.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", ZodFirstPartyTypeKind2.ZodIntersection = "ZodIntersection", ZodFirstPartyTypeKind2.ZodTuple = "ZodTuple", ZodFirstPartyTypeKind2.ZodRecord = "ZodRecord", ZodFirstPartyTypeKind2.ZodMap = "ZodMap", ZodFirstPartyTypeKind2.ZodSet = "ZodSet", ZodFirstPartyTypeKind2.ZodFunction = "ZodFunction", ZodFirstPartyTypeKind2.ZodLazy = "ZodLazy", ZodFirstPartyTypeKind2.ZodLiteral = "ZodLiteral", ZodFirstPartyTypeKind2.ZodEnum = "ZodEnum", ZodFirstPartyTypeKind2.ZodEffects = "ZodEffects", ZodFirstPartyTypeKind2.ZodNativeEnum = "ZodNativeEnum", ZodFirstPartyTypeKind2.ZodOptional = "ZodOptional", ZodFirstPartyTypeKind2.ZodNullable = "ZodNullable", ZodFirstPartyTypeKind2.ZodDefault = "ZodDefault", ZodFirstPartyTypeKind2.ZodCatch = "ZodCatch", ZodFirstPartyTypeKind2.ZodPromise = "ZodPromise", ZodFirstPartyTypeKind2.ZodBranded = "ZodBranded", ZodFirstPartyTypeKind2.ZodPipeline = "ZodPipeline"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom((data) => data instanceof cls, params, !0), stringType = ZodString.create, numberType = ZodNumber.create, nanType = ZodNaN.create, bigIntType = ZodBigInt.create, booleanType = ZodBoolean.create, dateType = ZodDate.create, symbolType = ZodSymbol.create, undefinedType = ZodUndefined.create, nullType = ZodNull.create, anyType = ZodAny.create, unknownType = ZodUnknown.create, neverType = ZodNever.create, voidType = ZodVoid.create, arrayType = ZodArray.create, objectType = ZodObject.create, strictObjectType = ZodObject.strictCreate, unionType = ZodUnion.create, discriminatedUnionType = ZodDiscriminatedUnion.create, intersectionType = ZodIntersection.create, tupleType = ZodTuple.create, recordType = ZodRecord.create, mapType = ZodMap.create, setType = ZodSet.create, functionType = ZodFunction.create, lazyType = ZodLazy.create, literalType = ZodLiteral.create, enumType = ZodEnum.create, nativeEnumType = ZodNativeEnum.create, promiseType = ZodPromise.create, effectsType = ZodEffects.create, optionalType = ZodOptional.create, nullableType = ZodNullable.create, preprocessType = ZodEffects.createWithPreprocess, pipelineType = ZodPipeline.create, ostring = () => stringType().optional(), onumber = () => numberType().optional(), oboolean = () => booleanType().optional(), coerce = { + string: (arg) => ZodString.create({ ...arg, coerce: !0 }), + number: (arg) => ZodNumber.create({ ...arg, coerce: !0 }), + boolean: (arg) => ZodBoolean.create({ + ...arg, + coerce: !0 + }), + bigint: (arg) => ZodBigInt.create({ ...arg, coerce: !0 }), + date: (arg) => ZodDate.create({ ...arg, coerce: !0 }) +}, NEVER = INVALID, mod = /* @__PURE__ */ Object.freeze({ + __proto__: null, + defaultErrorMap: errorMap, + setErrorMap, + getErrorMap, + makeIssue, + EMPTY_PATH, + addIssueToContext, + ParseStatus, + INVALID, + DIRTY, + OK, + isAborted, + isDirty, + isValid, + isAsync, + get util() { + return util; + }, + ZodParsedType, + getParsedType, + ZodType, + ZodString, + ZodNumber, + ZodBigInt, + ZodBoolean, + ZodDate, + ZodSymbol, + ZodUndefined, + ZodNull, + ZodAny, + ZodUnknown, + ZodNever, + ZodVoid, + ZodArray, + get objectUtil() { + return objectUtil; + }, + ZodObject, + ZodUnion, + ZodDiscriminatedUnion, + ZodIntersection, + ZodTuple, + ZodRecord, + ZodMap, + ZodSet, + ZodFunction, + ZodLazy, + ZodLiteral, + ZodEnum, + ZodNativeEnum, + ZodPromise, + ZodEffects, + ZodTransformer: ZodEffects, + ZodOptional, + ZodNullable, + ZodDefault, + ZodCatch, + ZodNaN, + BRAND, + ZodBranded, + ZodPipeline, + custom, + Schema: ZodType, + ZodSchema: ZodType, + late, + get ZodFirstPartyTypeKind() { + return ZodFirstPartyTypeKind; + }, + coerce, + any: anyType, + array: arrayType, + bigint: bigIntType, + boolean: booleanType, + date: dateType, + discriminatedUnion: discriminatedUnionType, + effect: effectsType, + enum: enumType, + function: functionType, + instanceof: instanceOfType, + intersection: intersectionType, + lazy: lazyType, + literal: literalType, + map: mapType, + nan: nanType, + nativeEnum: nativeEnumType, + never: neverType, + null: nullType, + nullable: nullableType, + number: numberType, + object: objectType, + oboolean, + onumber, + optional: optionalType, + ostring, + pipeline: pipelineType, + preprocess: preprocessType, + promise: promiseType, + record: recordType, + set: setType, + strictObject: strictObjectType, + string: stringType, + symbol: symbolType, + transformer: effectsType, + tuple: tupleType, + undefined: undefinedType, + union: unionType, + unknown: unknownType, + void: voidType, + NEVER, + ZodIssueCode, + quotelessJson, + ZodError +}); + +// packages/miniflare/src/workers/shared/zod.worker.ts +var HEX_REGEXP = /^[0-9a-f]*$/i, BASE64_REGEXP = /^[0-9a-z+/=]*$/i, HexDataSchema = mod.string().regex(HEX_REGEXP).transform((hex) => Buffer.from(hex, "hex")), Base64DataSchema = mod.string().regex(BASE64_REGEXP).transform((base64) => Buffer.from(base64, "base64")); +export { + BASE64_REGEXP, + Base64DataSchema, + HEX_REGEXP, + HexDataSchema, + mod as z +}; +//# sourceMappingURL=zod.worker.js.map diff --git a/node_modules/miniflare/dist/src/workers/shared/zod.worker.js.map b/node_modules/miniflare/dist/src/workers/shared/zod.worker.js.map new file mode 100644 index 0000000..1ee4ceb --- /dev/null +++ b/node_modules/miniflare/dist/src/workers/shared/zod.worker.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../../../../src/workers/shared/zod.worker.ts", "../../../../../../node_modules/zod/lib/index.mjs"], + "mappings": ";AAAA,SAAS,cAAc;;;ACAvB,IAAI;AAAA,CACH,SAAUA,OAAM;AACb,EAAAA,MAAK,cAAc,CAAC,QAAQ;AAC5B,WAAS,SAAS,MAAM;AAAA,EAAE;AAC1B,EAAAA,MAAK,WAAW;AAChB,WAAS,YAAY,IAAI;AACrB,UAAM,IAAI,MAAM;AAAA,EACpB;AACA,EAAAA,MAAK,cAAc,aACnBA,MAAK,cAAc,CAAC,UAAU;AAC1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AA,EACR,UAAY;AAAA,EACZ,YAAc;AAAA,EACd,cAAc;AAAA,EACd,MAAM;AAAA,EACN,SAAS;AAAA,EACT,KAAK;AAAA,EACL,KAAK;AAAA,EACL,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,MAAQ;AAAA,EACR,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,KAAK;AAAA,EACL,cAAc;AAAA,EACd,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,OAAO;AAAA,EACP,WAAa;AAAA,EACb,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;;;ADrjHM,IAAM,aAAa,gBAEb,gBAAgB,mBAChB,gBAAgB,IAC1B,OAAO,EACP,MAAM,UAAU,EAChB,UAAU,CAAC,QAAQ,OAAO,KAAK,KAAK,KAAK,CAAC,GAChC,mBAAmB,IAC7B,OAAO,EACP,MAAM,aAAa,EACnB,UAAU,CAAC,WAAW,OAAO,KAAK,QAAQ,QAAQ,CAAC;", + "names": ["util", "errorUtil", "errorMap", "ctx", "result", "objectUtil", "issues", "elements", "processed", "ZodFirstPartyTypeKind"] +} diff --git a/node_modules/miniflare/package.json b/node_modules/miniflare/package.json new file mode 100644 index 0000000..2f8e73e --- /dev/null +++ b/node_modules/miniflare/package.json @@ -0,0 +1,67 @@ +{ + "name": "miniflare", + "version": "3.20230922.0", + "description": "Fun, full-featured, fully-local simulator for Cloudflare Workers", + "keywords": [ + "cloudflare", + "workers", + "worker", + "local", + "cloudworker" + ], + "homepage": "https://github.com/cloudflare/miniflare/tree/master/packages/tre#readme", + "bugs": { + "url": "https://github.com/cloudflare/miniflare/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/cloudflare/miniflare.git", + "directory": "packages/tre" + }, + "license": "MIT", + "author": "MrBBot ", + "main": "./dist/src/index.js", + "types": "./dist/src/index.d.ts", + "files": [ + "dist/src", + "bootstrap.js" + ], + "dependencies": { + "acorn": "^8.8.0", + "acorn-walk": "^8.2.0", + "capnp-ts": "^0.7.0", + "exit-hook": "^2.2.1", + "glob-to-regexp": "^0.4.1", + "source-map-support": "0.5.21", + "stoppable": "^1.1.0", + "undici": "^5.22.1", + "workerd": "1.20230922.0", + "ws": "^8.11.0", + "youch": "^3.2.2", + "zod": "^3.20.6" + }, + "devDependencies": { + "@cloudflare/kv-asset-handler": "^0.3.0", + "@cloudflare/workers-types": "^4.20230807.0", + "@types/debug": "^4.1.7", + "@types/estree": "^1.0.0", + "@types/glob-to-regexp": "^0.4.1", + "@types/http-cache-semantics": "^4.0.1", + "@types/source-map-support": "^0.5.6", + "@types/stoppable": "^1.1.1", + "@types/ws": "^8.5.3", + "devalue": "^4.3.0", + "devtools-protocol": "^0.0.1182435", + "http-cache-semantics": "^4.1.0", + "kleur": "^4.1.5" + }, + "engines": { + "node": ">=16.13" + }, + "volta": { + "extends": "../../package.json" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..c4498bc --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..eea666e --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.1.2", + "description": "Tiny millisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.12.1", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..9a1996b --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,60 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/mustache/CHANGELOG.md b/node_modules/mustache/CHANGELOG.md new file mode 100644 index 0000000..b1f72d0 --- /dev/null +++ b/node_modules/mustache/CHANGELOG.md @@ -0,0 +1,618 @@ +# Change Log + +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +## [4.2.0] / 28 March 2021 + +### Added + +* [#773]: Add package.json `exports` field, by [@manzt]. + +## [4.1.0] / 6 December 2020 + +### Added + +* [#764]: `render()` now recognizes a config object argument, by [@pineapplemachine]. + +### Fixed + +* [#764]: Ask custom `escape` functions to escape all types of values (including `number`s), by [@pineapplemachine]. + +## [4.0.1] / 15 March 2020 + +### Fixed + + * [#739]: Fix custom delimiters in nested partials, by [@aielo]. + +## [4.0.0] / 16 January 2020 + +Majority of using projects don't have to worry by this being a new major version. + +**TLDR;** if your project manipulates `Writer.prototype.parse | Writer.cache` directly or uses `.to_html()`, you probably have to change that code. + +This release allows the internal template cache to be customised, either by disabling it completely +or provide a custom strategy deciding how the cache should behave when mustache.js parses templates. + +```js +const mustache = require('mustache'); + +// disable caching +Mustache.templateCache = undefined; + +// or use a built-in Map in modern environments +Mustache.templateCache = new Map(); +``` + +Projects that wanted to customise the caching behaviour in earlier versions of mustache.js were forced to +override internal method responsible for parsing templates; `Writer.prototype.parse`. In short, that was unfortunate +because there is more than caching happening in that method. + +We've improved that now by introducing a first class API that only affects template caching. + +The default template cache behaves as before and is still compatible with older JavaScript environments. +For those who wants to provide a custom more sopisiticated caching strategy, one can do that with an object that adheres to the following requirements: + +```ts +{ + set(cacheKey: string, value: string): void + get(cacheKey: string): string | undefined + clear(): void +} +``` + +### Added + +* [#731]: Allow template caching to be customised, by [@AndrewLeedham]. + +### Removed + +* [#735]: Remove `.to_html()`, by [@phillipj]. + +## [3.2.1] / 30 December 2019 + +### Fixed + + * [#733]: Allow the CLI to use JavaScript views when the project has ES6 modules enabled, by [@eobrain]. + +## [3.2.0] / 18 December 2019 + +### Added + +* [#728]: Expose ECMAScript Module in addition to UMD (CommonJS, AMD & global scope), by [@phillipj] and [@zekth]. + +### Using mustache.js as an ES module + +To stay backwards compatible with already using projects, the default exposed module format is still UMD. +That means projects using mustache.js as an CommonJS, AMD or global scope module, from npm or directly from github.com +can keep on doing that for now. + +For those projects who would rather want to use mustache.js as an ES module, the `mustache/mustache.mjs` file has to +be `import`ed directly. + +Below are some usage scenarios for different runtimes. + +#### Modern browser with ES module support + +```html + + +``` + +#### [Node.js](https://nodejs.org) (>= v13.2.0 or using --experimental-modules flag) + +```js +// index.mjs +import mustache from 'mustache/mustache.mjs' + +console.log(mustache.render('Hello {{name}}!', { name: 'Santa' })) +// Hello Santa! +``` + +ES Module support for Node.js will be improved in the future when [Conditional Exports](https://nodejs.org/api/esm.html#esm_conditional_exports) +is enabled by default rather than being behind an experimental flag. + +More info in [Node.js ECMAScript Modules docs](https://nodejs.org/api/esm.html). + +#### [Deno](https://deno.land/) + +```js +// index.ts +import mustache from 'https://unpkg.com/mustache@3.2.0/mustache.mjs' + +console.log(mustache.render('Hello {{name}}!', { name: 'Santa' })) +// Hello Santa! +``` + +## [3.1.0] / 13 September 2019 + +### Added + + * [#717]: Added support .js files as views in command line tool, by [@JEStaubach]. + +### Fixed + + * [#716]: Bugfix for indentation of inline partials, by [@yotammadem]. + +## [3.0.3] / 27 August 2019 + +### Added + + * [#713]: Add test cases for custom functions in partials, by [@wol-soft]. + +### Fixed + + * [#714]: Bugfix for wrong function output in partials with indentation, by [@phillipj]. + +## [3.0.2] / 21 August 2019 + +### Fixed + + * [#705]: Fix indentation of partials, by [@kevindew] and [@yotammadem]. + +### Dev + + * [#701]: Fix test failure for Node 10 and above, by [@andersk]. + * [#704]: Lint all test files just like the source files, by [@phillipj]. + * Start experimenting & comparing GitHub Actions vs Travis CI, by [@phillipj]. + +## [3.0.1] / 11 November 2018 + + * [#679]: Fix partials not rendering tokens when using custom tags, by [@stackchain]. + +## [3.0.0] / 16 September 2018 + +We are very happy to announce a new major version of mustache.js. We want to be very careful not to break projects +out in the wild, and adhering to [Semantic Versioning](http://semver.org/) we have therefore cut this new major version. + +The changes introduced will likely not require any actions for most using projects. The things to look out for that +might cause unexpected rendering results are described in the migration guide below. + +A big shout out and thanks to [@raymond-lam] for this release! Without his contributions with code and issue triaging, +this release would never have happened. + +### Major + +* [#618]: Allow rendering properties of primitive types that are not objects, by [@raymond-lam]. +* [#643]: `Writer.prototype.parse` to cache by tags in addition to template string, by [@raymond-lam]. +* [#664]: Fix `Writer.prototype.parse` cache, by [@seminaoki]. + +### Minor + +* [#673]: Add `tags` parameter to `Mustache.render()`, by [@raymond-lam]. + +### Migrating from mustache.js v2.x to v3.x + +#### Rendering properties of primitive types + +We have ensured properties of primitive types can be rendered at all times. That means `Array.length`, `String.length` +and similar. A corner case where this could cause unexpected output follows: + +View: +``` +{ + stooges: [ + { name: "Moe" }, + { name: "Larry" }, + { name: "Curly" } + ] +} +``` + +Template: +``` +{{#stooges}} + {{name}}: {{name.length}} characters +{{/stooges}} +``` + +Output with v3.0: +``` + Moe: 3 characters + Larry: 5 characters + Curly: 5 characters +``` + +Output with v2.x: +``` + Moe: characters + Larry: characters + Curly: characters +``` + +#### Caching for templates with custom delimiters + +We have improved the templates cache to ensure custom delimiters are taken into consideration for the cache. +This improvement might cause unexpected rendering behaviour for using projects actively using the custom delimiters functionality. + +Previously it was possible to use `Mustache.parse()` as a means to set global custom delimiters. If custom +delimiters were provided as an argument, it would affect all following calls to `Mustache.render()`. +Consider the following: + +```js +const template = "[[item.title]] [[item.value]]"; +mustache.parse(template, ["[[", "]]"]); + +console.log( + mustache.render(template, { + item: { + title: "TEST", + value: 1 + } + }) +); + +>> TEST 1 +``` + +The above illustrates the fact that `Mustache.parse()` made mustache.js cache the template without considering +the custom delimiters provided. This is no longer true. + +We no longer encourage using `Mustache.parse()` for this purpose, but have rather added a fourth argument to +`Mustache.render()` letting you provide custom delimiters when rendering. + +If you still need the pre-parse the template and use custom delimiters at the same time, ensure to provide +the custom delimiters as argument to `Mustache.render()` as well. + +## [2.3.2] / 17 August 2018 + +This release is made to revert changes introduced in [2.3.1] that caused unexpected behaviour for several users. + +### Minor + + * [#670]: Rollback template cache causing unexpected behaviour, by [@raymond-lam]. + +## [2.3.1] / 7 August 2018 + +### Minor + + * [#643]: `Writer.prototype.parse` to cache by tags in addition to template string, by [@raymond-lam]. + * [#664]: Fix `Writer.prototype.parse` cache, by [@seminaoki]. + +### Dev + + * [#666]: Install release tools with npm rather than pre-commit hook & `Rakefile`, by [@phillipj]. + * [#667], [#668]: Stabilize browser test suite, by [@phillipj]. + +### Docs + + * [#644]: Document global Mustache.escape overriding capacity, by [@paultopia]. + * [#657]: Correct `Mustache.parse()` return type documentation, by [@bbrooks]. + +## [2.3.0] / 8 November 2016 + +### Minor + + * [#540]: Add optional `output` argument to mustache CLI, by [@wizawu]. + * [#597]: Add compatibility with amdclean, by [@mightyplow]. + +### Dev + + * [#553]: Assert `null` lookup when rendering an unescaped value, by [@dasilvacontin]. + * [#580], [#610]: Ignore eslint for greenkeeper updates, by [@phillipj]. + * [#560]: Fix CLI tests for Windows, by [@kookookchoozeus]. + * Run browser tests w/node v4, by [@phillipj]. + +### Docs + + * [#542]: Add API documentation to README, by [@tomekwi]. + * [#546]: Add missing syntax highlighting to README code blocks, by [@pra85]. + * [#569]: Update Ctemplate links in README, by [@mortonfox]. + * [#592]: Change "loadUser" to "loadUser()" in README, by [@Flaque]. + * [#593]: Adding doctype to HTML code example in README, by [@calvinf]. + +### Dependencies + + * eslint -> 2.2.0. Breaking changes fix by [@phillipj]. [#548] + * eslint -> 2.5.1. + * mocha -> 3.0.2. + * zuul -> 3.11.0. + +## [2.2.1] / 13 December 2015 + +### Fixes + + * Improve HTML escaping, by [@phillipj]. + * Fix inconsistency in defining global mustache object, by [@simast]. + * Fix switch-case indent error, by [@norfish]. + * Unpin chai and eslint versions, by [@dasilvacontin]. + * Update README.md with proper grammar, by [@EvanLovely]. + * Update mjackson username in README, by [@mjackson]. + * Remove syntax highlighting in README code sample, by [@imagentleman]. + * Fix typo in README, by [@Xcrucifier]. + * Fix link typo in README, by [@keirog]. + +## [2.2.0] / 15 October 2015 + +### Added + + * Add Partials support to CLI, by [@palkan]. + +### Changed + + * Move install instructions to README's top, by [@mateusortiz] + * Improved devhook install output, by [@ShashankaNataraj]. + * Clarifies and improves language in documentation, by [@jfmercer]. + * Linting CLI tool, by [@phillipj]. + * npm 2.x and node v4 on Travis, by [@phillipj]. + +### Fixes + + * Fix README spelling error to "aforementioned", by [@djchie]. + * Equal error message test in .render() for server and browser, by [@phillipj]. + +### Dependencies + + * chai -> 3.3.0 + * eslint -> 1.6.0 + +## [2.1.3] / 23 July 2015 + +### Added + + * Throw error when providing .render() with invalid template type, by [@phillipj]. + * Documents use of string literals containing double quotes, by [@jfmercer]. + +### Changed + + * Move mustache gif to githubusercontent, by [@Andersos]. + +### Fixed + + * Update UMD Shim to be resilient to HTMLElement global pollution, by [@mikesherov]. + +## [2.1.2] / 17 June 2015 + +### Added + + * Mustache global definition ([#466]) by [@yousefcisco]. + +## [2.1.1] / 11 June 2015 + +### Added + + * State that we use semver on the change log, by [@dasilvacontin]. + * Added version links to change log, by [@dasilvacontin]. + +### Fixed + + * Bugfix for using values from view's context prototype, by [@phillipj]. + * Improve test with undefined/null lookup hit using dot notation, by [@dasilvacontin]. + * Bugfix for null/undefined lookup hit when using dot notation, by [@phillipj]. + * Remove moot `version` property from bower.json, by [@kkirsche]. + * bower.json doesn't require a version bump via hook, by [@dasilvacontin]. + + +## [2.1.0] / 5 June 2015 + + * Added license attribute to package.json, by [@pgilad]. + * Minor changes to make mustache.js compatible with both WSH and ASP, by [@nagaozen]. + * Improve CLI view parsing error, by [@phillipj]. + * Bugfix for view context cache, by [@phillipj]. + +## [2.0.0] / 27 Mar 2015 + + * Fixed lookup not stopping upon finding `undefined` or `null` values, by [@dasilvacontin]. + * Refactored pre-commit hook, by [@dasilvacontin]. + +## [1.2.0] / 24 Mar 2015 + + * Added -v option to CLI, by [@phillipj]. + * Bugfix for rendering Number when it serves as the Context, by [@phillipj]. + * Specified files in package.json for a cleaner install, by [@phillipj]. + +## [1.1.0] / 18 Feb 2015 + + * Refactor Writer.renderTokens() for better readability, by [@phillipj]. + * Cleanup tests section in readme, by [@phillipj]. + * Added JSHint to tests/CI, by [@phillipj]. + * Added node v0.12 on travis, by [@phillipj]. + * Created command line tool, by [@phillipj]. + * Added *falsy* to Inverted Sections description in README, by [@kristijanmatic]. + +## [1.0.0] / 20 Dec 2014 + + * Inline tag compilation, by [@mjackson]. + * Fixed AMD registration, volo package.json entry, by [@jrburke]. + * Added spm support, by [@afc163]. + * Only access properties of objects on Context.lookup, by [@cmbuckley]. + +## [0.8.2] / 17 Mar 2014 + + * Supporting Bower through a bower.json file. + +## [0.8.1] / 3 Jan 2014 + + * Fix usage of partial templates. + +## [0.8.0] / 2 Dec 2013 + + * Remove compile* writer functions, use mustache.parse instead. Smaller API. + * Throw an error when rendering a template that contains higher-order sections and + the original template is not provided. + * Remove low-level Context.make function. + * Better code readability and inline documentation. + * Stop caching templates by name. + +## [0.7.3] / 5 Nov 2013 + + * Don't require the original template to be passed to the rendering function + when using compiled templates. This is still required when using higher-order + functions in order to be able to extract the portion of the template + that was contained by that section. Fixes [#262]. + * Performance improvements. + +## [0.7.2] / 27 Dec 2012 + + * Fixed a rendering bug ([#274]) when using nested higher-order sections. + * Better error reporting on failed parse. + * Converted tests to use mocha instead of vows. + +## [0.7.1] / 6 Dec 2012 + + * Handle empty templates gracefully. Fixes [#265], [#267], and [#270]. + * Cache partials by template, not by name. Fixes [#257]. + * Added Mustache.compileTokens to compile the output of Mustache.parse. Fixes + [#258]. + +## [0.7.0] / 10 Sep 2012 + + * Rename Renderer => Writer. + * Allow partials to be loaded dynamically using a callback (thanks + [@TiddoLangerak] for the suggestion). + * Fixed a bug with higher-order sections that prevented them from being + passed the raw text of the section from the original template. + * More concise token format. Tokens also include start/end indices in the + original template. + * High-level API is consistent with the Writer API. + * Allow partials to be passed to the pre-compiled function (thanks + [@fallenice]). + * Don't use eval (thanks [@cweider]). + +## [0.6.0] / 31 Aug 2012 + + * Use JavaScript's definition of falsy when determining whether to render an + inverted section or not. Issue [#186]. + * Use Mustache.escape to escape values inside {{}}. This function may be + reassigned to alter the default escaping behavior. Issue [#244]. + * Fixed a bug that clashed with QUnit (thanks [@kannix]). + * Added volo support (thanks [@guybedford]). + +[4.1.0]: https://github.com/janl/mustache.js/compare/v4.0.1...v4.1.0 +[4.0.1]: https://github.com/janl/mustache.js/compare/v4.0.0...v4.0.1 +[4.0.0]: https://github.com/janl/mustache.js/compare/v3.2.1...v4.0.0 +[3.2.1]: https://github.com/janl/mustache.js/compare/v3.2.0...v3.2.1 +[3.2.0]: https://github.com/janl/mustache.js/compare/v3.1.0...v3.2.0 +[3.1.0]: https://github.com/janl/mustache.js/compare/v3.0.3...v3.1.0 +[3.0.3]: https://github.com/janl/mustache.js/compare/v3.0.2...v3.0.3 +[3.0.2]: https://github.com/janl/mustache.js/compare/v3.0.1...v3.0.2 +[3.0.1]: https://github.com/janl/mustache.js/compare/v3.0.0...v3.0.1 +[3.0.0]: https://github.com/janl/mustache.js/compare/v2.3.2...v3.0.0 +[2.3.2]: https://github.com/janl/mustache.js/compare/v2.3.1...v2.3.2 +[2.3.1]: https://github.com/janl/mustache.js/compare/v2.3.0...v2.3.1 +[2.3.0]: https://github.com/janl/mustache.js/compare/v2.2.1...v2.3.0 +[2.2.1]: https://github.com/janl/mustache.js/compare/v2.2.0...v2.2.1 +[2.2.0]: https://github.com/janl/mustache.js/compare/v2.1.3...v2.2.0 +[2.1.3]: https://github.com/janl/mustache.js/compare/v2.1.2...v2.1.3 +[2.1.2]: https://github.com/janl/mustache.js/compare/v2.1.1...v2.1.2 +[2.1.1]: https://github.com/janl/mustache.js/compare/v2.1.0...v2.1.1 +[2.1.0]: https://github.com/janl/mustache.js/compare/v2.0.0...v2.1.0 +[2.0.0]: https://github.com/janl/mustache.js/compare/v1.2.0...v2.0.0 +[1.2.0]: https://github.com/janl/mustache.js/compare/v1.1.0...v1.2.0 +[1.1.0]: https://github.com/janl/mustache.js/compare/v1.0.0...v1.1.0 +[1.0.0]: https://github.com/janl/mustache.js/compare/0.8.2...v1.0.0 +[0.8.2]: https://github.com/janl/mustache.js/compare/0.8.1...0.8.2 +[0.8.1]: https://github.com/janl/mustache.js/compare/0.8.0...0.8.1 +[0.8.0]: https://github.com/janl/mustache.js/compare/0.7.3...0.8.0 +[0.7.3]: https://github.com/janl/mustache.js/compare/0.7.2...0.7.3 +[0.7.2]: https://github.com/janl/mustache.js/compare/0.7.1...0.7.2 +[0.7.1]: https://github.com/janl/mustache.js/compare/0.7.0...0.7.1 +[0.7.0]: https://github.com/janl/mustache.js/compare/0.6.0...0.7.0 +[0.6.0]: https://github.com/janl/mustache.js/compare/0.5.2...0.6.0 + +[#186]: https://github.com/janl/mustache.js/issues/186 +[#244]: https://github.com/janl/mustache.js/issues/244 +[#257]: https://github.com/janl/mustache.js/issues/257 +[#258]: https://github.com/janl/mustache.js/issues/258 +[#262]: https://github.com/janl/mustache.js/issues/262 +[#265]: https://github.com/janl/mustache.js/issues/265 +[#267]: https://github.com/janl/mustache.js/issues/267 +[#270]: https://github.com/janl/mustache.js/issues/270 +[#274]: https://github.com/janl/mustache.js/issues/274 +[#466]: https://github.com/janl/mustache.js/issues/466 +[#540]: https://github.com/janl/mustache.js/issues/540 +[#542]: https://github.com/janl/mustache.js/issues/542 +[#546]: https://github.com/janl/mustache.js/issues/546 +[#548]: https://github.com/janl/mustache.js/issues/548 +[#553]: https://github.com/janl/mustache.js/issues/553 +[#560]: https://github.com/janl/mustache.js/issues/560 +[#569]: https://github.com/janl/mustache.js/issues/569 +[#580]: https://github.com/janl/mustache.js/issues/580 +[#592]: https://github.com/janl/mustache.js/issues/592 +[#593]: https://github.com/janl/mustache.js/issues/593 +[#597]: https://github.com/janl/mustache.js/issues/597 +[#610]: https://github.com/janl/mustache.js/issues/610 +[#643]: https://github.com/janl/mustache.js/issues/643 +[#644]: https://github.com/janl/mustache.js/issues/644 +[#657]: https://github.com/janl/mustache.js/issues/657 +[#664]: https://github.com/janl/mustache.js/issues/664 +[#666]: https://github.com/janl/mustache.js/issues/666 +[#667]: https://github.com/janl/mustache.js/issues/667 +[#668]: https://github.com/janl/mustache.js/issues/668 +[#670]: https://github.com/janl/mustache.js/issues/670 +[#618]: https://github.com/janl/mustache.js/issues/618 +[#673]: https://github.com/janl/mustache.js/issues/673 +[#679]: https://github.com/janl/mustache.js/issues/679 +[#701]: https://github.com/janl/mustache.js/issues/701 +[#704]: https://github.com/janl/mustache.js/issues/704 +[#705]: https://github.com/janl/mustache.js/issues/705 +[#713]: https://github.com/janl/mustache.js/issues/713 +[#714]: https://github.com/janl/mustache.js/issues/714 +[#716]: https://github.com/janl/mustache.js/issues/716 +[#717]: https://github.com/janl/mustache.js/issues/717 +[#728]: https://github.com/janl/mustache.js/issues/728 +[#733]: https://github.com/janl/mustache.js/issues/733 +[#731]: https://github.com/janl/mustache.js/issues/731 +[#735]: https://github.com/janl/mustache.js/issues/735 +[#739]: https://github.com/janl/mustache.js/issues/739 +[#764]: https://github.com/janl/mustache.js/issues/764 +[#773]: https://github.com/janl/mustache.js/issues/773 + +[@afc163]: https://github.com/afc163 +[@aielo]: https://github.com/aielo +[@andersk]: https://github.com/andersk +[@Andersos]: https://github.com/Andersos +[@AndrewLeedham]: https://github.com/AndrewLeedham +[@bbrooks]: https://github.com/bbrooks +[@calvinf]: https://github.com/calvinf +[@cmbuckley]: https://github.com/cmbuckley +[@cweider]: https://github.com/cweider +[@dasilvacontin]: https://github.com/dasilvacontin +[@djchie]: https://github.com/djchie +[@eobrain]: https://github.com/eobrain +[@EvanLovely]: https://github.com/EvanLovely +[@fallenice]: https://github.com/fallenice +[@Flaque]: https://github.com/Flaque +[@guybedford]: https://github.com/guybedford +[@imagentleman]: https://github.com/imagentleman +[@JEStaubach]: https://github.com/JEStaubach +[@jfmercer]: https://github.com/jfmercer +[@jrburke]: https://github.com/jrburke +[@kannix]: https://github.com/kannix +[@keirog]: https://github.com/keirog +[@kkirsche]: https://github.com/kkirsche +[@kookookchoozeus]: https://github.com/kookookchoozeus +[@kristijanmatic]: https://github.com/kristijanmatic +[@kevindew]: https://github.com/kevindew +[@manzt]: https://github.com/manzt +[@mateusortiz]: https://github.com/mateusortiz +[@mightyplow]: https://github.com/mightyplow +[@mikesherov]: https://github.com/mikesherov +[@mjackson]: https://github.com/mjackson +[@mortonfox]: https://github.com/mortonfox +[@nagaozen]: https://github.com/nagaozen +[@norfish]: https://github.com/norfish +[@palkan]: https://github.com/palkan +[@paultopia]: https://github.com/paultopia +[@pgilad]: https://github.com/pgilad +[@phillipj]: https://github.com/phillipj +[@pineapplemachine]: https://github.com/pineapplemachine +[@pra85]: https://github.com/pra85 +[@raymond-lam]: https://github.com/raymond-lam +[@seminaoki]: https://github.com/seminaoki +[@ShashankaNataraj]: https://github.com/ShashankaNataraj +[@simast]: https://github.com/simast +[@stackchain]: https://github.com/stackchain +[@TiddoLangerak]: https://github.com/TiddoLangerak +[@tomekwi]: https://github.com/tomekwi +[@wizawu]: https://github.com/wizawu +[@wol-soft]: https://github.com/wol-soft +[@Xcrucifier]: https://github.com/Xcrucifier +[@yotammadem]: https://github.com/yotammadem +[@yousefcisco]: https://github.com/yousefcisco +[@zekth]: https://github.com/zekth diff --git a/node_modules/mustache/LICENSE b/node_modules/mustache/LICENSE new file mode 100644 index 0000000..4df7d1a --- /dev/null +++ b/node_modules/mustache/LICENSE @@ -0,0 +1,11 @@ +The MIT License + +Copyright (c) 2009 Chris Wanstrath (Ruby) +Copyright (c) 2010-2014 Jan Lehnardt (JavaScript) +Copyright (c) 2010-2015 The mustache.js community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mustache/README.md b/node_modules/mustache/README.md new file mode 100644 index 0000000..127dfe1 --- /dev/null +++ b/node_modules/mustache/README.md @@ -0,0 +1,621 @@ +# mustache.js - Logic-less {{mustache}} templates with JavaScript + +> What could be more logical awesome than no logic at all? + +[![Build Status](https://travis-ci.org/janl/mustache.js.svg?branch=master)](https://travis-ci.org/janl/mustache.js) + +[mustache.js](http://github.com/janl/mustache.js) is a zero-dependency implementation of the [mustache](http://mustache.github.com/) template system in JavaScript. + +[Mustache](http://mustache.github.com/) is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. + +We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values. + +For a language-agnostic overview of mustache's template syntax, see the `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html). + +## Where to use mustache.js? + +You can use mustache.js to render mustache templates anywhere you can use JavaScript. This includes web browsers, server-side environments such as [Node.js](http://nodejs.org/), and [CouchDB](http://couchdb.apache.org/) views. + +mustache.js ships with support for the [CommonJS](http://www.commonjs.org/) module API, the [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) API (AMD) and [ECMAScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). + +In addition to being a package to be used programmatically, you can use it as a [command line tool](#command-line-tool). + +And this will be your templates after you use Mustache: + +!['stache](https://cloud.githubusercontent.com/assets/288977/8779228/a3cf700e-2f02-11e5-869a-300312fb7a00.gif) + +## Install + +You can get Mustache via [npm](http://npmjs.com). + +```bash +$ npm install mustache --save +``` + +## Usage + +Below is a quick example how to use mustache.js: + +```js +var view = { + title: "Joe", + calc: function () { + return 2 + 4; + } +}; + +var output = Mustache.render("{{title}} spends {{calc}}", view); +``` + +In this example, the `Mustache.render` function takes two parameters: 1) the [mustache](http://mustache.github.com/) template and 2) a `view` object that contains the data and code needed to render the template. + +## Templates + +A [mustache](http://mustache.github.com/) template is a string that contains any number of mustache tags. Tags are indicated by the double mustaches that surround them. `{{person}}` is a tag, as is `{{#person}}`. In both examples we refer to `person` as the tag's key. There are several types of tags available in mustache.js, described below. + +There are several techniques that can be used to load templates and hand them to mustache.js, here are two of them: + +#### Include Templates + +If you need a template for a dynamic part in a static website, you can consider including the template in the static HTML file to avoid loading templates separately. Here's a small example: + +```js +// file: render.js + +function renderHello() { + var template = document.getElementById('template').innerHTML; + var rendered = Mustache.render(template, { name: 'Luke' }); + document.getElementById('target').innerHTML = rendered; +} +``` + +```html + + +

Loading...
+ + + + + + +``` + +#### Load External Templates + +If your templates reside in individual files, you can load them asynchronously and render them when they arrive. Another example using [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch): + +```js +function renderHello() { + fetch('template.mustache') + .then((response) => response.text()) + .then((template) => { + var rendered = Mustache.render(template, { name: 'Luke' }); + document.getElementById('target').innerHTML = rendered; + }); +} +``` + +### Variables + +The most basic tag type is a simple variable. A `{{name}}` tag renders the value of the `name` key in the current context. If there is no such key, nothing is rendered. + +All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: `{{{name}}}`. You can also use `&` to unescape a variable. + +If you'd like to change HTML-escaping behavior globally (for example, to template non-HTML formats), you can override Mustache's escape function. For example, to disable all escaping: `Mustache.escape = function(text) {return text;};`. + +If you want `{{name}}` _not_ to be interpreted as a mustache tag, but rather to appear exactly as `{{name}}` in the output, you must change and then restore the default delimiter. See the [Custom Delimiters](#custom-delimiters) section for more information. + +View: + +```json +{ + "name": "Chris", + "company": "GitHub" +} +``` + +Template: + +``` +* {{name}} +* {{age}} +* {{company}} +* {{{company}}} +* {{&company}} +{{=<% %>=}} +* {{company}} +<%={{ }}=%> +``` + +Output: + +```html +* Chris +* +* <b>GitHub</b> +* GitHub +* GitHub +* {{company}} +``` + +JavaScript's dot notation may be used to access keys that are properties of objects in a view. + +View: + +```json +{ + "name": { + "first": "Michael", + "last": "Jackson" + }, + "age": "RIP" +} +``` + +Template: + +```html +* {{name.first}} {{name.last}} +* {{age}} +``` + +Output: + +```html +* Michael Jackson +* RIP +``` + +### Sections + +Sections render blocks of text zero or more times, depending on the value of the key in the current context. + +A section begins with a pound and ends with a slash. That is, `{{#person}}` begins a `person` section, while `{{/person}}` ends it. The text between the two tags is referred to as that section's "block". + +The behavior of the section is determined by the value of the key. + +#### False Values or Empty Lists + +If the `person` key does not exist, or exists and has a value of `null`, `undefined`, `false`, `0`, or `NaN`, or is an empty string or an empty list, the block will not be rendered. + +View: + +```json +{ + "person": false +} +``` + +Template: + +```html +Shown. +{{#person}} +Never shown! +{{/person}} +``` + +Output: + +```html +Shown. +``` + +#### Non-Empty Lists + +If the `person` key exists and is not `null`, `undefined`, or `false`, and is not an empty list the block will be rendered one or more times. + +When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections. + +View: + +```json +{ + "stooges": [ + { "name": "Moe" }, + { "name": "Larry" }, + { "name": "Curly" } + ] +} +``` + +Template: + +```html +{{#stooges}} +{{name}} +{{/stooges}} +``` + +Output: + +```html +Moe +Larry +Curly +``` + +When looping over an array of strings, a `.` can be used to refer to the current item in the list. + +View: + +```json +{ + "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] +} +``` + +Template: + +```html +{{#musketeers}} +* {{.}} +{{/musketeers}} +``` + +Output: + +```html +* Athos +* Aramis +* Porthos +* D'Artagnan +``` + +If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration. + +View: + +```js +{ + "beatles": [ + { "firstName": "John", "lastName": "Lennon" }, + { "firstName": "Paul", "lastName": "McCartney" }, + { "firstName": "George", "lastName": "Harrison" }, + { "firstName": "Ringo", "lastName": "Starr" } + ], + "name": function () { + return this.firstName + " " + this.lastName; + } +} +``` + +Template: + +```html +{{#beatles}} +* {{name}} +{{/beatles}} +``` + +Output: + +```html +* John Lennon +* Paul McCartney +* George Harrison +* Ringo Starr +``` + +#### Functions + +If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object. + +View: + +```js +{ + "name": "Tater", + "bold": function () { + return function (text, render) { + return "" + render(text) + ""; + } + } +} +``` + +Template: + +```html +{{#bold}}Hi {{name}}.{{/bold}} +``` + +Output: + +```html +Hi Tater. +``` + +### Inverted Sections + +An inverted section opens with `{{^section}}` instead of `{{#section}}`. The block of an inverted section is rendered only if the value of that section's tag is `null`, `undefined`, `false`, *falsy* or an empty list. + +View: + +```json +{ + "repos": [] +} +``` + +Template: + +```html +{{#repos}}{{name}}{{/repos}} +{{^repos}}No repos :({{/repos}} +``` + +Output: + +```html +No repos :( +``` + +### Comments + +Comments begin with a bang and are ignored. The following template: + +```html +

Today{{! ignore me }}.

+``` + +Will render as follows: + +```html +

Today.

+``` + +Comments may contain newlines. + +### Partials + +Partials begin with a greater than sign, like {{> box}}. + +Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops. + +They also inherit the calling context. Whereas in ERB you may have this: + +```html+erb +<%= partial :next_more, :start => start, :size => size %> +``` + +Mustache requires only this: + +```html +{{> next_more}} +``` + +Why? Because the `next_more.mustache` file will inherit the `size` and `start` variables from the calling context. In this way you may want to think of partials as includes, imports, template expansion, nested templates, or subtemplates, even though those aren't literally the case here. + + +For example, this template and partial: + + base.mustache: +

Names

+ {{#names}} + {{> user}} + {{/names}} + + user.mustache: + {{name}} + +Can be thought of as a single, expanded template: + +```html +

Names

+{{#names}} + {{name}} +{{/names}} +``` + +In mustache.js an object of partials may be passed as the third argument to `Mustache.render`. The object should be keyed by the name of the partial, and its value should be the partial text. + +```js +Mustache.render(template, view, { + user: userTemplate +}); +``` + +### Custom Delimiters + +Custom delimiters can be used in place of `{{` and `}}` by setting the new values in JavaScript or in templates. + +#### Setting in JavaScript + +The `Mustache.tags` property holds an array consisting of the opening and closing tag values. Set custom values by passing a new array of tags to `render()`, which gets honored over the default values, or by overriding the `Mustache.tags` property itself: + +```js +var customTags = [ '<%', '%>' ]; +``` + +##### Pass Value into Render Method +```js +Mustache.render(template, view, {}, customTags); +``` + +##### Override Tags Property +```js +Mustache.tags = customTags; +// Subsequent parse() and render() calls will use customTags +``` + +#### Setting in Templates + +Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings. + +Consider the following contrived example: + +```html+erb +* {{ default_tags }} +{{=<% %>=}} +* <% erb_style_tags %> +<%={{ }}=%> +* {{ default_tags_again }} +``` + +Here we have a list with three items. The first item uses the default tag style, the second uses ERB style as defined by the Set Delimiter tag, and the third returns to the default style after yet another Set Delimiter declaration. + +According to [ctemplates](https://htmlpreview.github.io/?https://raw.githubusercontent.com/OlafvdSpek/ctemplate/master/doc/howto.html), this "is useful for languages like TeX, where double-braces may occur in the text and are awkward to use for markup." + +Custom delimiters may not contain whitespace or the equals sign. + +## Pre-parsing and Caching Templates + +By default, when mustache.js first parses a template it keeps the full parsed token tree in a cache. The next time it sees that same template it skips the parsing step and renders the template much more quickly. If you'd like, you can do this ahead of time using `mustache.parse`. + +```js +Mustache.parse(template); + +// Then, sometime later. +Mustache.render(template, view); +``` + +## Command line tool + +mustache.js is shipped with a Node.js based command line tool. It might be installed as a global tool on your computer to render a mustache template of some kind + +```bash +$ npm install -g mustache + +$ mustache dataView.json myTemplate.mustache > output.html +``` + +also supports stdin. + +```bash +$ cat dataView.json | mustache - myTemplate.mustache > output.html +``` + +or as a package.json `devDependency` in a build process maybe? + +```bash +$ npm install mustache --save-dev +``` + +```json +{ + "scripts": { + "build": "mustache dataView.json myTemplate.mustache > public/output.html" + } +} +``` +```bash +$ npm run build +``` + +The command line tool is basically a wrapper around `Mustache.render` so you get all the features. + +If your templates use partials you should pass paths to partials using `-p` flag: + +```bash +$ mustache -p path/to/partial1.mustache -p path/to/partial2.mustache dataView.json myTemplate.mustache +``` + +## Plugins for JavaScript Libraries + +mustache.js may be built specifically for several different client libraries, including the following: + + - [jQuery](http://jquery.com/) + - [MooTools](http://mootools.net/) + - [Dojo](http://www.dojotoolkit.org/) + - [YUI](http://developer.yahoo.com/yui/) + - [qooxdoo](http://qooxdoo.org/) + +These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands: +```bash +$ rake jquery +$ rake mootools +$ rake dojo +$ rake yui3 +$ rake qooxdoo +``` + +## TypeScript + +Since the source code of this package is written in JavaScript, we follow the [TypeScript publishing docs](https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) preferred approach +by having type definitions available via [@types/mustache](https://www.npmjs.com/package/@types/mustache). + +## Testing + +In order to run the tests you'll need to install [Node.js](http://nodejs.org/). + +You also need to install the sub module containing [Mustache specifications](http://github.com/mustache/spec) in the project root. +```bash +$ git submodule init +$ git submodule update +``` +Install dependencies. +```bash +$ npm install +``` +Then run the tests. +```bash +$ npm test +``` +The test suite consists of both unit and integration tests. If a template isn't rendering correctly for you, you can make a test for it by doing the following: + + 1. Create a template file named `mytest.mustache` in the `test/_files` + directory. Replace `mytest` with the name of your test. + 2. Create a corresponding view file named `mytest.js` in the same directory. + This file should contain a JavaScript object literal enclosed in + parentheses. See any of the other view files for an example. + 3. Create a file with the expected output in `mytest.txt` in the same + directory. + +Then, you can run the test with: +```bash +$ TEST=mytest npm run test-render +``` + +### Browser tests + +Browser tests are not included in `npm test` as they run for too long, although they are ran automatically on Travis when merged into master. Run browser tests locally in any browser: +```bash +$ npm run test-browser-local +``` +then point your browser to `http://localhost:8080/__zuul` + +## Who uses mustache.js? + +An updated list of mustache.js users is kept [on the Github wiki](https://github.com/janl/mustache.js/wiki/Beard-Competition). Add yourself or your company if you use mustache.js! + +## Contributing + +mustache.js is a mature project, but it continues to actively invite maintainers. You can help out a high-profile project that is used in a lot of places on the web. No big commitment required, if all you do is review a single [Pull Request](https://github.com/janl/mustache.js/pulls), you are a maintainer. And a hero. + +### Your First Contribution + +- review a [Pull Request](https://github.com/janl/mustache.js/pulls) +- fix an [Issue](https://github.com/janl/mustache.js/issues) +- update the [documentation](https://github.com/janl/mustache.js#usage) +- make a website +- write a tutorial + +## Thanks + +mustache.js wouldn't kick ass if it weren't for these fine souls: + + * Chris Wanstrath / defunkt + * Alexander Lang / langalex + * Sebastian Cohnen / tisba + * J Chris Anderson / jchris + * Tom Robinson / tlrobinson + * Aaron Quint / quirkey + * Douglas Crockford + * Nikita Vasilyev / NV + * Elise Wood / glytch + * Damien Mathieu / dmathieu + * Jakub Kuźma / qoobaa + * Will Leinweber / will + * dpree + * Jason Smith / jhs + * Aaron Gibralter / agibralter + * Ross Boucher / boucher + * Matt Sanford / mzsanford + * Ben Cherry / bcherry + * Michael Jackson / mjackson + * Phillip Johnsen / phillipj + * David da Silva Contín / dasilvacontin diff --git a/node_modules/mustache/bin/mustache b/node_modules/mustache/bin/mustache new file mode 100644 index 0000000..6db073f --- /dev/null +++ b/node_modules/mustache/bin/mustache @@ -0,0 +1,150 @@ +#!/usr/bin/env node + +var fs = require('fs'), + path = require('path'); + +var Mustache = require('..'); +var pkg = require('../package'); +var partials = {}; + +var partialsPaths = []; +var partialArgIndex = -1; + +while ((partialArgIndex = process.argv.indexOf('-p')) > -1) { + partialsPaths.push(process.argv.splice(partialArgIndex, 2)[1]); +} + +var viewArg = process.argv[2]; +var templateArg = process.argv[3]; +var outputArg = process.argv[4]; + +if (hasVersionArg()) { + return console.log(pkg.version); +} + +if (!templateArg || !viewArg) { + console.error('Syntax: mustache